Convert HTML with Web Fonts to PDF

The Web Fonts offer a great flexibility to web designers to create special effects on text in a HTML document because they are not limited anymore to a small set of fonts installed on the client computers displaying the HTML document. The Web Fonts can be downloaded on the fly by the modern web browsers and used to render the HTML document without installing those fonts on the local machine. The location from where they can be downloaded is given in a CSS3 @font-face rule.

The HiQPdf HTML to PDF Converter has the capacity to convert HTML documents with Web Fonts. It offers support for TrueType fonts in .ttf files, OpenType fonts with TrueType Outlines in .otf files and Web Open Font Format (WOFF) fonts with TrueType Outlines in .woff files.

The Web Open Font Format (WOFF), as its name suggests, was designed to be used with web pages. It is based on a compression algorithm which makes the fonts file smaller and more appropriate for distribution over a network. The WOFF format is currently supported by all major browsers (Firefox 3.6 and later versions, Google Chrome 6.0 and later versions, Internet Explorer 9 and later versions, Opera 11.10 and later versions, Safari 5.1 and later versions).

In the live demo for Converting HTML with Web Fonts to PDF you learn how to define the web fonts in HTML using the @font-face rules and the C# code to convert such a HTML document to PDF.

Set Different Layouts for Screen and Print in HTML to PDF Converter for .NET

Using CSS media types a HTML document can have one layout for screen, one for print , one for handheld devices. The @media rule allows different style rules for different media in the same style sheet in a HTML document.

By default the HTML to PDF converter will render the HTML document for screen, but this can be changed when another media type is assigned to MediaType property. For example, when this property is set to print the CSS properties defined by the @media print rule will be used when the HTML is rendered instead of the CSS properties defined by the @media screen rule.

Below there is a HTML document which demonstrates how to define different styles for screen and for print media types.

<html> 
<head> 
    <title>
        HTML to PDF Rendering Changes Based on Selected Media Type
    </title> 
    <style type="text/css"> 
        body { 
            font-family: 'Arial'; 
            font-size: 16px; 
        } 

        @media screen 
        { 
            p 
            { 
                font-family: Verdana; 
                font-size: 14px; 
                font-style: italic; 
                color: Green; 
            } 
        } 
        @media print 
        { 
            p 
            { 
                font-family: 'Courier New';
                font-size: 12px; 
                color: Black; 
            } 
        } 
        @media screen,print 
        { 
            p 
            { 
                font-weight: bold; 
            } 
        } 
    </style> 
</head> 
<body> 
    <br /><br /> 
    The style of the paragraph below is changed based on 
        the selected media type:
    <br /><br /> 
    <p> 
        This is a media type selection test. When viewing on screen
        the text is bigger, italic and green. When printing the 
        text is smaller, normal and black.
    </p> 
</body> 
</html>

For more details and C# and VB.NET code samples please visit the HTML to PDF Conversion Media Types online demo.

HTML to PDF Conversion Triggering Modes

By default the HTML to PDF starts immediately after the HTML document was loaded in converter. This default behavior is suitable for converting most of the HTML documents. However, there are situations when some JavaScript scripts continue execution even after the document was loaded. In this case it is necessary to configure the HiQPdf HTML to PDF Converter for .NET to wait a predefined interval before starting the rendering to PDF or to configure the converter to wait for the hiqPdfConverter.startConversion() method to be manually called from JavaScript.

Below there is an example of HTML document which requires manual triggering of the conversion. In the sample script we provide, a ticks counter is incremented each 30 ms after the document was loaded. When the ticks count reached 100 in about 3 seconds the startConversion() method is called.

In the HTML script below you can also notice a call to the hiqPdfInfo.getVersion() JavaScript method. This method is exposed by the converter to the JavaScript code in the HTML document being converted to offer information about the HiQPdf library version. The existence of the hiqPdfInfo object in JavaScript can be used to determine whether the document is currently loaded in HiQPdf converter. For example, when the HTML document is loaded in converter you can run a script to change the styles in the document.

<html>
<head>
    <title>Conversion Triggering Mode</title>
</head>
<body>
    <span style="font-family: Times New Roman; font-size: 10pt">When the triggering mode
        is 'Manual' the conversion is triggered by the call to <b>hiqPdfConverter.startConversion()</b>
        from JavaScript.<br />
        In this example document the startConversion() method is called when the ticks count
        reached 100 which happens in about 3 seconds.</span>
    <br />
    <br />
    <b>Ticks Count:</b> <span style="color: Red" id="ticks">0</span>
    <br />
    <br />
    <!-- display HiQPdf HTML converter version if the document is loaded in converter-->
    <span style="font-family: Times New Roman; font-size: 10pt">HiQPdf Info:
        <script type="text/javascript">
            // check if the document is loaded in HiQPdf HTML to PDF Converter
            if (typeof hiqPdfInfo == "undefined") {
                // hiqPdfInfo object is not defined and the document is loaded in a browser
                document.write("Not in HiQPdf");
            }
            else {
                // hiqPdfInfo object is defined and the document is loaded in converter
                document.write(hiqPdfInfo.getVersion());
            }
        </script>
    </span>
    <br />
    <script type="text/javascript">
        var ticks = 0;
        function tick() {
            // increment ticks count
            ticks++;

            var ticksElement = document.getElementById("ticks");
            // set ticks count
            ticksElement.innerHTML = ticks;
            if (ticks == 100) {
                // trigger conversion
                ticksElement.style.color = "green";
                hiqPdfConverter.startConversion();
            }
            else {
                // wait one more tick
                setTimeout("tick()", 30);
            }
        }

        tick();
    </script>
</body>
</html>

There are three conversion triggering modes: Auto, WaitTime and Manual. In the sample script above, a ticks counter is incremented each 30 ms after the document was loaded. When the ticks count reached 100 in about 3 seconds the startConversion() is called.

When the triggering mode is Manual the call to startConversion() will trigger the conversion.

When the triggering mode is WaitTime a wait time of 5 seconds is sufficient to allow the ticks count reach 100.

When the triggering mode is Auto the conversion will start before the counter reached 100.

