Tuesday, 5 July 2016

Create a PDF mail attachment from HTML using .Net

The following is how I managed to get a PDF document created from a string of HTML using Select PDF and then converted to a MemoryStream for attachment to an e-mail.

First, create the HTML string. I use a string builder variable

Dim sbHTML As New StringBuilder

Then create the PDF document from the string (Imports SelectPdf is required)

Dim converter As New HtmlToPdf()
converter.Options.PdfPageSize = PdfPageSize.A4
converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait

Dim docPDF As PdfDocument = converter.ConvertHtmlString(sbHTML.ToString, Nothing)

Then save the PDF to a memory stream

Dim bytPDF As Byte() = Nothing
Dim msPDF As New MemoryStream()
docPDF.Save(msPDF)
bytPDF = msPDF.ToArray()

Set stream to beginning so it can be read as an attachment

msPDF.Seek(0, SeekOrigin.Begin)

Finally, create the message

Dim mm As New MailMessage

and create the content type for the attachment (and attach it to the e-mail)

Dim ct As New ContentType
ct.MediaType = MediaTypeNames.Application.Pdf
ct.Name = "invoice.pdf"
Dim attach As New Attachment(msPDF, ct)
mm.Attachments.Add(attach)

Dispose and close objects after sending

msPDF.Close()
msPDF.Dispose()
docPDF.Close()

No comments:

Post a Comment