Click here to Skip to main content
6,630,586 members and growing! (16,112 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Samples     Intermediate

Generate PDF documents from a HTML page using ASP.NET

By Albert Pascual

Convert HTML to PDF from an ASPX page.
C#, .NET, Win2K, WinXP, Win2003, ASP.NET, Visual Studio, Dev
Posted:17 May 2004
Updated:23 May 2004
Views:307,720
Bookmarked:145 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
44 votes for this article.
Popularity: 5.26 Rating: 3.20 out of 5
12 votes, 27.3%
1
5 votes, 11.4%
2
5 votes, 11.4%
3
6 votes, 13.6%
4
16 votes, 36.4%
5

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

About the Author

Albert Pascual


Member
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
Occupation: Web Developer
Location: United States United States

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 81 (Total in Forum: 81) (Refresh)FirstPrevNext
GeneralI got error: C:\Windows\system32\LIBEAY32.dll is not a valid windows image Pinmemberhalifaxdal11:41 3 Apr '09  
GeneralNot able to view DisplayPDF.aspx page. Pinmemberriteshmanglani21:16 8 Jan '09  
GeneralOpen source / free HTMLDOC or GHTMLDOC download site Pinmemberdaluu12:59 21 Nov '08  
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pinmemberpc.huff18:35 13 Apr '09  
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pinmemberdaluu9:38 14 Apr '09  
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pinmemberpc.huff9:42 14 Apr '09  
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pinmemberpc.huff9:45 14 Apr '09  
GeneralDownloading PDF PinmemberVinoth Dhakshinamoorthy4:16 17 Jun '08  
GeneralRe: Downloading PDF Pinmemberbkstylz9:30 13 Aug '08  
GeneralRe: Downloading PDF PinmemberDarthJay11:47 29 Aug '08  
GeneralRe: Downloading PDF Pinmembereva xanthou6:15 20 May '09  
GeneralPermissions? Pinmemberjd_hannah11:51 6 Jun '08  
GeneralRe: Permissions? Pinmemberjd_hannah12:29 6 Jun '08  
GeneralCode / Bug Fix PinmemberJustin Porteous23:17 1 Jun '08  
Generalghtmldoc.exe OR HTMLDOC.exe for HTMLDOC 1.9 Pinmemberdeepakleo20:20 20 Dec '07  
Generalghtmldoc.exe for HTMLDOC 1.9 Pinmemberdeepakleo20:18 20 Dec '07  
GeneralProblem with visual studio 2005 PinmemberMamta M2:04 26 Jul '07  
General100% Managed HTML to PDF Converter Library Pinmemberwinnovative11:03 8 Jul '07  
GeneralProfessional HTML To PDF Converter for .NET 2.0 PinmemberFlorentin BADEA21:22 24 May '07  
GeneralPretty useless Pinmemberdc1974:52 19 Apr '07  
GeneralRe: Pretty useless PinmemberAlexander German1:35 5 Jul '07  
GeneralRe: Pretty useless PinmemberDeCrypted139:07 7 Aug '07  
GeneralI can not convet from HTML to PDF Pinmemberminhhong04111:02 2 Apr '07  
GeneralRe: I can not convet from HTML to PDF Pinmemberdeepakleo19:27 20 Dec '07  
GeneralRe: I can not convet from HTML to PDF Pinmemberdeepakleo19:28 20 Dec '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 23 May 2004
Editor: Smitha Vijayan
Copyright 2004 by Albert Pascual
Everything else Copyright © CodeProject, 1999-2009
Web22 | Advertise on the Code Project