iTextSharp - 在电子邮件附件中发送内存中的pdf

Gus*_*nti 97 c# pdf email itextsharp

我在这里问过几个问题,但我仍然遇到问题.如果你能在我的代码中告诉我我做错了什么,我将不胜感激.我从ASP.Net页面运行上面的代码并获得"无法访问封闭的流".

var doc = new Document();

MemoryStream memoryStream = new MemoryStream();

PdfWriter.GetInstance(doc, memoryStream);
doc.Open();
doc.Add(new Paragraph("First Paragraph"));
doc.Add(new Paragraph("Second Paragraph"));

doc.Close(); //if I remove this line the email attachment is sent but with 0 bytes 

MailMessage mm = new MailMessage("username@gmail.com", "username@gmail.com")
{
    Subject = "subject",
    IsBodyHtml = true,
    Body = "body"
};

mm.Attachments.Add(new Attachment(memoryStream, "test.pdf"));
SmtpClient smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    Credentials = new NetworkCredential("username@gmail.com", "my_password")
};

smtp.Send(mm); //the "Cannot Access a Closed Stream" error is thrown here
Run Code Online (Sandbox Code Playgroud)

谢谢!!!

编辑:

只是为了帮助某人寻找这个问题的答案,发送附加到电子邮件的pdf文件而不必实际创建文件的代码如下(感谢Ichiban和Brianng):

var doc = new Document();
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);

doc.Open();
doc.Add(new Paragraph("First Paragraph"));
doc.Add(new Paragraph("Second Paragraph"));

writer.CloseStream = false;
doc.Close();
memoryStream.Position = 0;

MailMessage mm = new MailMessage("username@gmail.com", "username@gmail.com")
{
    Subject = "subject",
    IsBodyHtml = true,
    Body = "body"
};

mm.Attachments.Add(new Attachment(memoryStream, "filename.pdf"));
SmtpClient smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    Credentials = new NetworkCredential("username@gmail.com", "password")

};

smtp.Send(mm);
Run Code Online (Sandbox Code Playgroud)

bri*_*nng 79

你有没有尝试过:

PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);

// Build pdf code...

writer.CloseStream = false;
doc.Close();

// Build email

memoryStream.Position = 0;
mm.Attachments.Add(new Attachment(memoryStream, "test.pdf"));
Run Code Online (Sandbox Code Playgroud)

如果我的记忆正确地为我服务,这解决了之前项目中的类似问题.

http://forums.asp.net/t/1093198.aspx


ich*_*ban 18

我尝试了brianng发布的代码并且有效.只需将代码顶部更改为:

var doc = new Document();
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream); //capture the object
doc.Open();
doc.Add(new Paragraph("First Paragraph"));
doc.Add(new Paragraph("Second Paragraph"));
writer.CloseStream = false; //set the closestream property
doc.close(); //close the document without closing the underlying stream
memoryStream.Position = 0;

/* remainder of your code stays the same*/
Run Code Online (Sandbox Code Playgroud)

  • 感谢您抽出宝贵时间进行验证! (3认同)
  • @Gustavo,该文件在Acrobat查看器中正确打开.它大约是900字节.确保你保留行:memoryStream.Position = 0; 在doc.Close()之后.我忘了提到那个.(见上面的更新) (2认同)