Click here to Skip to main content
Click here to Skip to main content

Generate PDF documents from a HTML page using ASP.NET

, 23 May 2004
Rate this:
Please Sign up or sign in to vote.
Convert HTML to PDF from an ASPX page.


This project uses an HTML to PDF exe from ESP. Please read the GNU license agreement for more information. HTMLDOC is a desktop application to create PDF documents from a HTML page. I wrote some code to use it from a web application. The best used is from a Web Report to add a PRINT to PDF button to use the C# class.

Using the code

    public string Run(string sRawUrl)
        string sFileName = GetNewName();
        string sPage = Server.MapPath("" + sFileName + ".html");            
        string sUrlVirtual = sRawUrl;
        StringWriter sw = new StringWriter();

        Server.Execute(sUrlVirtual, sw);

        StreamWriter sWriter = File.CreateText(sPage);

        System.Diagnostics.Process pProcess 
                             = new System.Diagnostics.Process();
        pProcess.StartInfo.FileName = m_sDrive + ":" + m_Directory + 
        pProcess.StartInfo.Arguments = "--webpage --quiet " + sFontSize + 
                  m_sWaterMark + " --bodyfont Arial " + sLandScape + 
                  " -t pdf14 -f " + sFileName + ".pdf " + sFileName + ".html";
        pProcess.StartInfo.WorkingDirectory = m_sDrive + ":" + m_Directory;


        return(sFileName + ".pdf");            

The class PDFGenerator contains a public method called Run that will call the process hghtmldoc.exe with the arguments you choose. The most important part is to set a working directory where the Web application has permission to read, write and execute, otherwise the program won't work, and the function pProcess.Start will raise a Win32 Exception "access denied".

StreamWriter will save the page into a HTML file on the hard disk.

The file DisplayPDF.aspx and DisplayPDF.aspx.cs will do just that, displays the generated PDF file when ready.

        private void Page_Load(object sender, System.EventArgs e)

            if ( Request.Params["File"] != null )
                bool bRet = false;
                int iTimeout = 0;
                while ( bRet == false )
                    bRet = CheckIfFileExist(Request.Params["File"].ToString());
                    if ( iTimeout == 10 )

                if ( bRet == true )
                    Response.ContentType = "Application/pdf";
                        Response.WriteFile( MapPath( "" + 
                                      Request.Params["File"].ToString() ) ); 
                    if ( Request.Params["Msg"] != null )
                        LabelMsg.Text = Request.Params["Msg"].ToString();

The page accepts a parameter, FILE, previously saved in the hard disk by StreamWriter. The Response.Redirect will include application/PDF, so the browser knows what kind of file is downloading and ask you to SAVE or OPEN. If you have Adobe plug-in installed on your browser, you'll be able to see the PDF from your browser.

Points of Interest

It is important you create a directory to save the HTML file and generate the PDF, also give that directory all the permissions you need to run the EXE.


Remember the HTMLDOC is copywrite ESP. Please go to this link and download the latest version. The GNU license agreement is included in the project.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Albert Pascual
Web Developer
United States United States
Al is just another Software Engineer working in C++, ASp.NET and C#. Enjoys snowboarding in Big Bear, and wait patiently for his daughters to be old enough to write code and snowboard.
Al is a Microsoft ASP.NET MVP

Comments and Discussions

