Click here to Skip to main content
12,252,506 members (59,901 online)
Click here to Skip to main content
Add your own
alternative version


201 bookmarked

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


You may also be interested in...

Comments and Discussions

GeneralError plz help Pin
Sankar 1234-Aug-06 8:03
memberSankar 1234-Aug-06 8:03 
GeneralRe: Error plz help Pin
tiodio16-Mar-07 1:55
membertiodio16-Mar-07 1:55 
Generalghtmldoc is notworking in 2.0 ???? [modified] Pin
Hemant Shrivastava20-Jul-06 21:01
memberHemant Shrivastava20-Jul-06 21:01 
GeneralRecursive Loop - IIS freeze Pin
ninja260519-Jun-06 1:38
memberninja260519-Jun-06 1:38 
The code runs fine on my workstation which has IIS 5, but doenst work on the Windows Server 2003 with IIS 6. The code goes into recursive loop after Server.Execute line.
And whenever it execute this line of code, it gives Stack Over Flow Exception(mscorlib.dll) on the next line of code.

Here is the attached code:

private void btnEmail_ServerClick(object sender, EventArgs e)


string sUrl = Request.RawUrl;

string sFileName = Convert.ToString(DateTime.Now.Ticks);

string sPage;

//sPage = Server.MapPath("FileServer/Patient/" + Session["PrimaryId"].ToString() + "/" + sFileName + ".html");

sPage = Request.PhysicalApplicationPath + @"Patient\Other_Records\" + sFileName + ".html";

string sUrlVirtual = sUrl;

//string sDirectory = Server.MapPath("FileServer/Patient/" + Session["PrimaryId"].ToString() + "/");

string sDirectory = Request.PhysicalApplicationPath + @"Patient\Other_Records\" ;

string sFontSize = "--fontsize " + "8";

string sLandScape = "";

// string sExeFile = Server.MapPath("bin");

string sExeFile = Request.PhysicalApplicationPath + @"\bin";

StringWriter sw = new StringWriter();

Server.Execute(sUrlVirtual, sw);

StreamWriter sWriter = File.CreateText(sPage);



System.Diagnostics.Process objProcess = new System.Diagnostics.Process();

objProcess.StartInfo.FileName = sExeFile + @"\ghtmldoc.exe";

objProcess.StartInfo.Arguments = "--webpage --quiet " + sFontSize + " --bodyfont Arial " + sLandScape + " -t pdf14 -f " + sFileName + ".pdf " + sFileName + ".html";

objProcess.StartInfo.WorkingDirectory = sDirectory;


string sHtml = sFileName + ".html";

string sPDF = sFileName + ".pdf";



What would be the problem with Server.Execute on IIS6 and windows server 2003

Thanks in advance

Generalexcellent Pin
sandeepsaini2k9-Jun-06 0:59
membersandeepsaini2k9-Jun-06 0:59 
Generalgetting this to work.. Pin
ste_max30-May-06 0:55
memberste_max30-May-06 0:55 
Generalsimplified instructions Pin
BoredOfCoding11-May-06 10:28
memberBoredOfCoding11-May-06 10:28 
GeneralRe: simplified instructions Pin
Pavan Kumar Komaragiri19-Jan-07 23:30
memberPavan Kumar Komaragiri19-Jan-07 23:30 
GeneralRe: simplified instructions Pin
devenderrao14-May-08 20:24
memberdevenderrao14-May-08 20:24 
GeneralNot displaying PDF file Pin
I am blue11-May-06 0:21
memberI am blue11-May-06 0:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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
Web02 | 2.8.160426.1 | Last Updated 24 May 2004
Article Copyright 2004 by Albert Pascual
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid