Sunday, May 18, 2008

Create PDF files in memory and mail them as an attachment

In my previous post i showed how to create an PDF file on-the-fly with iTextSharp.

Now we pick up the first HELLO WORLD example and dont write it to C:\text.pdf but to a MemoryStream. After that we mail it as an attachment.

As you will see it's no rocket science!



protected void Page_Load(object sender, EventArgs e)
{
//Create document A4
Document document = new Document(PageSize.A4);
//Start the writer and write to memory
MemoryStream myStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, myStream);
//Open document
document.Open();

#region Example1
//Set some document attributes
document.AddTitle("Hello world");
document.AddAuthor("Sjoerd Perfors");
document.AddSubject("This is my first PDF created on: " + DateTime.Now.ToShortDateString());
//Add an image
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance("c:\\caesar_coin.jpg");
document.Add(image);
//Add a normal text
document.Add(new Chunk("HELLO WORLD", FontFactory.GetFont(FontFactory.HELVETICA, 18, Color.RED)));
//Add text to a specific position
PdfContentByte cb = writer.DirectContent;
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.ShowTextAligned(Element.ALIGN_RIGHT, "Another text placed on 100,400", 100, 400, 0);
cb.EndText();
#endregion

//Close the document
document.Close();

//Copy the stream to another stream and close it.
MemoryStream pdfstream = new MemoryStream(myStream.ToArray());
myStream.Close();
//Use the stream to send email
string fromEmail = "someone@someplace.com";
string toEmail = "someone@thisplace.com";
string body = "BODY";
string titel = "Sending your personal on the fly created PDF!!";

try
{
//Create the mailmessage object.
MailMessage objEmail = new MailMessage(fromEmail, toEmail, titel, body);
//Add the stream as attachemnt.
objEmail.Attachments.Add(new Attachment(pdfstream, "yourpdf.pdf"));
//Create the smtpclient with a SMTPserver defined in your web.config.
SmtpClient emailClient = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"]);
//Send the mail
emailClient.Send(objEmail);
//Close the stream
pdfstream.Close();
}
catch (Exception exc)
{
Console.WriteLine("Send failure: " + exc.ToString());
}
}


Goodluck!

No comments: