Trying to use PdfStamper and MemoryStream to add data to existing PDF then email it

﹥>﹥吖頭↗ 提交于 2019-12-12 03:38:40

问题


Here is my chunk of code. It compiles fine and when I fire off the event I get the email, but I then get this error Email attachment ERROR on Adobe while opening(Acrobat could not open 'Att00002.pdf' because it is either not a supported file type or because the file has been damaged(for example, it was sent as an email attachment and wasnt correctly decoded.)

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

EDITED *************************************

        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:


You're calling stamper.close() inside the using (PdfStamper stamper = new PdfStamper(reader, _output)). The using will automatically close the stamper upon exiting it in addition to your manual close(), so technically the stamper is trying to be closed twice. Because of this it is also trying to close the MemoryStream more than once. That's where the exception is coming from.

I would use the technique located in the answer here for your MemoryStream and PdfStamper (modified and taken from: Getting PdfStamper to work with MemoryStreams (c#, itextsharp)):

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


来源:https://stackoverflow.com/questions/33107703/trying-to-use-pdfstamper-and-memorystream-to-add-data-to-existing-pdf-then-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!