program tip

iTextSharp-이메일 첨부 파일로 메모리 내 PDF 보내기

radiobox 2020. 8. 24. 08:01
반응형

iTextSharp-이메일 첨부 파일로 메모리 내 PDF 보내기


여기서 몇 가지 질문을했지만 여전히 문제가 있습니다. 내 코드에서 내가 뭘 잘못하고 있는지 말해 주시면 감사하겠습니다. 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

감사!!!

편집하다:

이 질문에 대한 답을 찾는 사람을 돕기 위해 파일을 물리적으로 만들지 않고도 이메일에 첨부 된 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);

시도해 보셨습니까?

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

내 기억이 제대로 작동한다면 이전 프로젝트에서 비슷한 문제가 해결되었습니다.

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


나는 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*/

Can you flush the document or memory stream and then close it after you attach it?


Probably calling doc.Close() Disposes the underlying stream. Try removing doc.Close() and instead of that line set memoryStream.Position = 0;

Alternatively you can use a temp file:

var tempFilePath = Path.GetTempFileName();

try 
{           
    var doc = new Document();

    PdfWriter.GetInstance(doc, File.OpenWrite(tempFilePath));
    doc.Open();
    doc.Add(new Paragraph("First Paragraph"));
    doc.Add(new Paragraph("Second Paragraph"));

    doc.Close();

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

    mm.Attachments.Add(new Attachment(tempFilePath, "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);
}
finally
{
    File.Delete(tempFilePath);
}

I had the same problem and I used this post to solve it.In the code written by brianng

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

I think instead of writing

writer.CloseStream = false and memoryStream.Position = 0;

Just create a new Stream

MemoryStream m = new MemoryStream(memoryStream);

and then call

mm.Attachments.Add(new Attachment(memoryStream, "test.pdf"));

Both work but I think it is better to create the new stream

참고URL : https://stackoverflow.com/questions/1196059/itextsharp-sending-in-memory-pdf-in-an-email-attachment

반응형