问题描述
这是我的一大堆代码。它编译得很好,当我发起事件时我收到了电子邮件,但是我得到了这个错误
电子邮件附件错误在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("[email protected]", "[email protected]", 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);
}
推荐答案
您正在拨打 stamper.close()
在内使用(PdfStamper压模=新PdfStamper(reader,_output))
。除了手动关闭()之外,使用
将在退出时自动关闭压模,因此从技术上讲,压模试图关闭两次。因此,它也试图不止一次关闭 MemoryStream
。这就是异常的来源。
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.
我会在这里使用你的 MemoryStream
的答案中的技巧 PdfStamper
(已修改并取自:):
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
}
}
这篇关于尝试使用PdfStamper和MemoryStream将数据添加到现有PDF然后通过电子邮件发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!