KeyLimeTie Blog

Extract Current Webpage HTML (and maybe generate a PDF)

By Brian Pautsch – 9/20/2006 11:04:25 PM. Posted to Thoughts.

I recently had a requirement from a customer to generate a PDF that looked exactly like the webpage. Instead of trying to recreate the webpage in Crystal or SQL Server Reports, I decided it would be much easier, cheaper and maintainable to simply take the webpage's HTML, load it into a 3rd party PDF generator and create a PDF.

Below is the code you need to do this.
The important part is that you need to override the page's "OnPreRenderComplete" event and extract the HTML from the base.
1protectedoverridevoid OnPreRenderComplete(EventArgs e)
2{
3    GeneratePDFFromPageHTML();
4}
5
6protected void GeneratePDFFromPageHTML() 7{ 8 StringWriter sw; 9 HtmlTextWriter htmltw; 10
11 try
12 { 13 //Get the current page's HTML
14 sw = new StringWriter(); 15 htmltw = new HtmlTextWriter(sw); 16 base.Render(htmltw); 17 StringBuilder html = sw.GetStringBuilder(); 18
19 //Generate PDF with HTML here. Code not supplied
20 //since there are so many 3rd party PDF generators.
21 //When done generating PDF, either load it into the
22 //browser or stream it back as an attachment
23 } 24 catch (Exception ex) 25 { 26 //Handle exception
27 } 28 finally
29 { 30 if (htmltw != null) 31 { 32 htmltw.Close(); 33 htmltw.Dispose(); 34 htmltw = null; 35 } 36 if (sw != null) 37 { 38 sw.Close(); 39 sw.Dispose(); 40 sw = null; 41 } 42 } 43}

Comments

Leave a Comment

Name:
Email:
URL:
Comment:
Security Code:
Type Security Code:

Photos on Flickr

More Photos »

Search Blog


Get Email Updates

Like what you read here at KeyLimeTie? Sign up for our email list!

Subscribe