tags:

views:

237

answers:

2

I've used ABDpdf to render a pdf and stream it to the browser, but I'm wondering if I can attach the rendered pdf to an email. Has anyone ever done that?

I'm hoping there is a way that doesn't require me to save the pdf to a temp directory then attach the file, then delete it.

+2  A: 

According to the documentation on the ABCpdf PDF support site, there is an overload of the Doc() object that supports saving to a stream. With this feature, you can save the results a generated PDF without explicitly writing to disk by using the MemoryStream class.

ABCpdf PDF Component for .NET : Doc.Save()
MemoryStream (System.IO) @ MSDN

With a MemoryStream created, you may then pass the stream on to any email provider that supports creating attachments from a stream. MailMessage in System.Net.Mail has support for this.

MailMessage Class (System.Net.Mail) @ MSDN
MailMessage.Attachments Property @ MSDN
Attachments Class @ MSDN
Attachments Constructor @ MSDN

Finally, if you've never used the MailMessage class before, use the SmtpClient class to send your message on its way.

SmtpClient Class (System.Net.Mail)

meklarian
+3  A: 

Meklarian is right, but one little thing to point out, is that after you've saved the pdf into your stream, you will want to reset your stream position back to 0. Otherwise the attachment that is sent will be all foo-barred.

(It took me about two hours to figure it out. Ouch. Hope to help someone else save some time.)

    //Create the pdf doc
    Doc theDoc = new Doc();
    theDoc.FontSize = 12;
    theDoc.AddText("Hello, World!");

    //Save it to the Stream
    Stream pdf = new MemoryStream();
    theDoc.Save(pdf);
    theDoc.Clear();

    //Important to reset back to the begining of the stream!!!
    pdf.Position = 0; 

    //Send the message
    MailMessage msg = new MailMessage();
    msg.To.Add("[email protected]");
    msg.From = new MailAddress("[email protected]");
    msg.Subject = "Hello";
    msg.Body = "World";
    msg.Attachments.Add(new Attachment(pdf, "MyPDF.pdf", "application/pdf"));
    SmtpClient smtp = new SmtpClient("smtp.yourserver.com");
    smtp.Send(msg);
KennyJacobson
+1... I forget to reset stream position in other scenarios as well.
meklarian