private void buttonCreatePdf_Click(object sender, EventArgs e)
{
    // create the HTML to PDF converter
    HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

    Cursor = Cursors.WaitCursor;

    string pdfFile = Application.StartupPath + @"\DemoOutput\TriggeringMode.pdf";
    try
    {
        // set triggering mode; for WaitTime mode set the wait time before convert
        switch (comboBoxTriggeringMode.SelectedItem.ToString())
        {
            case "Auto":
                htmlToPdfConverter.TriggerMode = ConversionTriggerMode.Auto;
                break;
            case "WaitTime":
                htmlToPdfConverter.TriggerMode = ConversionTriggerMode.WaitTime;
                htmlToPdfConverter.WaitBeforeConvert = int.Parse(textBoxWaitTime.Text);
                break;
            case "Manual":
                htmlToPdfConverter.TriggerMode = ConversionTriggerMode.Manual;
                break;
            default:
                htmlToPdfConverter.TriggerMode = ConversionTriggerMode.Auto;
                break;
        }

        // convert the URL to PDF
        htmlToPdfConverter.ConvertHtmlToFile(textBoxHtmlCode.Text, null, pdfFile);
    }
    catch (Exception ex)
    {
        MessageBox.Show(String.Format("Conversion failed. {0}", ex.Message));
        return;
    }
    finally
    {
        Cursor = Cursors.Arrow;
    }

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

For more details and C# and VB.NET code samples please visit the HTML to PDF Conversion Triggering Modes online demo.

Convert HTML to PDF in ASP.NET and MVC with C# and VB.NET

The majority of the websites are already able to produce reports or to present various results in HTML pages. While the HTML content is simple generate and edit it is not suitable for printing or for transmission by email. The de facto standard for printing is the PDF format. The HiQPdf HTML to PDF Converter for .NET can be used in your .NET applications to transform any HTML page into a PDF document preserving the original aspect of the HTML document.

The HiQPdf Library for .NET offers you a modern, simple, fast, flexible and powerful tool to create complex and stylish PDF documents in your applications with just a few lines of code.

Using the high quality HTML to PDF conversion engine you can easily design a document in HTML with CSS3, JavaScript, SVG or Canvas and then convert it to PDF preserving the exact content and style.

The main features of the converter are listed below:

  • Convert HTML and HTML5 Documents and Web Pages to PDF
  • Convert URLs and HTML Strings to PDF Files or Memory Buffers
  • Set the PDF Page Size and Orientation
  • Fit HTML Content in PDF Page Size
  • Advanced Support for Web Fonts in .WOFF and .TTF Formats
  • Advanced Support for Scalar Vector Graphics (SVG)
  • Advanced Support for HTML5 and CSS3
  • Delayed Conversion Triggering Mode
  • Control PDF page breaks with page-break CSS attributes in HTML
  • Repeat HTML Table Header and Footer on Each PDF Page
  • Packaged and Delivered as a Zip Archive
  • No External Dependencies
  • Direct Copy Deployment Supported
  • ASP.NET and Windows Forms Samples, Complete Documentation
  • Supported on All Windows Versions

You can find all the HiQPdf Library for .NET Features with a brief description of each feature on product page.

html_to_pdf

The C# sample code below shows how easy you can create the PDF documents from existing HTML pages or HTML strings. With just a few lines of code you can get richly formatted PDF document:

protected void buttonConvertToPdf_Click(object sender, EventArgs e)
{
    // create the HTML to PDF converter
    HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

    // set browser width
    htmlToPdfConverter.BrowserWidth = int.Parse(textBoxBrowserWidth.Text);

    // set browser height if specified, otherwise use the default
    if (textBoxBrowserHeight.Text.Length > 0)
        htmlToPdfConverter.BrowserHeight = int.Parse(textBoxBrowserHeight.Text);

    // set HTML Load timeout
    htmlToPdfConverter.HtmlLoadedTimeout = int.Parse(textBoxLoadHtmlTimeout.Text);

    // set PDF page size and orientation
    htmlToPdfConverter.Document.PageSize = GetSelectedPageSize();
    htmlToPdfConverter.Document.PageOrientation = GetSelectedPageOrientation();

    // set the PDF standard used by the document
    htmlToPdfConverter.Document.PdfStandard = checkBoxPdfA.Checked ? PdfStandard.PdfA : PdfStandard.Pdf;

    // set PDF page margins
    htmlToPdfConverter.Document.Margins = new PdfMargins(5);

    // set whether to embed the true type font in PDF
    htmlToPdfConverter.Document.FontEmbedding = checkBoxFontEmbedding.Checked;

    // set triggering mode; for WaitTime mode set the wait time before convert
    switch (dropDownListTriggeringMode.SelectedValue)
    {
        case "Auto":
            htmlToPdfConverter.TriggerMode = ConversionTriggerMode.Auto;
            break;
        case "WaitTime":
            htmlToPdfConverter.TriggerMode = ConversionTriggerMode.WaitTime;
            htmlToPdfConverter.WaitBeforeConvert = int.Parse(textBoxWaitTime.Text);
            break;
        case "Manual":
            htmlToPdfConverter.TriggerMode = ConversionTriggerMode.Manual;
            break;
        default:
            htmlToPdfConverter.TriggerMode = ConversionTriggerMode.Auto;
            break;
    }

    // set header and footer
    SetHeader(htmlToPdfConverter.Document);
    SetFooter(htmlToPdfConverter.Document);

    // set the document security
    htmlToPdfConverter.Document.Security.OpenPassword = textBoxOpenPassword.Text;
    htmlToPdfConverter.Document.Security.AllowPrinting = checkBoxAllowPrinting.Checked;

    // set the permissions password too if an open password was set
    if (htmlToPdfConverter.Document.Security.OpenPassword != null && htmlToPdfConverter.Document.Security.OpenPassword != String.Empty)
        htmlToPdfConverter.Document.Security.PermissionsPassword = htmlToPdfConverter.Document.Security.OpenPassword + "_admin";

    // convert HTML to PDF
    byte[] pdfBuffer = null;

    if (radioButtonConvertUrl.Checked)
    {
        // convert URL to a PDF memory buffer
        string url = textBoxUrl.Text;

        pdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(url);
    }
    else
    {
        // convert HTML code
        string htmlCode = textBoxHtmlCode.Text;
        string baseUrl = textBoxBaseUrl.Text;

        // convert HTML code to a PDF memory buffer
        pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlCode, baseUrl);
    }

    // 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("{0}; filename=HtmlToPdf.pdf; size={1}",
        checkBoxOpenInline.Checked ? "inline" : "attachment", 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();
}

You can find more HTML to PDF C# and VB.NET samples in the online demo.