Click here to Skip to main content
15,868,292 members
Articles / Web Development / ASP.NET
Article

Generate PDF documents from a HTML page using ASP.NET

Rate me:
Please Sign up or sign in to vote.
3.34/5 (62 votes)
23 May 20041 min read 1.4M   34.1K   202   95
Convert HTML to PDF from an ASPX page.

Introduction

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

C#
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);
    sWriter.WriteLine(sw.ToString());
    sWriter.Close();

    System.Diagnostics.Process pProcess
                         = new System.Diagnostics.Process();
    pProcess.StartInfo.FileName = m_sDrive + ":" + m_Directory +
                                        "\\ghtmldoc.exe";
    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;

    pProcess.Start();

    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.

C#
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());
            Thread.Sleep(1000);
            iTimeout++;
            if ( iTimeout == 10 )
                break;
        }

        if ( bRet == true )
        {
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "Application/pdf";
            try
            {
                Response.WriteFile( MapPath( "" +
                              Request.Params["File"].ToString() ) );
                Response.Flush();
                Response.Close();
            }
            catch
            {
                Response.ClearContent();
            }

        }
        else
        {
            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.

History

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.

License

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


Written By
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

Blog

Comments and Discussions

 
GeneralCharset Pin
Fernando Callejon3-Jan-07 11:46
Fernando Callejon3-Jan-07 11:46 
QuestionNew .net developer [modified] Pin
nauyshine13-Nov-06 16:07
nauyshine13-Nov-06 16:07 
Questiongenerated pdf from html contains "default" in header Pin
jhlal8-Nov-06 2:07
jhlal8-Nov-06 2:07 
QuestionASP .Net 2.0 Pin
rav795-Oct-06 12:02
rav795-Oct-06 12:02 
QuestionMessage Closed Pin
20-Sep-06 14:59
xvietntx20-Sep-06 14:59 
GeneralError plz help Pin
sukantaDas4-Aug-06 8:03
sukantaDas4-Aug-06 8:03 
GeneralRe: Error plz help Pin
tiodio16-Mar-07 1:55
tiodio16-Mar-07 1:55 
Generalghtmldoc is notworking in asp.net 2.0 ???? [modified] Pin
Hemant Shrivastava20-Jul-06 21:01
Hemant Shrivastava20-Jul-06 21:01 
GeneralRecursive Loop - IIS freeze Pin
ninja260519-Jun-06 1:38
ninja260519-Jun-06 1:38 
Generalexcellent Pin
sandeepsaini2k9-Jun-06 0:59
sandeepsaini2k9-Jun-06 0:59 
Generalgetting this to work.. Pin
ste_max30-May-06 0:55
ste_max30-May-06 0:55 
Generalsimplified instructions Pin
BoredOfCoding11-May-06 10:28
BoredOfCoding11-May-06 10:28 
GeneralRe: simplified instructions Pin
Pavan Kumar Komaragiri19-Jan-07 23:30
Pavan Kumar Komaragiri19-Jan-07 23:30 
GeneralRe: simplified instructions Pin
devenderrao14-May-08 20:24
devenderrao14-May-08 20:24 
GeneralNot displaying PDF file Pin
I am blue11-May-06 0:21
I am blue11-May-06 0:21 
GeneralHTML to PDF conversion using asp.net Pin
laksnara7-Feb-06 2:22
laksnara7-Feb-06 2:22 
GeneralErrors Pin
jinphxaz3-Feb-06 8:29
jinphxaz3-Feb-06 8:29 
Generalgetting error due to pprocess.Start() Pin
mbbisht10-Jan-06 17:53
mbbisht10-Jan-06 17:53 
Generalgetting error in pProcess.Start(); Pin
mbbisht3-Jan-06 0:51
mbbisht3-Jan-06 0:51 
GeneralRe: getting error in pProcess.Start(); Pin
Albert Pascual3-Jan-06 5:53
sitebuilderAlbert Pascual3-Jan-06 5:53 
GeneralRe: getting error in pProcess.Start(); Pin
I am blue21-Mar-06 23:37
I am blue21-Mar-06 23:37 
GeneralRe: getting error in pProcess.Start(); Pin
hoangthaitu_vn25-Jul-06 21:20
hoangthaitu_vn25-Jul-06 21:20 
GeneralRe: getting error in pProcess.Start(); Pin
jcm123418-Dec-06 23:45
jcm123418-Dec-06 23:45 
GeneralRe: getting error in pProcess.Start(); Pin
a109493225-Dec-06 16:04
a109493225-Dec-06 16:04 
Generalmissing 'PdfLibrary' Pin
Jeremy Moore18-Aug-05 10:11
Jeremy Moore18-Aug-05 10:11 

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.