简体   繁体   English

将byte []转换为PDF Sharp Document和Email as Attachment

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

I am using the PDF Sharp library to create a custom PDF. 我正在使用PDF Sharp库来创建自定义PDF。 I want to be able to email this custom PDF as an attachment without saving a local copy first. 我希望能够将此自定义PDF作为附件通过电子邮件发送,而无需先保存本地副本。 The way I am trying to achieve this is by converting the generated PDF Sharp document to a byte array as follows: 我试图实现这一点的方法是将生成的PDF Sharp文档转换为字节数组,如下所示:

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. 这部分似乎正在工作,但是我遇到问题的部分是将字节数组转换回PDF文件。 With the code below the PDF is being attached to the email but when the attachment is opened it is a blank file. 使用下面的代码将PDF附加到电子邮件中,但是当附件打开时,它是一个空白文件。 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? 任何人都可以解释一种正确的方法将PDF流转换回有效的PDF并发送是一个电子邮件附件?

The reason the document was appearing blank when I converted the stream back to a PDF is that when using document.Save(memoryStream, false); 当我将流转换回PDF时文档显示为空白的原因是当使用document.Save(memoryStream, false); , it is neccessary to call document.Close(); ,有必要调用document.Close(); after, ie: 之后,即:

document.Save(memoryStream, false);
document.Close();
            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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM