ASP.NET - convert aspx page to pdf file at runtime

Asked By kiruba .e on 13-Dec-11 06:32 AM
Hi,

Is this possible to convert our .aspx page to pdf file at runtime.?

if so, pls tell how to do this? but the pdf file should consist of multiple pages.

thanks and regards,
kiruba.e
Jitendra Faye replied to kiruba .e on 13-Dec-11 06:37 AM
Try this code-

string name = "test.pdf";
           
FileStream fs = new FileStream ( Server.MapPath("~/") + name, FileMode.Create, FileAccess.Write );
           
StreamWriter sw = new StreamWriter ( fs, System.Text.Encoding.GetEncoding ( "gb2312" ) );
            sw
.WriteLine ( "Hello World" );
            sw
.Close ( );

           
// If inside of a page:

           
Response.AddHeader ( "Content-Disposition", "attachment; filename=" + Server.UrlEncode ( name ) );
           
Response.ContentType = "application/pdf";
           
//Response.AddHeader ( "Content-Type", "binary/octet-stream" );
           
//Response.AddHeader ( "Content-Disposition", "attachment; filename=" + downloadName + "; size=" + downloadBytes.Length.ToString ( ) );
           
//Response.Flush ( );
           
//Response.BinaryWrite ( downloadBytes );

           
Response.Flush ( );
           
Response.End ( );


           
Response.WriteFile ( name );
           
Response.End ( );


Try this and let me know.
kiruba .e replied to Jitendra Faye on 13-Dec-11 06:40 AM
wil it show in a single page of pdf?

Suchit shah replied to kiruba .e on 13-Dec-11 06:41 AM
I use the Winnovative.WnvHtmlConvert;

You can find it and download the wnvhtmlconvert.dll.
Make reference to the dll.
It is not free but it has demo version with a license. Get it from the site: http://www.winnovative-software.com/[http://www.winnovative-software.com/]

Use the following function:


    /// <summary>
        /// Convert the HTML code from the specified URL to a PDF document and send the 
        /// document as an attachment to the browser
        /// </summary>
        private void ConvertURLToPDF()
        {
            // Create the PDF converter. Optionally you can specify the virtual browser 
            // width as parameter. 1024 pixels is default, 0 means autodetect
            PdfConverter pdfConverter = new PdfConverter();
            // set the license key - required
            pdfConverter.LicenseKey = "you license here";
            // set the converter options - optional
            pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
            pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
            pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait;
            // set if header and footer are shown in the PDF - optional - default is false 
            pdfConverter.PdfDocumentOptions.ShowHeader = false;
            pdfConverter.PdfDocumentOptions.ShowFooter = false;
            // set to generate a pdf with selectable text or a pdf with embedded image - optional - default is true
            pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true;
            // set if the HTML content is resized if necessary to fit the PDF page width - optional - default is true
            pdfConverter.PdfDocumentOptions.FitWidth = true;
            // 
            // set the embedded fonts option - optional - default is false
            pdfConverter.PdfDocumentOptions.EmbedFonts = false;
            // set the live HTTP links option - optional - default is true
            pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = true;
            if (true) //(radioConvertToSelectablePDF.Checked)
            {
                // set if the JavaScript is enabled during conversion to a PDF with selectable text 
                // - optional - default is false
                pdfConverter.ScriptsEnabled = false;
                // set if the ActiveX controls (like Flash player) are enabled during conversion 
                // to a PDF with selectable text - optional - default is false
                pdfConverter.ActiveXEnabled = false;
            }
            else
            {
                // set if the JavaScript is enabled during conversion to a PDF with embedded image 
                // - optional - default is true
                pdfConverter.ScriptsEnabledInImage = true;
                // set if the ActiveX controls (like Flash player) are enabled during conversion 
                // to a PDF with embedded image - optional - default is true
                pdfConverter.ActiveXEnabledInImage = true;
            }
            // set if the images in PDF are compressed with JPEG to reduce the PDF document size - optional - default is true
            pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = true;
            // enable auto-generated bookmarks for a specified list of tags (e.g. H1 and H2)
            if (false)
            {
                pdfConverter.PdfBookmarkOptions.TagNames = new string[] { "H1", "H2" };
            }
            // set PDF security options - optional
            //pdfConverter.PdfSecurityOptions.CanPrint = true;
            //pdfConverter.PdfSecurityOptions.CanEditContent = true;
            //pdfConverter.PdfSecurityOptions.UserPassword = "";

            //set PDF document description - optional
            //pdfConverter.PdfDocumentInfo.AuthorName = "Winnovative HTML to PDF Converter";

            //// add HTML header
            //if (cbAddHeader.Checked)
            //    AddHeader(pdfConverter);
            //// add HTML footer
            //if (cbAddFooter.Checked)
            //    AddFooter(pdfConverter);

            // Performs the conversion and get the pdf document bytes that you can further 
            // save to a file or send as a browser response
            byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(urlToConvert);
            // send the PDF document as a response to the browser for download
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.AddHeader("Content-Type", "binary/octet-stream");
            response.AddHeader("Content-Disposition",
                "attachment; filename=ConversionResult.pdf; size=" + pdfBytes.Length.ToString());
            response.Flush();
            response.BinaryWrite(pdfBytes);
            response.Flush();
            response.End();
        }
