Tuesday, July 28, 2009

iTextSharp - Sending in-memory pdf in an email attachment

I was helping a client with the good old task of printing reports in a pdf format from an Asp.Net page, without having to use a commercial tool. I did a bit of research on iTextSharp and it appears to do everything I need. For instance, one of my goals was to be able to create a pdf file in memory and send it as an email attachment. Here's the code I used to do that:
(In this example I use gmail as my smtp server, so it makes it easier for you to try it for yourself)

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

//Keeps the memoryStream object open when closing the Document (doc)
writer.CloseStream = false;
doc.Close();

//Moves the pointer to the beginning of the stream. Without this
//line an empty file is generated and attached to the email.
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);