Wednesday, July 18, 2012

Convert HTML FORM data to PDF with HiQPDF Html to Pdf .net Library

The solution presented in this article covers the following very common scenario:
You have filled some values in a HTML form of a web page and you want to convert this web page to PDF preserving the values filled in the form and the ASP.NET Session Data
In order to capture the values filled in the ASP.NET page, you have to override the Render method of the ASP.NET page to get the HTML code that would be generated during Render phase of the page processing and convert that HTML code to PDF passing the page URL as base URL parameter to the converter.  The sample code below demonstrates how this procedure works in  HiQPDF HTML to PDF .NET Library.

When a 'Convert This Page to PDF' button in the page is pressed, the convertCrtPageToPdf boolean field is set to true. This field is checked in the overridden Render method and if it is true then the HTML code is captured, converted to PDF and the generated PDF is sent as response to browser instead of the normal HTML:

C# code:
---------
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Text;
using System.IO;

using HiQPdf;

namespace HiQPdf_Demo
{
    public partial class ConvertHtmlPreservingState : System.Web.UI.Page
    {
        // a flag to indicate to Render method if the current page
        // will be converted to PDF
        bool convertCrtPageToPdf = false;
        protected void buttonConvertCrtPage_Click(object sender, EventArgs e)
        {
            // indicate to Render method that the current page
            // will be converted to PDF
            convertCrtPageToPdf = true;

            // save custom value in ASP.NET session variable
            Session["SessionVariable"] = textBoxCrtSessionVariable.Text;

            // show session variable value
            panelSessionVariableValue.Visible = true;
            litSessionVariableValue.Text = Session["SessionVariable"].ToString();
        }
        // override the Render method of the ASP.NET page
        protected override void Render(HtmlTextWriter writer)
        {
            if (convertCrtPageToPdf)
            {
                // setup a TextWriter to capture the current page HTML code
                TextWriter tw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(tw);

                // render the HTML markup into the TextWriter
                base.Render(htw);

                // get the current page HTML code
                string htmlCode = tw.ToString();

                // convert the HTML code to PDF

                // create the HTML to PDF converter
                HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

                // hide the HTML buttons
                htmlToPdfConverter.HiddenHtmlElements = new string[] { "#convertCrtPageDiv"};

                // the base URL used to resolve images, CSS and script files
                string currentPageUrl = HttpContext.Current.Request.Url.AbsoluteUri;

                // convert HTML code to a PDF memory buffer
                byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlCode, currentPageUrl);

                // inform the browser about the binary data format
                HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");

                // let the browser know how to open the PDF document, attachment or inline, and the file name
                HttpContext.Current.Response.AddHeader("Content-Disposition",
                    String.Format("attachment; filename=ConvertThisHtmlWithState.pdf; size={0}", pdfBuffer.Length.ToString()));

                // write the PDF buffer to HTTP response
                HttpContext.Current.Response.BinaryWrite(pdfBuffer);

                // call End() method of HTTP response to stop ASP.NET page processing
                HttpContext.Current.Response.End();
            }
            else
            {
                base.Render(writer);
            }
        }
    }
}

Wednesday, July 11, 2012

Sunday, July 8, 2012

HTML to PDF Batch conversion

Full demo source code and details  at HiQPDF HTML to PDF .NET Library
The HiQPdf.HtmlToPdf class can be used to quickly create and save a PDF document to a file, to a stream or in a memory buffer but it will convert only one HTML document to a PDF document. 
Sometimes it is necessary to add multiple HTML documents to the same PDF document and eventualy overlapping the HTML content in multiple layers. 
This is possible with HiQPdf software using In Place HTML to PDF Object. The HTML objects are added to a PDF document which can be created by one of the methods described in PDF Documents topic.
A very interesting feature producing very special effects is that the content from a HTML document which doesn't have a background color or image will not have a background when converted to PDF. This makes possible to overlap multiple HTML documents in PDF while leaving visible the content underneath them.
In this sample you can see how to layout and overlay multiple HTML objects in the same PDF document. The HTML from URL 1 is laid out at the beginning of the PDF document and the URL 2 is laid out immediately after first HTML or on a new page if 'Layout on New Page' option is on. If the second HTML is laid out on a new page then there is the option to change the orientation of the new pages. 
The HTML code from the text box is finally overlaid in the first page of the PDF document at the given location. 
C#  code:
private void buttonCreatePdf_Click(object sender, EventArgs e)
{
    // create an empty PDF document
    PdfDocument document = new PdfDocument();
    // set a demo serial number
    document.SerialNumber = "zoann56qqIKnrLyvvLf74P7u/u7/7vf39/fu/f/g//zg9/f39w==";
    // add a page to document
    PdfPage page1 = document.AddPage(PdfPageSize.A4, PdfDocumentMargins.Empty, PdfPageOrientation.Portrait);
    Cursor = Cursors.WaitCursor;
    string pdfFile = Application.StartupPath + @"\DemoOutput\LayoutMultipleHtml.pdf";
    try
    {
        // set the document header and footer before adding any objects to document
        SetHeader(document);
        SetFooter(document);
        // layout the HTML from URL 1
        PdfHtml html1 = new PdfHtml(textBoxUrl1.Text);
        PdfLayoutInfo html1LayoutInfo = page1.Layout(html1);
        // determine the PDF page where to add URL 2
        PdfPage page2 = null;
        PointF location2 = PointF.Empty;
        if (checkBoxNewPage.Checked)
        {
            // URL 2 is laid out on a new page with the selected orientation
            page2 = document.AddPage(PdfPageSize.A4, PdfDocumentMargins.Empty, GetSelectedPageOrientation());
            location2 = PointF.Empty;
        }
        else
        {
            // URL 2 is laid out immediately after URL 1 and html1LayoutInfo
            // gives the location where the URL 1 layout finished
            page2 = document.Pages[html1LayoutInfo.LastPageIndex];
            location2 = new PointF(html1LayoutInfo.LastPageRectangle.X, html1LayoutInfo.LastPageRectangle.Bottom);
        }
        // layout the HTML from URL 2
        PdfHtml html2 = new PdfHtml(location2.X, location2.Y, textBoxUrl2.Text);
        page2.Layout(html2);
        // overlay the HTML code at the given location
        float destX = int.Parse(textBoxXLocation.Text);
        float destY = int.Parse(textBoxYLocation.Text);
        PdfHtml overlayHtml = new PdfHtml(destX, destY, textBoxHtmlCode.Text, textBoxBaseUrl.Text);
        overlayHtml.BrowserWidth = 500;
        page1.Layout(overlayHtml);
        document.WriteToFile(pdfFile);
    }
    catch (Exception ex)
    {
        MessageBox.Show(String.Format("Cannot create the PDF document. {0}", ex.Message));
        return;
    }
    finally
    {
        document.Close();
        Cursor = Cursors.Arrow;
    }


    // open the created PDF document
    try
    {
        System.Diagnostics.Process.Start(pdfFile);
    }
    catch (Exception ex)
    {
        MessageBox.Show(String.Format("The PDF document was created but cannot open '{0}'. {1}", 
                    pdfFile, ex.Message));
    }
}


private void SetHeader(PdfDocument document)
{
    if (!checkBoxAddHeader.Checked || checkBoxNewPage.Checked && 
                GetSelectedPageOrientation() == PdfPageOrientation.Landscape)
    {
        checkBoxAddHeader.Checked = false;
        return;
    }
    // create the document header
    document.Header = document.CreateHeaderCanvas(document.Pages[0].DrawableRectangle.Width, 50);
    // add PDF objects to the header canvas
    string headerImageFile = Application.StartupPath + @"\DemoFiles\Images\HiQPdfLogo.png";
    PdfImage logoHeaderImage = new PdfImage(5, 5, 40, Image.FromFile(headerImageFile));
    logoHeaderImage.AlphaBlending = true; // Note: this must be set on false when creating a PDF/A document
    document.Header.Layout(logoHeaderImage);
    // layout HTML in header
    PdfHtml headerHtml = new PdfHtml(50, 5, 0, document.Header.Height,
                    @"<span style=""color:Navy; font-family:Times New Roman; font-style:italic"">
                    Quickly Create High Quality PDFs with </span><a href=""http://www.hiqpdf.com"">HiQPdf</a>", null);
    headerHtml.FitDestHeight = true;
    headerHtml.FontEmbedding = true;
    document.Header.Layout(headerHtml);
    // create a border for header
    float headerWidth = document.Header.Width;
    float headerHeight = document.Header.Height;
    PdfRectangle borderRectangle = new PdfRectangle(1, 1, headerWidth - 2, headerHeight - 2);
    borderRectangle.LineStyle.LineWidth = 0.5f;
    borderRectangle.ForeColor = Color.Navy;
    document.Header.Layout(borderRectangle);
}
private void SetFooter(PdfDocument document)
{
    if (!checkBoxAddFooter.Checked || checkBoxNewPage.Checked && 
                    GetSelectedPageOrientation() == PdfPageOrientation.Landscape)
    {
        checkBoxAddFooter.Checked = false;
        return;
    }


    //create the document footer
    document.Footer = document.CreateFooterCanvas(document.Pages[0].DrawableRectangle.Width, 50);
    // layout HTML in footer
    PdfHtml footerHtml = new PdfHtml(5, 5, 0, document.Footer.Height, 
                    @"<span style=""color:Navy; font-family:Times New Roman; font-style:italic"">
                    Quickly Create High Quality PDFs with </span><a href=""http://www.hiqpdf.com"">HiQPdf</a>", null);
    footerHtml.FitDestHeight = true; 
    footerHtml.FontEmbedding = true;
    document.Footer.Layout(footerHtml);
    float footerHeight = document.Footer.Height;
    float footerWidth = document.Footer.Width;
    // add page numbering
    Font pageNumberingFont = new Font(new FontFamily("Times New Roman"), 8, GraphicsUnit.Point);
    //pageNumberingFont.Mea
    PdfText pageNumberingText = new PdfText(5, footerHeight - 12, "Page {CrtPage} of {PageCount}", 
                            pageNumberingFont);
    pageNumberingText.HorizontalAlign = PdfTextHAlign.Center;
    pageNumberingText.EmbedSystemFont = true;
    pageNumberingText.ForeColor = Color.DarkGreen;
    document.Footer.Layout(pageNumberingText);
    string footerImageFile = Application.StartupPath + @"\DemoFiles\Images\HiQPdfLogo.png";
    PdfImage logoFooterImage = new PdfImage(footerWidth - 40 - 5, 5, 40, Image.FromFile(footerImageFile));
    logoFooterImage.AlphaBlending = true; // Note: this must be set on false when creating a PDF/A document
    document.Footer.Layout(logoFooterImage);
    // create a border for footer
    PdfRectangle borderRectangle = new PdfRectangle(1, 1, footerWidth - 2, footerHeight - 2);
    borderRectangle.LineStyle.LineWidth = 0.5f;
    borderRectangle.ForeColor = Color.DarkGreen;
    document.Footer.Layout(borderRectangle);
}
Full demo source code and details  at HiQPDF HTML to PDF .NET Library

HTML to PDF Custom Header and Footer

Full demo source code and details  at HiQPDF HTML to PDF .NET Library
A PdfDocument object can be created by a call to HtmlToPdf.ConvertUrlToPdfDocument() or using the PdfDocument class constructor.  
A PdfDocument can have a header and footer which is repeated in each page of the document. Using the HiQPdf software it is possible to change the document header and footer in a page with a custom header and footer. 
Below you can find a complete example where a custom header is set in the first page and a custom footer is set in the second page. 


C# code:
private void buttonCreatePdf_Click(object sender, EventArgs e)
{
    // create an empty PDF document
    PdfDocument document = new PdfDocument();
    // add a page to document
    PdfPage page1 = document.AddPage(PdfPageSize.A4, new PdfDocumentMargins(5), PdfPageOrientation.Portrait);
    // set the document header and footer before adding any objects to document
    SetHeader(document);
    SetFooter(document);
    // add some content to first page
    PdfHtml html1 = new PdfHtml("<b>First Page Body</b>", null);
    PdfLayoutInfo html1LayoutInfo = page1.Layout(html1);
    // add a second page to document
    PdfPage page2 = document.AddPage(PdfPageSize.A4, new PdfDocumentMargins(5), PdfPageOrientation.Portrait);
    // add some content to second page
    PdfHtml html2 = new PdfHtml("<b>Second Page Body</b>", null);
    PdfLayoutInfo html2LayoutInfo = page2.Layout(html2);
    // set a custom header in first page
    page1 = document.Pages[0];
    // override the document header in first page
    page1.Header = document.CreateHeaderCanvas(document.Header.Width, document.Header.Height);
    // draw the custom page header
    DrawCustomHeader(page1.Header);
    // set a custom footer in second page
    page2 = document.Pages[1];
    // override the document footer in second page
    page2.Footer = document.CreateFooterCanvas(document.Footer.Width, document.Footer.Height);
    // draw the custom page footer
    DrawCustomFooter(page2.Footer);
    // write the output PDF file
    document.WriteToFile("CustomHeaderAndFooter.pdf");
}
private void SetHeader(PdfDocument document)
{
    // create the document header
    document.Header = document.CreateHeaderCanvas(document.Pages[0].DrawableRectangle.Width, 50);
    // layout HTML in header
    PdfHtml headerHtml = new PdfHtml(0, 0, 0, document.Header.Height, "<span style=\"color:Blue\">Default Header Content</span>", null);
    headerHtml.FitDestHeight = true;
    headerHtml.FontEmbedding = true;
    document.Header.Layout(headerHtml);
}
private void SetFooter(PdfDocument document)
{
    //create the document footer
    document.Footer = document.CreateFooterCanvas(document.Pages[0].DrawableRectangle.Width, 50);
    // layout HTML in footer
    PdfHtml footerHtml = new PdfHtml(0, 0, 0, document.Footer.Height, "<span style=\"color:Green\">Default Footer Content</span>", null);
    footerHtml.FitDestHeight = true;
    footerHtml.FontEmbedding = true;
    document.Footer.Layout(footerHtml);
}
private void DrawCustomHeader(PdfDocumentHeader pageHeader)
{
    // layout HTML in custom header
    PdfHtml headerHtml = new PdfHtml(0, 0, 0, pageHeader.Height, "<span style=\"color:Red\">Custom Header Content</span>", null);
    headerHtml.FitDestHeight = true;
    headerHtml.FontEmbedding = true;
    pageHeader.Layout(headerHtml);
}
private void DrawCustomFooter(PdfDocumentFooter pageFooter)
{
    // layout HTML in custom footer
    PdfHtml footerHtml = new PdfHtml(0, 0, 0, pageFooter.Height, "<span style=\"color:Red\">Custom Footer Content</span>", null);
    footerHtml.FitDestHeight = true;
    footerHtml.FontEmbedding = true;
    pageFooter.Layout(footerHtml);
}