dipa ahuja replied to kiruba .e on 13-Dec-11 06:42 AM
Download the dll from here:

http://www.sautinsoft.com/

  void htmlToPDF()
  {
  SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();
  if (p != null)
  {
    p.PageStyle.PageOrientation.Landscape();
    p.TextStyle.Header = @"Sample header";
    p.PageStyle.PageNumFormat = "Page {page} of {numpages}";
 
    string htmlURL = @"http://www.sautinsoft.com/help/html-to-rtf/net/help/htmlsamples/sample1.htm";
    string pdfFile = @"d:\test.pdf";
 
    int result = p.HtmlToPdfConvertFile(htmlURL, pdfFile);
 
    if (result == 0)
    {
    System.Console.WriteLine("Converted successfully!");
    System.Diagnostics.Process.Start(pdfFile);
    }
    else
    System.Console.WriteLine("Converting Error!");
  }
 
  }

For iTextSharp :

http://blog.dmbcllc.com/2009/07/28/itextsharp-html-to-pdf-parsing-html/
 
dipa ahuja replied to kiruba .e on 13-Dec-11 06:44 AM
OR this

  protected void Page_Load(object sender, EventArgs e)
  {
    SautinSoft.PdfVision v = new SautinSoft.PdfVision();
    byte[] pdf = v.ConvertHtmlFileToPDFStream(@"http://sautinsoft.net/pdf-to-word-images-convert.aspx");
    //show PDF
    if (pdf != null)
    {
      Response.Buffer = true;
      Response.Clear();
      Response.ContentType = "application/PDF";
      Response.BinaryWrite(pdf);
      Response.Flush();
      Response.End();
    }
  }
 
Suchit shah replied to kiruba .e on 13-Dec-11 06:44 AM
One way might be to download a custom PDF converter (http://sourceforge.net/projects/pdfcreator/ is a good one) that installs itself as a printer driver on the server. You could then write some code to pass the page, or the necessary data from the page, to this printer, which will output the converted file to the server's harddrive. Your code could then make this file available to the user so that they can download it as a PDF.

It'll unfortunately be more difficult than it sounds; writing PDF conversion components is always a nightmare. Maybe there exists a third-party component that you could purchase?


HOW TO: Generate PDF Output On-the-fly

Solution

Solution 1: Use an open-source .NET PDF library. Sample list:

  • http://sourceforge.net/projects/npdf/ at SourceForge.net - generates XSL-FO from DataTable to render PDF
  • http://sourceforge.net/projects/itextsharp/ at SourceForge.net
    • Examples and Tutorial: http://itextsharp.sourceforge.net/
    • Also see this article: http://www.dopostback.com/eGo/%7B0.7017112.tpgxpht1nnc8n66qcxnl1.594132E.02.3202003%7D/file.aspx?ID=7 by Valerio Fornito, DoPostBack.com
  • http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=5588085e-3d0b-4db8-8a88-603ef212d0db at GotDotNet - design PDF document visually using Visual Studio IDE
  • http://report.sourceforge.net/ at SourceForge.net

Solution 2: Use a commercial .NET PDF library. Sample list:

  • http://www.websupergoo.com/abcpdf-5.htm by WebSupergoo - free license also available
  • http://www.chive.com/products/apoc/ by Chive Software - generates PDF using XSL-FO
  • http://www.aspose.com/Products/Aspose.Pdf/ by Aspose
  • http://dynamicpdf.com/Products/default.asp by ceTe Software
  • http://www.o2sol.com/public/webui/home.shtml by O2 Solutions
  • http://www.pdflib.com/ by PDFLib GmbH
  • http://tallpdf.net/ by TallComponents - able to create PDF documents either programmatically using an object model or from XML.
    • Tutorial: http://www.codeproject.com/showcase/TallComponents.asp by Frank Rem (CodeProject.com)
  • http://www.xmlpdf.com/xmlpdf.html by Visual Programming - converts XML to PDF

Solution 3: Use http://www.activepdf.com/en/Products/WebGrabber to convert any URL output to PDF on-the-fly.

Solution 4: Use a report generator like Crystal Reports or http://www.microsoft.com/sql/reporting/ to render to PDF.

  • http://www.developerfusion.com/show/4266/ by Edward Tanquay (DeveloperFusion.com) - using Crystal Reports
  • http://msdn.microsoft.com/msdnmag/issues/02/05/Crystal/default.aspx by Andrew Brust (MSDN Magazine)

Hope it helps,

kiruba .e replied to dipa ahuja on 13-Dec-11 07:05 AM
yeah its working.  thanks.    but if the page length is more means,  will it automatically split to multiple pages in pdf.
dipa ahuja replied to kiruba .e on 13-Dec-11 07:06 AM
Your Welcome :)

Yes , as per your content, the pages no. will be increase same like in word document

Jitendra Faye replied to kiruba .e on 13-Dec-11 07:46 AM
It depends on your aspx page contents size.
shashi rani replied to kiruba .e on 11-May-12 04:55 AM
end of post