Click here to Skip to main content
11,581,353 members (57,833 online)
Click here to Skip to main content

Generate PDF documents from a HTML page using ASP.NET

, 23 May 2004 2.3M 29.7K 199
Rate this:
Please Sign up or sign in to vote.
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

    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.

        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

Share

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

Blog

You may also be interested in...

Comments and Discussions

 
GeneralHTML to PDF [modified] Pin
Florin Chivu7-Mar-10 6:36
memberFlorin Chivu7-Mar-10 6:36 
GeneralMy vote of 2 Pin
AJFK2-Feb-10 4:49
memberAJFK2-Feb-10 4:49 
GeneralI got error: C:\Windows\system32\LIBEAY32.dll is not a valid windows image Pin
halifaxdal3-Apr-09 10:41
memberhalifaxdal3-Apr-09 10:41 
GeneralNot able to view DisplayPDF.aspx page. Pin
riteshmanglani8-Jan-09 20:16
memberriteshmanglani8-Jan-09 20:16 
GeneralOpen source / free HTMLDOC or GHTMLDOC download site Pin
daluu21-Nov-08 11:59
memberdaluu21-Nov-08 11:59 
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pin
pc.huff13-Apr-09 17:35
memberpc.huff13-Apr-09 17:35 
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pin
daluu14-Apr-09 8:38
memberdaluu14-Apr-09 8:38 
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pin
pc.huff14-Apr-09 8:42
memberpc.huff14-Apr-09 8:42 
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pin
pc.huff14-Apr-09 8:45
memberpc.huff14-Apr-09 8:45 
GeneralDownloading PDF Pin
Vinoth Dhakshinamoorthy17-Jun-08 3:16
memberVinoth Dhakshinamoorthy17-Jun-08 3:16 
GeneralRe: Downloading PDF Pin
bkstylz13-Aug-08 8:30
memberbkstylz13-Aug-08 8:30 
GeneralRe: Downloading PDF Pin
DarthJay29-Aug-08 10:47
memberDarthJay29-Aug-08 10:47 
GeneralRe: Downloading PDF Pin
eva xanthou20-May-09 5:15
membereva xanthou20-May-09 5:15 
GeneralRe: Downloading PDF Pin
jlfritz16-Dec-10 4:07
memberjlfritz16-Dec-10 4:07 
GeneralRe: Downloading PDF Pin
Gudny26-Sep-11 3:06
memberGudny26-Sep-11 3:06 
QuestionPermissions? Pin
jd_hannah6-Jun-08 10:51
memberjd_hannah6-Jun-08 10:51 
AnswerRe: Permissions? Pin
jd_hannah6-Jun-08 11:29
memberjd_hannah6-Jun-08 11:29 
GeneralCode / Bug Fix Pin
Justin Porteous1-Jun-08 22:17
memberJustin Porteous1-Jun-08 22:17 
GeneralRe: Code / Bug Fix Pin
Md. Humayun Rashed29-Jul-12 19:19
memberMd. Humayun Rashed29-Jul-12 19:19 
Generalghtmldoc.exe OR HTMLDOC.exe for HTMLDOC 1.9 Pin
deepakleo20-Dec-07 19:20
memberdeepakleo20-Dec-07 19:20 
Generalghtmldoc.exe for HTMLDOC 1.9 Pin
deepakleo20-Dec-07 19:18
memberdeepakleo20-Dec-07 19:18 
GeneralProblem with visual studio 2005 Pin
Mamta M26-Jul-07 1:04
memberMamta M26-Jul-07 1:04 
General100% Managed HTML to PDF Converter Library Pin
winnovative8-Jul-07 10:03
memberwinnovative8-Jul-07 10:03 
GeneralPretty useless Pin
dc19719-Apr-07 3:52
memberdc19719-Apr-07 3:52 
GeneralRe: Pretty useless Pin
Alexander German5-Jul-07 0:35
memberAlexander German5-Jul-07 0:35 
GeneralRe: Pretty useless Pin
DeCrypted137-Aug-07 8:07
memberDeCrypted137-Aug-07 8:07 
GeneralRe: Pretty useless Pin
Robert Jun25-May-14 21:58
memberRobert Jun25-May-14 21:58 
GeneralI can not convet from HTML to PDF Pin
minhhong04112-Apr-07 0:02
memberminhhong04112-Apr-07 0:02 
GeneralRe: I can not convet from HTML to PDF Pin
deepakleo20-Dec-07 18:27
memberdeepakleo20-Dec-07 18:27 
GeneralRe: I can not convet from HTML to PDF Pin
deepakleo20-Dec-07 18:28
memberdeepakleo20-Dec-07 18:28 
GeneralFailed to map the path '/'. Pin
amper_119-Mar-07 23:02
memberamper_119-Mar-07 23:02 
GeneralRe: Failed to map the path '/'. Pin
deepakleo20-Dec-07 18:31
memberdeepakleo20-Dec-07 18:31 
GeneralCharset Pin
Fernando Callejon3-Jan-07 11:46
memberFernando Callejon3-Jan-07 11:46 
QuestionNew .net developer [modified] Pin
nauyshine13-Nov-06 16:07
membernauyshine13-Nov-06 16:07 
Questiongenerated pdf from html contains "default" in header Pin
jhlal8-Nov-06 2:07
memberjhlal8-Nov-06 2:07 
QuestionASP .Net 2.0 Pin
rav795-Oct-06 12:02
memberrav795-Oct-06 12:02 
QuestionPDF to HTML?? Pin
xvietntx20-Sep-06 14:59
memberxvietntx20-Sep-06 14:59 
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 asp.net 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 
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 
GeneralHTML to PDF conversion using asp.net Pin
laksnara7-Feb-06 2:22
memberlaksnara7-Feb-06 2:22 
GeneralErrors Pin
jinphxaz3-Feb-06 8:29
memberjinphxaz3-Feb-06 8:29 
Generalgetting error due to pprocess.Start() Pin
mbsum10-Jan-06 17:53
membermbsum10-Jan-06 17:53 

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
Web03 | 2.8.150603.1 | Last Updated 24 May 2004
Article Copyright 2004 by Albert Pascual
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid