Click here to Skip to main content
Click here to Skip to main content

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.

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

Comments and Discussions

 
QuestionPermissions? Pinmemberjd_hannah6-Jun-08 10:51 
AnswerRe: Permissions? Pinmemberjd_hannah6-Jun-08 11:29 
GeneralCode / Bug Fix PinmemberJustin Porteous1-Jun-08 22:17 
GeneralRe: Code / Bug Fix PinmemberMd. Humayun Rashed29-Jul-12 19:19 
Generalghtmldoc.exe OR HTMLDOC.exe for HTMLDOC 1.9 Pinmemberdeepakleo20-Dec-07 19:20 
Generalghtmldoc.exe for HTMLDOC 1.9 Pinmemberdeepakleo20-Dec-07 19:18 
GeneralProblem with visual studio 2005 PinmemberMamta M26-Jul-07 1:04 
General100% Managed HTML to PDF Converter Library Pinmemberwinnovative8-Jul-07 10:03 
I found an amazing html to pdf converter library for .net at http://www.dotnet-reporting.com , is the same. It has full support for HTML tags and CSS and I created a PDF report from a ASP.NET page in a few minutes. That would have taken ages with other reporting tools.
 
Here are a few lines of code that I used to create the report
 
PdfConverter pdfConverter = new PdfConverter();
pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait;
pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true;
pdfConverter.PdfDocumentOptions.ShowFooter = false;
pdfConverter.PdfDocumentOptions.ShowHeader = false;
pdfConverter.LicenseFilePath = Server.MapPath(@"~/Bin");
byte[] downloadBytes = pdfConverter.GetPdfFromUrlBytes(MyURL);
 
There are other interesting PDF tools there like PDF MErge, PDF Split, RTF to PDF Converter, PDF Security tools .
 
Regards,
Florin
 

 


 
HTML to PDF Converter for .NET
GeneralProfessional HTML To PDF Converter for .NET 2.0 PinmemberFlorentin BADEA24-May-07 20:22 
GeneralPretty useless Pinmemberdc19719-Apr-07 3:52 
GeneralRe: Pretty useless PinmemberAlexander German5-Jul-07 0:35 
GeneralRe: Pretty useless PinmemberDeCrypted137-Aug-07 8:07 
GeneralRe: Pretty useless PinmemberRobert Jun25-May-14 21:58 
GeneralI can not convet from HTML to PDF Pinmemberminhhong04112-Apr-07 0:02 
GeneralRe: I can not convet from HTML to PDF Pinmemberdeepakleo20-Dec-07 18:27 
GeneralRe: I can not convet from HTML to PDF Pinmemberdeepakleo20-Dec-07 18:28 
GeneralFailed to map the path '/'. Pinmemberamper_119-Mar-07 23:02 
GeneralRe: Failed to map the path '/'. Pinmemberdeepakleo20-Dec-07 18:31 
GeneralCharset PinmemberFernando Callejon3-Jan-07 11:46 
QuestionNew .net developer [modified] Pinmembernauyshine13-Nov-06 16:07 
Questiongenerated pdf from html contains "default" in header Pinmemberjhlal8-Nov-06 2:07 
QuestionASP .Net 2.0 Pinmemberrav795-Oct-06 12:02 
QuestionPDF to HTML?? Pinmemberxvietntx20-Sep-06 14:59 
GeneralError plz help PinmemberSankar 1234-Aug-06 8:03 
GeneralRe: Error plz help Pinmembertiodio16-Mar-07 1: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 | Mobile
Web03 | 2.8.141022.1 | Last Updated 24 May 2004
Article Copyright 2004 by Albert Pascual
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid