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
Rate this:
Please Sign up or sign in to vote.

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
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

 
QuestionmagicPDF should do the trick [modified] PinmemberAbramson uri1-Mar-13 14:21 
AnswerRe: have you tried [link removed] / ? PinmemberJibesh1-Mar-13 14:42 
QuestionCould not load type 'SuperJockey.PDF.DisplayPDF'. PinmemberMCA.Bhupendra9-Feb-13 23:29 
Questionhtml to pdf Pinmembersweval28-Dec-11 22:09 
GeneralEO HTML to PDF converter (C# and VB.NET) Pinmemberszchenh14-Apr-11 11:17 
GeneralReg DLL file Pinmembervimaldreams106-Apr-11 4:03 
GeneralHTML to PDF converter based on Webkit [ .NET / JAVA / C++ / PHP / Python / Ruby ] Pinmembercodeivan7-Feb-11 12:08 
Generalbest way to convert HTML to pdf from your asp.net with all styling and formatting Pinmembergo2amitech30-Jul-10 20:58 
GeneralMy vote of 1 PinmemberAvinash T P14-Jul-10 19:52 
GeneralHTML to PDF [modified] PinmemberFlorin Chivu7-Mar-10 6:36 
GeneralMy vote of 2 PinmemberAJFK2-Feb-10 4:49 
GeneralI got error: C:\Windows\system32\LIBEAY32.dll is not a valid windows image Pinmemberhalifaxdal3-Apr-09 10:41 
GeneralNot able to view DisplayPDF.aspx page. Pinmemberriteshmanglani8-Jan-09 20:16 
GeneralOpen source / free HTMLDOC or GHTMLDOC download site Pinmemberdaluu21-Nov-08 11:59 
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pinmemberpc.huff13-Apr-09 17:35 
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pinmemberdaluu14-Apr-09 8:38 
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pinmemberpc.huff14-Apr-09 8:42 
GeneralRe: Open source / free HTMLDOC or GHTMLDOC download site Pinmemberpc.huff14-Apr-09 8:45 
GeneralDownloading PDF PinmemberVinoth Dhakshinamoorthy17-Jun-08 3:16 
Hi Team,
 
Good Morning.
 
Find below are the clarifications and questions regarding PDF document creation
 
Does your PDF creator or converter component authenticate against RSA ClearTrust Authentication and get the snapshots of webpages viewed?
 
In our current application we are downloading a copy of the PDF after viewing some webpages.
 
The new PDF shall consist of the contents of the web pages viewed.
 
We have ClearTrust authentication software installed in our Model Office and Production servers.
 
Below is the procedure that we follow for downloading the PDF.
 
There are 8 .aspx pages that the End User should view.
 
Each webpage is authenticated against the ClearTrust server and then redirected to the actual Web URL.
 
At the end of the 8th webpage,there is a link button control provided to download the PDF.
 
Below is some sample piece of code which we use
 
strURLPage1 = ConfigurationManager.AppSettings["PDFURLPage1"];
strURLPage2 = ConfigurationManager.AppSettings["PDFURLPage2"];
Document document = new Document();
PdfPage page = document.Pages.AddNewPage(PageSize.Letter, new Margins(10, 10, 0, 0),PageOrientation.Portrait);
AddElementResult addResult;
string urlToConvert = strURLPage1 + strGlobalID + "&GroupID=" + intGroupID;
htmlToPdfElement = new HtmlToPdfElement(urlToConvert);
addResult = page.AddElement(htmlToPdfElement);
document.Save(Response, false, "MyPDFSample.pdf");
 
We already have purchased a software which uses the similar kind of code,but it fails in our Testing and Production Server's when we click on the Download PDF link button.
 
Find below the error
 
Could not get the metafile from url. Could not get image from url.The URL is not accessible..
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
 
Exception Details: Winnovative.PdfCreator.HtmlConvertException: Could not get the metafile from url. Could not get image from url.The URL is not accessible..
 
Source Error:
 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
 
Stack Trace:
 

 
[HtmlConvertException: Could not get the metafile from url. Could not get image from url.The URL is not accessible..]
r.a(String A_0, lo& A_1) +176
Winnovative.PdfCreator.HtmlToPdfElement.Render(ElementsRenderer renderer) +623
Winnovative.PdfCreator.PdfPage.AddElement(PageElement pageElement) +6
LegalHold.Memos.InvestigationMemoComplete.lnkDownload_Click(Object sender, EventArgs e) in C:\Inetpub\wwwroot\LegalHold\LegalHold\Memos\InvestigationMemos\InvestigationMemoComplete.aspx.cs:78
System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +90
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +76
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +177
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746
 
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
 
NOTE : Please forward it to appropriate team,if I had mailed to the wrong team.
 
Thanks,
D.Vinoth

GeneralRe: Downloading PDF Pinmemberbkstylz13-Aug-08 8:30 
GeneralRe: Downloading PDF PinmemberDarthJay29-Aug-08 10:47 
GeneralRe: Downloading PDF Pinmembereva xanthou20-May-09 5:15 
GeneralRe: Downloading PDF Pinmemberjlfritz16-Dec-10 4:07 
GeneralRe: Downloading PDF PinmemberGudny26-Sep-11 3:06 
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 
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 
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 
Generalghtmldoc is notworking in asp.net 2.0 ???? [modified] PinmemberHemant Shrivastava20-Jul-06 21:01 
GeneralRecursive Loop - IIS freeze Pinmemberninja260519-Jun-06 1:38 

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
Web04 | 2.8.140421.2 | Last Updated 24 May 2004
Article Copyright 2004 by Albert Pascual
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid