Pages

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 http://gr8code.blogspot.com

Dim
webPage As System.Net.WebRequest = _
System.Net.WebRequest.Create("http://someurl")

Dim
sReader As New IO.StreamReader( _

webPage.GetResponse().GetResponseStream())

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


Dim
strContent = sReader.ReadToEnd()


Dim parsedHtmlElements = _
   HTMLWorker.ParseToList(New
 StringReader(strContent),
 Nothing)


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

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

Dim writer = pdf.PdfWriter.GetInstance(document,
output)

document.Open()

For Each htmlElement In parsedHtmlElements
   document.Add(htmlElement)
Next
document.Close()

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

No comments:

Post a Comment