Convert URLs and HTML Strings to PDF

The HiQPdf Library offers methods to convert URLs and HTML code to a PDF buffer in memory or to a PDF file.

Convert Methods

The following methods of the HiQPdf.NextHtmlToPdf class can be used to convert HTML documents to PDF.

Methods to convert an HTML document from a given URL to PDF:

Methods to convert an HTML string to PDF:

Asynchronous HTML to PDF Methods

There are also asynchronous variants of these methods that follow the Task-based Asynchronous Pattern (TAP) in .NET, allowing HTML to PDF conversion to run in parallel using async and await. These methods share the same names as their synchronous counterparts and include the "Async" suffix. They also accept an optional System.ThreadingCancellationToken parameter that can be used to cancel the conversion operation where applicable.

You can find an example of how to use the asynchronous HTML to PDF conversion methods in the Convert Multiple HTML Pages to PDF in Parallel topic.

Below is a detailed description of the most important options of the HTML to PDF Converter.

HTML to PDF Converter Options

HiQPdf HTML to PDF Converter allows you to set various options to control the internal browser and PDF document properties. The most important options are listed below, grouped into several categories.

Page Layout

The page size, the width at which the HTML is laid out and the scale at which it is drawn are set together by a layout method of the converter. Each method covers one kind of document and sets the related options below; the browser width and the zoom are computed when the PDF is generated, from the page size, the orientation and the margins in use at that moment, so these can be set before or after the call.

The page size, the orientation, the margins and the other options can be changed after a method. Setting the browser width or the zoom after a method ends the automatic layout: the values set are used as they are, without adjusting them to the page, until a layout method is called again. The layout in use is reported by LayoutMethod. The methods, their parameters and the settings for the usual cases are described in HTML to PDF Page Setup and Scaling.

Browser Options

  • Browser Width. The width in pixels of the browser window in which the HTML is loaded and laid out. The corresponding property is HtmlToPdfBrowserWidth.

    The layout methods of the converter set it: 1024 pixels by default, for the desktop layout of a page. In the default layout, FitBrowserWindowToPage, the window is scaled to the width of the PDF page; with PageWidthFromBrowserWindow the PDF page takes the width of the window, one pixel being 0.75 points, so 1024 pixels give a page 768 points wide plus the margins. Setting the property keeps the value set, as described in HTML to PDF Page Setup and Scaling.

  • Browser Height. The height in pixels of the browser window in which the HTML is loaded, 2048 by default. The corresponding property is HtmlToPdfBrowserHeight.

    The height of the PDF pages does not depend on it: the converter renders the whole content whatever the window height. It matters for pages that load content when it scrolls into view. A page as tall as the content does not depend on this value.

  • Browser Zoom. The scale, in percent, at which the HTML layout is drawn on the PDF page. The corresponding property is HtmlToPdfBrowserZoom. Values from 10 to 200 are supported, with decimals.

    The zoom works like the zoom of a browser when it prints: at a lower zoom more content fits on a line and everything is smaller. The layout methods compute it when the PDF is generated, from the page size, the orientation and the margins: 77.47 in the default layout on A4. Setting the property replaces the computed value with the value set.

  • Load Lazy Images. Specifies whether lazy-loaded images are loaded during the HTML to PDF conversion process.

    The corresponding property that can be set in code is HtmlToPdfLoadLazyImages.

    The default value is true.

    These images are typically loaded by a browser only when they become visible within the viewport.

    The loading behavior can be further configured using the HtmlToPdfLazyImagesLoadMode property, which allows selecting between the browser’s internal mechanism and a custom loading approach. By default, Browser mode is used.

  • Media Type. Specifies the media type used when rendering the web page.

    The corresponding property that can be set in code is HtmlToPdfMediaType.

    By default, the converter uses the screen media type, in every page layout; the PrintLikeChrome layout selects print, as a browser does when it prints.

    This option determines which CSS media rules are applied, such as those defined for print or screen.

  • Wait Before Convert. Specifies the additional time, in seconds, to wait for asynchronous content to load or for a page redirect to complete before starting the conversion.

    The corresponding property that can be set in code is HtmlToPdfWaitBeforeConvert.

    The default value is 0.

    This option is used when the conversion is triggered automatically.

  • Load HTML Timeout. Specifies the navigation timeout, in seconds.

    The corresponding property that can be set in code is HtmlToPdfHtmlLoadedTimeout.

    The default value is 120.

PDF Page Options

  • PDF Page Size. Specifies the page size of the generated PDF document.

    The corresponding property that can be set in code is PdfDocumentControlPageSize.

    The default page size is A4.

    A standard size such as A4, Letter, or Legal can be selected, or a custom page size can be defined by specifying the width and height in points (1 point = 1/72 inch).

    The PDF document options are exposed through an instance of PdfDocumentControl, which is accessible through the HtmlToPdfDocument property.

    When PdfDocumentControlAutoResizePdfPageWidth is set to true, the default is false, the converter automatically adjusts the PDF page width to match the HtmlToPdfBrowserWidth value at the standard 96 DPI HTML rendering resolution.

    When PdfDocumentControlAutoResizePdfPageHeight is set to true, the default is false, the PDF page height is automatically adjusted to match the full height of the HTML content.

    The page has the exact size given by PdfDocumentControlPageSize when both properties are false, the default.

  • PDF Page Orientation. Specifies the page orientation of the generated PDF document.

    The corresponding property that can be set in code is PdfDocumentControlPageOrientation.

    The available values are Portrait and Landscape. The default value is Portrait.

    The PDF document options are exposed through an instance of PdfDocumentControl, which is accessible through the HtmlToPdfDocument property.

  • PDF Page Margins. Specifies the margins of the generated PDF document.

    The corresponding property that can be set in code is PdfDocumentControlMargins.

    The margins are expressed in points (1 point = 1/72 inch). The default value for all margins is 0.

    The PDF document options are exposed through an instance of PdfDocumentControl, which is accessible through the HtmlToPdfDocument property.

  • Auto Resize PDF Page Width. Specifies whether the PDF page width follows the browser window width. The corresponding property is PdfDocumentControlAutoResizePdfPageWidth. The default value is false.

    When true, the page is as wide as the browser window, one pixel being 0.75 points, plus the margins, and the HTML is drawn without scaling; the page height comes from PdfDocumentControlPageSize. This is the setting made by PageWidthFromBrowserWindow. To make the page follow the browser window, prefer calling PageWidthFromBrowserWindow, which also sets the window width and the zoom. While it is true, the browser width and the zoom are not computed by the layout methods: the values set are used, 1024 pixels and 100 percent by default. Setting it back to false restores the layout of the last layout method called. When false, the page has the size given by PdfDocumentControlPageSize and the HTML is laid out for that page.

  • Auto Resize Browser Width. Specifies whether the browser window grows to the width of the content when the content is wider than the window. The corresponding property is HtmlToPdfAutoResizeBrowserWidth. The default value is true; the layout methods set it to true.

    When true, the page is loaded in the window given, then the window is widened to the width the content takes and the page is measured and printed at that width, so the browser does not scale the content down to fit it on the page: the zoom is computed from the final window and the page keeps its width. The given width decides the responsive layout of pages that fit in it. The header and footer keep the zoom of the given window.

  • Auto Resize PDF Page Height. Specifies whether the PDF page is as tall as the rendered HTML content, so that the whole content is on one page. The corresponding property is PdfDocumentControlAutoResizePdfPageHeight. The default value is false.

    The page width comes from the page size, or from the browser window when PdfDocumentControlAutoResizePdfPageWidth is true. The browser window height is not used, the page is as tall as the content. When false, the page height is taken from PdfDocumentControlPageSize.

PDF Security

The Security property of the HiQPdf.Next.PdfDocumentControl class controls the security of the generated PDF document. It is possible to password-protect the document using open and permission passwords, allow or forbid document printing, content copying, content editing, form filling, annotation editing and document assembling. By default, the generated PDF document has no security features enabled.

HTML to PDF Converter Basic Features Demo

