我使用PDF Sharp库创建自定义PDF。我希望能够将此自定义PDF作为附件通过电子邮件发送,而无需先保存本地副本。我试图实现这一点的方法是将生成的PDF Sharp文档转换为字节数组,如下所示:
byte[] pdfBuffer = null;
using (MemoryStream ms = new MemoryStream())
{
document.Save(ms, false);
pdfBuffer = ms.ToArray();
}
这部分似乎正在工作,但是我遇到问题的部分是将字节数组转换回PDF文件。使用下面的代码将PDF附加到电子邮件中,但是当附件打开时,它是一个空白文件。这是我用来做的代码:
//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);
有人可以解释一下将PDF流转换回有效PDF并发送电子邮件附件的正确方法吗?
答案 0 :(得分:6)
当我将流转换回PDF时文档显示为空白的原因是,在使用document.Save(memoryStream, false);
时,必须在之后调用document.Close();
,即:
document.Save(memoryStream, false);
document.Close();
答案 1 :(得分:0)
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);