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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With