In this demo, you can convert a URL, a local file or a custom HTML string to PDF. You can control the options described in this section. As a security option, it is possible to set a password required when the created PDF document is opened and to disable document printing when it is opened in a viewer.

Demo Source Code

C#
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using HiQPdf_Next_AspNetDemo.Models;

using HiQPdf.Next;

namespace HiQPdf_Next_AspNetDemo.Controllers
{
    public class ConvertHtmlToPdfController : Controller
    {
        IWebHostEnvironment m_hostingEnvironment;
        public ConvertHtmlToPdfController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

        // GET: ConvertHtmlToPdf
        public ActionResult Index()
        {
            var model = SetViewModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult ConvertToPdf(ConvertHtmlToPdfViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
                throw new ValidationException(errorMessage);
            }

            // Set the serial number received after purchase to use the library in licensed mode; leave it commented for demo mode
            // Licensing.SerialNumber = "your-serial-number";

            // Create an HTML to PDF converter object with default settings
            HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

            // Set browser height if specified, otherwise use the default
            if (model.BrowserHeight.HasValue)
                htmlToPdfConverter.BrowserHeight = model.BrowserHeight.Value;

            // Set an additional delay, in seconds, to wait for asynchronous content after the initial load
            // The default value is 0
            htmlToPdfConverter.WaitBeforeConvert = model.WaitTime;

            // Set the maximum time, in seconds, to wait for the HTML page to load
            // The default value is 120 seconds
            htmlToPdfConverter.HtmlLoadedTimeout = model.LoadHtmlTimeout;

            // Optionally load the lazy images
            htmlToPdfConverter.LoadLazyImages = model.LoadLazyImages;

            // Set the lazy images load mode
            htmlToPdfConverter.LazyImagesLoadMode = model.LazyImagesLoadMode == "Browser" ?
                LazyImagesLoadMode.Browser : LazyImagesLoadMode.Custom;

            // JavaScript in the converted page; some options of the converter turn it on when they need it

            htmlToPdfConverter.RunJavaScript = model.JavaScriptEnabled;

            // Set the page layout: how the width at which the HTML is laid out relates to the PDF page width
            PdfPageSize pageSize = GetSelectedPageSize(model.PageSize);
            PdfPageOrientation pageOrientation = GetSelectedPageOrientation(model.PageOrientation);

            switch (model.PageLayout)
            {
                case "FitBrowserWindowToPage":
                    // Fixed page size: the HTML is laid out as in a browser window of the given width and the result
                    // is scaled to the content width of the page, so a responsive site keeps its desktop layout.
                    // This is the default layout of the converter, with an A4 page and a 1024 pixel window
                    htmlToPdfConverter.FitBrowserWindowToPage(pageSize, pageOrientation, windowWidth: model.BrowserWidth, singlePage: model.SinglePage);
                    break;

                case "LayoutAtPageWidth":
                    // Fixed page size: the HTML is laid out at the content width of the page, one CSS pixel
                    // being 0.75 points. For HTML templates designed for the paper size
                    htmlToPdfConverter.LayoutAtPageWidth(pageSize, pageOrientation, zoom: model.BrowserZoom, singlePage: model.SinglePage);
                    break;

                case "PrintLikeChrome":
                    // The output of the Save as PDF command of Chrome: the print media type, 1 cm margins, no
                    // background colors or images, drawn at the zoom; the margins and the backgrounds set below
                    // replace the ones of Chrome when they were changed in the form
                    htmlToPdfConverter.PrintLikeChrome(pageSize, pageOrientation, zoom: model.BrowserZoom, singlePage: model.SinglePage);
                    break;

                default:
                    // The PDF page width follows the browser window width and the HTML is drawn 1:1;
                    // the page height comes from the page size and the orientation
                    htmlToPdfConverter.PageWidthFromBrowserWindow(model.BrowserWidth, singlePage: model.SinglePage, zoom: model.BrowserZoom);
                    htmlToPdfConverter.Document.PageSize = pageSize;
                    htmlToPdfConverter.Document.PageOrientation = pageOrientation;
                    break;
            }

            // The page margins in points, after the layout, so that they replace the ones a layout sets. The default is 0

            htmlToPdfConverter.Document.Margins = new PdfMargins(

                model.LeftMargin, model.RightMargin,

                model.TopMargin, model.BottomMargin);

            // The background colors and images of the HTML, printed or not
            htmlToPdfConverter.Document.PrintBackgrounds = model.PrintBackgrounds;

            // The media type used in @media rules, after the layout, so that it replaces the one a layout sets
            htmlToPdfConverter.MediaType = model.MediaType == "Print" ? "print" : "screen";

            // Set the document security
            htmlToPdfConverter.Document.Security.OpenPassword = model.OpenPassword;
            htmlToPdfConverter.Document.Security.AllowPrinting = model.AllowPrinting;

            // Sets the PDF standard for the generated document
            // Leave as None to generate a plain PDF without an accessibility structure tree or archival metadata
            htmlToPdfConverter.Document.PdfStandard = model.PdfStandard;

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

            if (model.UrlOrHtmlCode == "ConvertUrl")
            {
                // Convert URL to a PDF memory buffer
                string url = model.Url;

                pdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(url);
            }
            else
            {
                // Convert HTML code
                string htmlCode = model.HtmlCode;
                string baseUrl = model.BaseUrl;

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

            // The zoom the HTML was drawn at, read from the PDF: the zoom of the layout, lower when the browser window
            // grew to the content; in the name of the file
            string printZoom = htmlToPdfConverter.ConversionInfo.PrintZoom.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture);

            FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
            if (!model.OpenInline)
                fileResult.FileDownloadName = "HtmlToPdf_zoom_" + printZoom + ".pdf";

            return fileResult;
        }

