Free Support Forum - aspose.com

Add attachement from a byte-array or stream

Hi,

I'm just trying the trial version of aspose.pdf and I want to add an attachement to a new pdf-file. Everything works fine using the Generator.Attachement()-class and selecting a file from a local folder as described in the knowledge base.

for example:
fileAttachment.AttachedFileName = "c:\test.jpg"

But I've stored the files in a BLOB in the database. So, I don't want to save them to the machine and after that add them to the pdf.

Is it possible to add a byte()-Array as an attachment to the pdf?

Regards,
Michael

Hi Michael,

Thank you for considering Aspose.Pdf.

I think you can use Attachment.AttachedStream API and see if it fits your requirement. You can create your ByteArray to a MemoryStream and attach it to the pdf file. Please see the following sample code in this regard:<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

//Instantiate Pdf instance by calling its empty constructor

Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

//Add a section into the pdf document

Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add();

//Instantiate attachment instance by calling its empty constructor

Aspose.Pdf.Generator.Attachment fileAttachment = new Aspose.Pdf.Generator.Attachment();

//Add attachment in the paragraphs collection of the section

sec1.Paragraphs.Add(fileAttachment);

//Set attachment type to File using AttachmentType enumeration

fileAttachment.AttachmentType = Aspose.Pdf.Generator.AttachmentType.File;

//Set the path of the attachment file

fileAttachment.AttachedFileName = "Result.png";

// Create a FileStream object to read the imag file

FileStream fs = File.OpenRead(@"E:\AP DATA\Source_Files\Result.png");

// Read the image into Byte array (You can use the code here onwards)

byte[] data = new byte[fs.Length];

fs.Read(data, 0, data.Length);

// Create a MemoryStream object from image Byte array

MemoryStream ms = new MemoryStream(data);

fileAttachment.AttachedStream = ms;

//Set the type of the file to be attached

fileAttachment.AttachedFileType = "png";

pdf1.Save(@"E:\AP DATA\Source_Files\Attachment_Test.pdf");

Please do let us know if this fits your requirement or not.

Thank You & Best Regards,

Hi,

thanks for your answer.
That's exactly what I'm searching for.

Regards,
Michael