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

Generate PDF documents from a HTML page using ASP.NET

By , 23 May 2004
 

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
Web Developer
United States United States
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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionmagicPDF should do the trick [modified]memberAbramson uri1 Mar '13 - 14:21 
its webkit and doesnt require a separate process.

modified 6 May '13 - 9:40.

AnswerRe: have you tried [link removed] / ?memberJibesh1 Mar '13 - 14:42 
do not post commercial link/advert unless someone asked for it. otherwise you will be reported for abuse. remove that

QuestionCould not load type 'SuperJockey.PDF.DisplayPDF'.memberMCA.Bhupendra9 Feb '13 - 23:29 
i am getting this error when i used your coding Cry | :((
Bhupendra

Questionhtml to pdfmembersweval28 Dec '11 - 22:09 
try the html to pdf converter from hiqpdf.com
GeneralEO HTML to PDF converter (C# and VB.NET)memberszchenh14 Apr '11 - 11:17 
Essential Objects recently released a good HTML to PDF converter. It can render any HTML file a browser can render, but all features are packed inside two DLL files. So it is very easy to redistribute. It does not rely on external browser on the user's computer either.
 
Check out the online demo here:
 
http://www.essentialobjects.com/Products/EOPdf/Default.aspx[^]
GeneralReg DLL filemembervimaldreams106 Apr '11 - 4:03 
When am trying to add the ssleay32.dll file to my application .. it says an error like please check the dll file is accessible or COM component ..
 
I couldn't add the dll files in my application....
 
can anyone help me to solve this issue.
GeneralHTML to PDF converter based on Webkit [ .NET / JAVA / C++ / PHP / Python / Ruby ]membercodeivan7 Feb '11 - 12:08 
PDFTron offers a high-quality HTML to PDF converter based on WebKit that produces small and optimized PDF documents.
 
HTML2PDF is part of Convert Add-on in PDFNet SDK
 

Supported languages are:
.NET / JAVA / C++ / PHP / Python / Ruby
 
Supported platfroms:
Windows, Linux, Mac
 
As a starting point please see HTML2PDF sample project:
 
http://www.pdftron.com/pdfnet/samplecode.html#HTML2PDF
Generalbest way to convert HTML to pdf from your asp.net with all styling and formattingmembergo2amitech30 Jul '10 - 20:58 
[HTML to pdf using asp.net ]
GeneralMy vote of 1memberAvinash T P14 Jul '10 - 19:52 
jkjk
GeneralHTML to PDF [modified]memberFlorin Chivu7 Mar '10 - 6:36 
For .NET I recommend you a professional HTML to PDF library or a free online HTML to PDF service.
 
EVO HTML to PDF is a another library which is even more CSS3 compliant.

modified on Monday, January 24, 2011 2:57 AM

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 24 May 2004
Article Copyright 2004 by Albert Pascual
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid