Monday, 4 April 2011

Creating PDF Documents with ASP.NET and iTextSharp

I read the article Creating PDF Documents with ASP.NET and iTextSharp by Scott Mitchell and I found it very useful, especially the section where he explains how to create a pdf file from an html template. Now I'm trying to create a helper that receives a URL and creates the pdf for me, this is because I use to create my reports in webforms, and it would be very useful if one could take the content of that report and generate a pdf file with it.
One thing to bear in mind before trying to create the pdf with this approach is that you cannot have any button of link in the page; otherwise the parser will throw an exception. The other thing is that your page has to have inline styles (which is not a good practice) in order to generate the pdf file with all your design.

'This works with URLs in the same site, I got an exception when
'trying others like

webPage As System.Net.WebRequest = _

sReader As New IO.StreamReader( _


'gets all the response as you
see it in the 'View source'

strContent = sReader.ReadToEnd()

Dim parsedHtmlElements = _

Dim document As New Document(PageSize.LEGAL, 50, 50, 25, 25)

Dim output As FileStream = _
   New FileStream(Server.MapPath("myFile.pdf"), 

Dim writer = pdf.PdfWriter.GetInstance(document,


For Each htmlElement In parsedHtmlElements

The helper is still far from being ready but I think this is a good starting point.

No comments:

Post a Comment