Question

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?

Was it helpful?

Solution

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();

OTHER TIPS

            WebClient User = new WebClient();
            Byte[] FileBuffer = User.DownloadData(strPDFPath);
            Stream stream = new MemoryStream(FileBuffer);
            ContentType ct = new ContentType(MediaTypeNames.Application.Pdf);
            pdf = new Attachment(stream, ct);
            pdf.ContentType.MediaType = MediaTypeNames.Application.Pdf;
            msg.Attachments.Add(pdf);
            pdf.ContentType.Name = Path.GetFileName(strPDFPath);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top