        private PdfPageSize GetSelectedPageSize(string pageSize)
        {
            switch (pageSize)
            {
                case "A0":
                    return PdfPageSize.A0;
                case "A1":
                    return PdfPageSize.A1;
                case "A10":
                    return PdfPageSize.A10;
                case "A2":
                    return PdfPageSize.A2;
                case "A3":
                    return PdfPageSize.A3;
                case "A4":
                    return PdfPageSize.A4;
                case "A5":
                    return PdfPageSize.A5;
                case "A6":
                    return PdfPageSize.A6;
                case "A7":
                    return PdfPageSize.A7;
                case "A8":
                    return PdfPageSize.A8;
                case "A9":
                    return PdfPageSize.A9;
                case "ArchA":
                    return PdfPageSize.ArchA;
                case "ArchB":
                    return PdfPageSize.ArchB;
                case "ArchC":
                    return PdfPageSize.ArchC;
                case "ArchD":
                    return PdfPageSize.ArchD;
                case "ArchE":
                    return PdfPageSize.ArchE;
                case "B0":
                    return PdfPageSize.B0;
                case "B1":
                    return PdfPageSize.B1;
                case "B2":
                    return PdfPageSize.B2;
                case "B3":
                    return PdfPageSize.B3;
                case "B4":
                    return PdfPageSize.B4;
                case "B5":
                    return PdfPageSize.B5;
                case "Flsa":
                    return PdfPageSize.Flsa;
                case "HalfLetter":
                    return PdfPageSize.HalfLetter;
                case "Ledger":
                    return PdfPageSize.Ledger;
                case "Legal":
                    return PdfPageSize.Legal;
                case "Letter":
                    return PdfPageSize.Letter;
                case "Letter11x17":
                    return PdfPageSize.Letter11x17;
                case "Note":
                    return PdfPageSize.Note;
                default:
                    return PdfPageSize.A4;
            }
        }

        private PdfPageOrientation GetSelectedPageOrientation(string pageOrientation)
        {
            return pageOrientation == "Portrait" ?
                PdfPageOrientation.Portrait : PdfPageOrientation.Landscape;
        }

        private ConvertHtmlToPdfViewModel SetViewModel()
        {
            var model = new ConvertHtmlToPdfViewModel();
            return model;
        }
    }
}

See Also