Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte[] to PDF Sharp Document and Email as Attachment

I am using the PDF Sharp library to create a custom PDF. I want to be able to email this custom PDF as an attachment without saving a local copy first. The way I am trying to achieve this is by converting the generated PDF Sharp document to a byte array as follows:

byte[] pdfBuffer = null;

using (MemoryStream ms = new MemoryStream())
{
  document.Save(ms, false);

  pdfBuffer = ms.ToArray();
}

This part seems to be working, however the part I am hving problems with is converting the byte array back a PDF file. With the code below the PDF is being attached to the email but when the attachment is opened it is a blank file. This is the code I am using to do that:

//Add PDF attachment.
Stream stream = new MemoryStream(attachmentData);

mailMessage.Attachments.Add(new Attachment(stream, attachmentFilename, "application/pdf"));

//Setup up SMTP details.
smtpClient = new SmtpClient("************.com");
smtpUserInfo = new System.Net.NetworkCredential("****@****.com", "*****", "*****.com");
smtpClient.Credentials = smtpUserInfo;
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

//Send the email.
smtpClient.Send(mailMessage);

Can anyone please explain a correct way of converting the PDF stream back to a valid PDF and send is an email attachment?

like image 540
636f6465 Avatar asked May 12 '14 11:05

636f6465


Video Answer


1 Answers

The reason the document was appearing blank when I converted the stream back to a PDF is that when using document.Save(memoryStream, false);, it is neccessary to call document.Close(); after, i.e.:

document.Save(memoryStream, false);
document.Close();
like image 140
636f6465 Avatar answered Sep 19 '22 09:09

636f6465