iTextSharp使用Memorystream将PDF作为附件发送
本文关键字:使用 Memorystream PDF iTextSharp | 更新日期: 2023-09-27 17:58:54
一直在努力解决这个问题,并且已经非常接近了,但还没有达到。我正在尝试使用iTextSharp V 4.1.2发送PDF作为电子邮件附件。我在下面提供的代码同时使用了文件流和内存流,文件流是为了向自己证明PDF模板上有数据(确实如此)。此外,我收到了电子邮件,但没有附件。有人能看到我缺了什么吗?
public class BasePDFController : BaseController
{protected ActionResult eMailPdf(对象模型){string pdf=路径。Combine(Server.MapPath("~/Instructure/PDFTemplates/fw9.pdf");string outputFilePath=@"C:''Projects''Temp''test_template_filled.pdf";
MemoryStream memoryStream = new MemoryStream();
PdfReader pdfFileReader = null;
PdfReader pdfMemoryReader = null;
try
{
pdfFileReader = new PdfReader(pdf);
pdfMemoryReader = new PdfReader(pdf);
using (FileStream pdfOutputFile = new FileStream(outputFilePath, FileMode.Create))
{
PdfStamper pdfFileStamper = null;
PdfStamper pdfMemoryStamper = null;
try
{
pdfFileStamper = new PdfStamper(pdfFileReader, pdfOutputFile);
pdfMemoryStamper = new PdfStamper(pdfMemoryReader, memoryStream);
AcroFields acroFileFields = pdfFileStamper.AcroFields;
AcroFields acroMemoryFields = pdfMemoryStamper.AcroFields;
acroFileFields.SetField("topmostSubform[0].Page1[0].f1_01_0_[0]", "Batman");
pdfFileStamper.FormFlattening = true;
pdfMemoryStamper.FormFlattening = true;
pdfMemoryStamper.Writer.CloseStream = false;
if (pdfMemoryStamper != null)
{
pdfMemoryStamper.Close();
}
memoryStream.Position = 0;
EmailProvider.Email email = new EmailProvider.Email();
email = new EmailProvider.Email
{
To = "someone@gamil.net",
Subject = "Scholars Attached PDF",
Body = "A PDF!",
Attachment = new Attachment(memoryStream, new System.Net.Mime.ContentType("application/pdf"))
};
EmailProvider.SendEmail(email);
}
finally
{
if (pdfFileStamper != null)
{
pdfFileStamper.Close();
}
}
}
}
finally
{
pdfFileReader.Close();
pdfMemoryReader.Close();
}
return File(outputFilePath, "application/pdf", "Returned.pdf");
}
}
编辑:-是的,邮件提供商有问题。我不知道该怎么解决,或者这是否是发送的最佳方式?写这篇文章的人显然放弃了。编辑固定了附件。
public static class EmailProvider
{
public class Email
{
public String To { get; set; }
public String Subject { get; set; }
public String Body { get; set; }
**public Attachment Attachment { get; set; }**
}
public static void SendEmail(Email email)
{
MailMessage mail = new MailMessage();
mail.To.Add(email.To);
mail.Subject = email.Subject;
mail.Body = email.Body;
mail.IsBodyHtml = true;
mail.Attachments.Add(email.Attachment);
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
}
}
电子邮件修复后,我收到了PDF!然而,当我尝试从电子邮件打开PDF时,我会收到一个错误:打开此文档时出错。文件已损坏,无法修复。想法?
您应该在pdfMemoryStamper.Writer.CloseStream = false;
之后调用pdfMemoryStamper.Close()
像这样:
// *snip*
pdfFileStamper.FormFlattening = true;
pdfMemoryStamper.FormFlattening = true;
pdfMemoryStamper.Writer.CloseStream = false;
pdfMemoryStamper.Close();
memoryStream.Position = 0;
// *snip*