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.Chromium.HtmlToPdf class can be called to convert HTML documents to PDF.

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

Methods to convert a HTML string to PDF:

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

Serial Number

The SerialNumber property of the of the HiQPdf.Chromium.HtmlToPdf class must be set with the purchased serial number as described in the License Purchasing section. In the sample code below is set with an evaluation serial number.

PDF Document Control

The Document property of the HiQPdf.Chromium.HtmlToPdf class having the PdfDocumentControl type is used to control most of the properties of the generated PDF document like page size, page orientation, page margins, header and footer, outlines and the document security.

PDF Page Size

The PageSize property of the HiQPdf.Chromium.PdfDocumentControl class controls the generated PDF document page size. The default value of this property is A4.

PDF Page Orientation

The PageOrientation property of the HiQPdf.Chromium.PdfDocumentControl class controls the generated PDF document page orientation. The default value of this property is Portrait.

PDF Page Margins

The Margins property of the HiQPdf.Chromium.PdfDocumentControl class controls the generated PDF document page margins. By default the generated document margins are all 0.

Auto Resize PDF Page Width

The AutoResizePdfPageWidth controls if the PDF page width is automatically resized to match the BrowserWidth at 96 DPI resolution. The PDF page height is given by the PageSize property. The default value is true.

Load Lazy Images

This option controls whether lazy images, which are typically loaded by a browser only when they become visible in the browser window, are also loaded during the HTML to PDF conversion. By default, this property is set to true and the lazy images are loaded. The property you can set in your code to control the loading of lazy images is HtmlToPdfLoadLazyImages. Additionally, it is possible to choose between the browser’s internal mechanism and a custom algorithm for loading lazy images using the HtmlToPdfLazyImagesLoadMode property. By default, the Browser mode is used by the converter.

Browser Options

The most important options controlling the internal browser are enumerated below.

Browser Width

The BrowserWidth property of the HiQPdf.Chromium.HtmlToPdf class is the equivalent of the web browser window width when viewing a web page. The default value is 1024 pixels.

Browser Height

The BrowserHeight property of the HiQPdf.Chromium.HtmlToPdf class is the equivalent of the web browser window height when viewing a web page. The HTML to PDF Converter will automatically determine the HTML content height and will go beyond the initial given height if necessary to convert the entire HTML content to PDF. The default value is 2048 pixels.

Browser Zoom

The BrowserZoom property of the HiQPdf.Chromium.HtmlToPdf class is the equivalent of the web browser zoom level when viewing a web page. The default value is 100.

Auto Resize Browser Height

The AutoResizeBrowserHeight controls if the browser will be automatically resized to the HTML content height determined after the initial loading. It can be used to improve rendering of web pages with image lazy loading. The default value is false.

Wait Before Convert

The WaitBeforeConvert property of the HiQPdf.Chromium.HtmlToPdf class introduces an additional time in seconds to wait before starting the conversion to allow more time to JavaScript to update the web page.

Load HTML Timeout

The HtmlLoadedTimeout property of the HiQPdf.Chromium.HtmlToPdf class controls the maximum time in seconds to wait for HTML document to be loaded. The default value is 120 seconds. An exception is thrown if the HTML document cannot be loaded in HtmlLoadedTimeout seconds.

MediaType

The MediaType property of the HiQPdf.Chromium.HtmlToPdf class controls the style used by the web page if it has different styles for printing and for displaying on the screen. If the rendered PDF have a different style compared to what you see in a browser, then this might be because the converter is using by default the style for printing while the browser uses the style for screen.

PDF Security

The Security property of the HiQPdf.Chromium.PdfDocumentControl class controls the security of the generated PDF document. It is possible to password protect the generated PDF document with open and permission password, allow or forbid the document priting, content copying, content editing, forms filling, edit annotations and assembling. By default the generated PDF document does not have any security features.

HTML to PDF Converter Basic Features Demo

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

Demo Source Code

C#
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;

using HiQPdf.Chromium;

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

        // GET: ConvertHtmlToPdf
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ConvertToPdf(IFormCollection collection)
        {
            m_formCollection = collection;

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

            // set a demo serial number
            htmlToPdfConverter.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ==";

            // set browser width
            htmlToPdfConverter.BrowserWidth = int.Parse(collection["textBoxBrowserWidth"]);

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

            // set browser zoom
            htmlToPdfConverter.BrowserZoom = int.Parse(collection["textBoxBrowserZoom"]);

            // auto resize the browser height based on HTML content size determined after initial loading
            htmlToPdfConverter.AutoResizeBrowserHeight = collection["checkBoxAutoResizeBrowserHeight"].Count > 0;

            // set wait time before starting conversion
            htmlToPdfConverter.WaitBeforeConvert = int.Parse(collection["textBoxWaitTime"]);

            // set HTML Load timeout
            htmlToPdfConverter.HtmlLoadedTimeout = int.Parse(collection["textBoxLoadHtmlTimeout"]);

            // set the selected media type
            htmlToPdfConverter.MediaType = collection["MediaType"] == "radioButtonPrintMediaType" ? "print" : "screen";

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

            // set PDF page width auto resize to match the BrowserWidth
            htmlToPdfConverter.Document.AutoResizePdfPageWidth = collection["checkBoxAutoResizePdfPageWidth"].Count > 0;

            // set PDF page margins
            // set PDF page margins
            htmlToPdfConverter.Document.Margins = new PdfMargins(
                        int.Parse(collection["textBoxLeftMargin"]), int.Parse(collection["textBoxRightMargin"]),
                        int.Parse(collection["textBoxTopMargin"]), int.Parse(collection["textBoxBottomMargin"]));

            // set the document security
            htmlToPdfConverter.Document.Security.OpenPassword = collection["textBoxOpenPassword"];
            htmlToPdfConverter.Document.Security.AllowPrinting = collection["checkBoxAllowPrinting"].Count > 0;

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

            if (collection["UrlOrHtmlCode"] == "radioButtonConvertUrl")
            {
                // convert URL to a PDF memory buffer
                string url = collection["textBoxUrl"];

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

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

            FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
            if (collection["checkBoxOpenInline"].Count == 0)
                fileResult.FileDownloadName = "HtmlToPdf.pdf";

            return fileResult;
        }

        private PdfPageSize GetSelectedPageSize()
        {
            switch (m_formCollection["dropDownListPageSizes"])
            {
                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()
        {
            return m_formCollection["dropDownListPageOrientations"] == "Portrait" ?
                PdfPageOrientation.Portrait : PdfPageOrientation.Landscape;
        }
    }
}

See Also