尝试使用PdfStamper和MemoryStream将数据添加到现有PDF,然后通过电子邮件发送

时间:2015-10-13 16:17:04

标签: c# adobe itextsharp memorystream pdfstamper

这是我的一大堆代码。它编译得很好,当我发起事件时,我收到了电子邮件,但我得到了这个错误 打开时,Adobe上的电子邮件附件错误(Acrobat无法打开'Att00002.pdf',因为它不是受支持的文件类型,或者因为文件已损坏(例如,它是作为电子邮件附件发送的,并且未正确解码。)

string agentName = "My Name";            
MemoryStream _output = new MemoryStream();
            PdfReader reader = new PdfReader("/pdf/Agent/Specialist_Certificate.pdf");
            using (PdfStamper stamper = new PdfStamper(reader, _output))
            {
                AcroFields fields = stamper.AcroFields;
            // set form fields
            fields.SetField("FIELD_AGENT_NAME", agentName);
            fields.SetField("FIELD_DATE", AvalonDate);

            // flatten form fields and close document
            stamper.FormFlattening = true;
            SendEmail(_output);
            DownloadAsPDF(_output);
            stamper.Close();
        }

private void SendEmail(MemoryStream ms)
{
    Attachment attach = new Attachment(ms, new System.Net.Mime.ContentType("application/pdf"));
    EmailHelper.SendEMail("myemail@myemail.com", "mjones@globusfamily.com", null, "", "Avalon Cert", "Hope this works", EmailHelper.EmailFormat.Html,attach);
}

已编辑*************************************

        using (MemoryStream _output = new MemoryStream())
        {
            using (PdfStamper stamper = new PdfStamper(reader, _output))
            {
                AcroFields fields = stamper.AcroFields;
                // set form fields
                fields.SetField("FIELD_AGENT_NAME", agentName);
                fields.SetField("FIELD_DATE", AvalonDate);

                // flatten form fields and close document
                stamper.FormFlattening = true;
            }
            SendEmail(_output);
        }

1 个答案:

答案 0 :(得分:3)

您在stamper.close()内呼叫using (PdfStamper stamper = new PdfStamper(reader, _output))。除了手动关闭()之外,using将在退出时自动关闭压模,因此从技术上讲,压模试图关闭两次。因此,它也试图不止一次关闭MemoryStream。这就是异常的来源。

我会使用此处答案中的技巧MemoryStreamPdfStamper(已修改并取自:Getting PdfStamper to work with MemoryStreams (c#, itextsharp)):

using (MemoryStream _output = new MemoryStream()) {
  using (PdfStamper stamper = new PdfStamper(reader, _output)) {
// do stuff      
  }    
}