QuestionmagicPDF should do the trick [modified] PinmemberAbramson uri1-Mar-13 15:21 
AnswerRe: have you tried [link removed] / ? PinmemberJibesh1-Mar-13 15:42 
QuestionCould not load type 'SuperJockey.PDF.DisplayPDF'. PinmemberMCA.Bhupendra10-Feb-13 0:29 
AnswerRe: Could not load type 'SuperJockey.PDF.DisplayPDF'. PinmemberCum7me30-Jul-14 3:30 
Questionhtml to pdf Pinmembersweval28-Dec-11 23:09 
GeneralEO HTML to PDF converter (C# and VB.NET) Pinmemberszchenh14-Apr-11 12:17 
GeneralReg DLL file Pinmembervimaldreams106-Apr-11 5:03 
GeneralHTML to PDF converter based on Webkit [ .NET / JAVA / C++ / PHP / Python / Ruby ] Pinmembercodeivan7-Feb-11 13:08 
Generalbest way to convert HTML to pdf from your with all styling and formatting Pinmembergo2amitech30-Jul-10 21:58 
GeneralMy vote of 1 PinmemberAvinash T P14-Jul-10 20:52 
GeneralHTML to PDF [modified] PinmemberFlorin Chivu7-Mar-10 7:36 
GeneralMy vote of 2 PinmemberAJFK2-Feb-10 5:49 
GeneralI got error: C:\Windows\system32\LIBEAY32.dll is not a valid windows image Pinmemberhalifaxdal3-Apr-09 11:41 
GeneralNot able to view DisplayPDF.aspx page. Pinmemberriteshmanglani8-Jan-09 21:16 
GeneralOpen source / free HTMLDOC or GHTMLDOC download site Pinmemberdaluu21-Nov-08 12:59 
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pinmemberpc.huff13-Apr-09 18:35 
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pinmemberdaluu14-Apr-09 9:38 
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pinmemberpc.huff14-Apr-09 9:42 
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pinmemberpc.huff14-Apr-09 9:45 
GeneralDownloading PDF PinmemberVinoth Dhakshinamoorthy17-Jun-08 4:16 
Hi Team,
Good Morning.
Find below are the clarifications and questions regarding PDF document creation
Does your PDF creator or converter component authenticate against RSA ClearTrust Authentication and get the snapshots of webpages viewed?
In our current application we are downloading a copy of the PDF after viewing some webpages.
The new PDF shall consist of the contents of the web pages viewed.
We have ClearTrust authentication software installed in our Model Office and Production servers.
Below is the procedure that we follow for downloading the PDF.
There are 8 .aspx pages that the End User should view.
Each webpage is authenticated against the ClearTrust server and then redirected to the actual Web URL.
At the end of the 8th webpage,there is a link button control provided to download the PDF.
Below is some sample piece of code which we use
strURLPage1 = ConfigurationManager.AppSettings["PDFURLPage1"];
strURLPage2 = ConfigurationManager.AppSettings["PDFURLPage2"];
Document document = new Document();
PdfPage page = document.Pages.AddNewPage(PageSize.Letter, new Margins(10, 10, 0, 0),PageOrientation.Portrait);
AddElementResult addResult;
string urlToConvert = strURLPage1 + strGlobalID + "&GroupID=" + intGroupID;
htmlToPdfElement = new HtmlToPdfElement(urlToConvert);
addResult = page.AddElement(htmlToPdfElement);
document.Save(Response, false, "MyPDFSample.pdf");
We already have purchased a software which uses the similar kind of code,but it fails in our Testing and Production Server's when we click on the Download PDF link button.
Find below the error
Could not get the metafile from url. Could not get image from url.The URL is not accessible..
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Winnovative.PdfCreator.HtmlConvertException: Could not get the metafile from url. Could not get image from url.The URL is not accessible..
Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:

[HtmlConvertException: Could not get the metafile from url. Could not get image from url.The URL is not accessible..]
r.a(String A_0, lo& A_1) +176
Winnovative.PdfCreator.HtmlToPdfElement.Render(ElementsRenderer renderer) +623
Winnovative.PdfCreator.PdfPage.AddElement(PageElement pageElement) +6
LegalHold.Memos.InvestigationMemoComplete.lnkDownload_Click(Object sender, EventArgs e) in C:\Inetpub\wwwroot\LegalHold\LegalHold\Memos\InvestigationMemos\InvestigationMemoComplete.aspx.cs:78
System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +90
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +76
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +177
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
NOTE : Please forward it to appropriate team,if I had mailed to the wrong team.

GeneralRe: Downloading PDF Pinmemberbkstylz13-Aug-08 9:30 
GeneralRe: Downloading PDF PinmemberDarthJay29-Aug-08 11:47 
GeneralRe: Downloading PDF Pinmembereva xanthou20-May-09 6:15 
GeneralRe: Downloading PDF Pinmemberjlfritz16-Dec-10 5:07 
GeneralRe: Downloading PDF PinmemberGudny26-Sep-11 4:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 24 May 2004
Article Copyright 2004 by Albert Pascual
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid