HTML to PDF

Have you ever wanted a function to convert HTML to PDF? It is really easy. A good use of this is when you have a resume on your website and you want to create a download of it as a PDF. Mind you; you will have to properly format your resume so it looks good in both cases. Not the easiest job, but totally worth while to have a resume download created on demand.

I just created a genPDF.aspx file that takes a URL and makes it to a PDF. Put a button on the page and have it call the genPDF.aspx page. Your download will automatically be created and pushed through to the browser.

Some things you will need first is a download of some zip files. You can get them from my website or you can seek them out on sourceforge ( iTextSharp / xmlworker ).

There is a lot of examples of how to do this; however, most examples do not support linked CSS files. My example does support linked CSS files.

The code is very simple:

 
     Document document = new Document();  
     try  
     {  
       var oStream = new MemoryStream();  
       PdfWriter writer = PdfWriter.GetInstance(document, oStream);  
       document.Open();  
       document.AddHeader("Content-Disposition", "attachment; filename=resume.pdf");  
       WebClient wc = new WebClient();  
       string htmlText = wc.DownloadString("http://ldndeveloper.com/resume/resume.aspx");  
       iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, new StringReader(htmlText));  
       document.Close();  
       Response.ClearContent();  
       Response.ClearHeaders();  
       Response.AppendHeader("Content-Type", "application/pdf");  
       Response.AppendHeader("Content-Disposition", "attachment;filename=andrew_pallant_resume2015.pdf");  
       Response.OutputStream.Write(oStream.GetBuffer(), 0, oStream.GetBuffer().Length);  
       Response.End();  
     }  
     catch(Exception ex)  
     {  
       Response.Write(ex.StackTrace);  
     }  

Published by

ldnDeveloper

Andrew Pallant (@LdnDeveloper) has been a web, database and desktop developer for over 16 years. Andrew has worked on projects that ranged from factory automation to writing business applications. Most recently he has been heavily involved in various forms for ecommerce projects. Over the years Andrew has worn many hats: Project Manager, IT Manager, Lead Developer, Supervisor of Developers and many more - See more at: http://www.unlatched.com/#sthash.8DiTkpKy.dpuf