LDNDeveloper

Andrew Pallant

Software & Web Developer


Donate To Support My Blog Donate if this post helped you. Coffee money is always welcomed!




HTML to PDF

Physical Link: 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);  
     }  

The post HTML to PDF appeared first on LDNDeveloper.

Author:
Categories: C#, C-Sharp, Developement, PDF, Web


©2024 LdnDeveloper