Friday, October 15, 2010

Create a PDF and attach it to an email message without saving it to disk

Okay, I must admit it -- I'm pretty proud of this one. This is cool!

The goal: Use WebSupergoo's ABCpdf .NET 7.0 to create a PDF file on the fly. Without saving the file to disk, attach it to an email message, and send the email.

Prerequisites:
  • Create a .NET 3.5 C# web site.

  • Configure the mailSettings section in web.config to point to your SMTP server. Don't have an SMTP server? See this handy tip.

  • Add a button to a form on your website. Place the code below in the button's Click event handler.

  • That's it! But if you're on 64-bit Windows and ABCpdf.NET is throwing an exception, try this.

Here's the code:

// Create a mail message, setting the "from" address, "to" address, subject and body
SmtpClient smptClient = new SmtpClient();
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("ssaporta@localupsolutions.com");
mailMessage.To.Add(new MailAddress("ssaporta@localupsolutions.com"));
mailMessage.Subject = "Test";
mailMessage.Body = "This is a test.";

// Use WebSupergoo's ABCpdf to create a PDF document
Doc theDoc = new Doc();
theDoc.AddHtml("<html><body>The time is now <b>" + DateTime.Now.ToString() + "</b> text.</body></html>");

// Save the document to a memory stream (rather than to a file on disk)
MemoryStream ms = new MemoryStream();
theDoc.Save(ms);

// Important: return to the beginning of the stream
ms.Position = 0;

// Set the MIME type and filename for the attachment
ContentType ct = new ContentType();
ct.MediaType = "application/pdf";
ct.Name = "mydoc" + DateTime.Now.ToString() + ".pdf";

// Create the attachment from the stream
Attachment attachment = new Attachment(ms, ct);
mailMessage.Attachments.Add(attachment);

// Send the email
smptClient.Send(mailMessage);

// Clean up
ms.Close();
theDoc.Clear();

Label1.Text = "Done";

No comments:

Post a Comment