Click here to Skip to main content
11,641,224 members (63,188 online)
Click here to Skip to main content

Generate PDF documents from a HTML page using ASP.NET

, 23 May 2004 2.3M 29.9K 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

 
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 
Generalgetting error in pProcess.Start(); Pin
mbsum3-Jan-06 0:51
membermbsum3-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
memberI am blue21-Mar-06 23:37 
GeneralRe: getting error in pProcess.Start(); Pin
hoangthaitu_vn25-Jul-06 21:20
memberhoangthaitu_vn25-Jul-06 21:20 
GeneralRe: getting error in pProcess.Start(); Pin
jcm123418-Dec-06 23:45
memberjcm123418-Dec-06 23:45 
GeneralRe: getting error in pProcess.Start(); Pin
a109493225-Dec-06 16:04
membera109493225-Dec-06 16:04 
Generalmissing 'PdfLibrary' Pin
Jeremy Moore18-Aug-05 10:11
memberJeremy Moore18-Aug-05 10:11 
GeneralRe: missing 'PdfLibrary' Pin
Albert Pascual18-Aug-05 10:16
memberAlbert Pascual18-Aug-05 10:16 
GeneralRe: missing 'PdfLibrary' Pin
Jeremy Moore18-Aug-05 10:23
memberJeremy Moore18-Aug-05 10:23 
GeneralRe: missing 'PdfLibrary' Pin
Albert Pascual18-Aug-05 11:12
memberAlbert Pascual18-Aug-05 11:12 
GeneralRe: missing 'PdfLibrary' Pin
Albert Pascual18-Aug-05 11:08
memberAlbert Pascual18-Aug-05 11:08 
GeneralRe: missing 'PdfLibrary' Pin
Jeremy Moore18-Aug-05 11:43
memberJeremy Moore18-Aug-05 11:43 
GeneralRe: missing 'PdfLibrary' Pin
Jeremy Moore18-Aug-05 12:58
memberJeremy Moore18-Aug-05 12:58 
QuestionHow to Add Images to PDF Pin
vpratap_822-Aug-05 2:27
membervpratap_822-Aug-05 2:27 
AnswerRe: How to Add Images to PDF Pin
Albert Pascual2-Aug-05 4:29
memberAlbert Pascual2-Aug-05 4:29 
GeneralRe: How to Add Images to PDF Pin
vpratap_822-Aug-05 4:52
membervpratap_822-Aug-05 4:52 
GeneralEuro symbol Pin
Peter VD31-May-05 4:38
memberPeter VD31-May-05 4:38 
GeneralRe: Euro symbol Pin
AudunH9-Feb-06 22:55
memberAudunH9-Feb-06 22:55 
Generalexe launched but no pdf created Pin
Anonymous20-May-05 0:11
sussAnonymous20-May-05 0:11 
GeneralRe: exe launched but no pdf created Pin
blamm23-May-05 9:27
memberblamm23-May-05 9:27 
GeneralRe: exe launched but no pdf created Pin
Albert Pascual18-Jul-05 15:11
memberAlbert Pascual18-Jul-05 15:11 
GeneralNo output generated :( Pin
jaismili6-Mar-05 14:49
memberjaismili6-Mar-05 14:49 
GeneralRe: No output generated :( Pin
Albert Pascual18-Jul-05 15:10
memberAlbert Pascual18-Jul-05 15:10 
QuestionWhat about multi threading? Pin
Rohit Singh 12318-Dec-04 1:13
memberRohit Singh 12318-Dec-04 1:13 
GeneralIncluding CSS Pin
rws098012-Aug-04 3:56
memberrws098012-Aug-04 3:56 
GeneralThankyou for the tips Pin
downhillchris4-Aug-04 16:40
memberdownhillchris4-Aug-04 16:40 
Generalerror Message Pin
gubitar29-Jun-04 23:53
membergubitar29-Jun-04 23:53 
GeneralRe: error Message Pin
Levi.Rosol8-Jul-04 5:43
memberLevi.Rosol8-Jul-04 5:43 
GeneralRe: error Message Pin
Albert Pascual18-Jul-05 15:13
memberAlbert Pascual18-Jul-05 15:13 
GeneralError Pin
degremont14-Jun-04 2:14
memberdegremont14-Jun-04 2:14 
GeneralRe: Error Pin
Levi.Rosol8-Jul-04 5:57
memberLevi.Rosol8-Jul-04 5:57 
QuestionDemo of HTMLDOC??? Pin
cpWayne27-May-04 23:27
membercpWayne27-May-04 23:27 
AnswerRe: Demo of HTMLDOC??? Pin
William Wise5-Jul-04 7:18
memberWilliam Wise5-Jul-04 7:18 
GeneralRe: Demo of HTMLDOC??? Pin
Leon Sandler16-Aug-04 14:25
memberLeon Sandler16-Aug-04 14:25 
GeneralRe: Demo of HTMLDOC??? Pin
Cultx18-May-05 9:22
memberCultx18-May-05 9:22 
GeneralRe: Demo of HTMLDOC??? Pin
daluu21-Nov-08 11:55
memberdaluu21-Nov-08 11:55 

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