How to render HTML to PDF document

In this article, we'll look at examples of how we can create PDF documents using the Aspose.HTML library.

We need to make some steps to get an HTML document: create a Console Application project, add Aspose.HTML library, declare field of HTMLDocument type, generate (or load) HTML content.


private static HTMLDocument _document;
static void Main()
{
    _document = new HTMLDocument();
    GenerateSampleHtml5Document();
    // TODO: Render PDF
}    

Below is the code of GenerateSampleHtml5Document method, but it will not be discussed in this article:


    private static void GenerateSampleHtml5Document()
    {
        _document.InsertBefore(_document.CreateDocumentType("html", "", "", ""), _document.DocumentElement);
        _document.DocumentElement.SetAttribute("lang", "en");
        _document.Title = "Page for PDF rendering demo";
        var head = _document.GetElementsByTagName("head")[0];
        var metaCharSet = (HTMLMetaElement)_document.CreateElement("meta");
        metaCharSet.SetAttribute("charset", "UTF-8");
        var metaViewPort = (HTMLMetaElement)_document.CreateElement("meta");
        metaViewPort.Name = "viewport";
        metaViewPort.Content = "width=device-width, initial-scale=1";
        var linkElement1 = (HTMLLinkElement)_document.CreateElement("link");
        linkElement1.Href = "http://cdn.myunv.com/css/uecore.css";
        linkElement1.Rel = "stylesheet";
        var linkElement2 = (HTMLLinkElement)_document.CreateElement("link");
        linkElement2.Href = "https://fonts.googleapis.com/css?family=Germania+One";
        linkElement2.Rel = "stylesheet";
        var style = (HTMLStyleElement)_document.CreateElement("style");            
        style.TextContent = "h1 {color: red;} " +
                            "h2 {color:green} " +
                            "table { border: 1px dashed black}" +
                            "p {font-family: 'Germania One', cursive;}" +
                            "#coverPage {page-break-after: always; }";
        head.AppendChild(metaCharSet);
        head.AppendChild(metaViewPort);
        head.AppendChild(linkElement1);
        head.AppendChild(linkElement2);
        head.AppendChild(style);
        var coverPageElement = _document.CreateElement("div");
        coverPageElement.InnerHTML = "<div id=\"coverPage\"><h1>Cover Page</h1></div>";
        var header1 = (HTMLHeadingElement)_document.CreateElement("h1");
        header1.TextContent = "Heading 1";
        var header2 = (HTMLHeadingElement)_document.CreateElement("h2");
        header2.TextContent = "Heading 2";
        _document.DocumentElement.LastElementChild.AppendChild(coverPageElement);
        _document.DocumentElement.LastElementChild.AppendChild(header1);
        _document.DocumentElement.LastElementChild.AppendChild(header2);
        var colors = new[] { "red", "orange", "black", "green", "blue", "indigo", "violet" };
        var alignment = new[] { "left", "right", "center" };
        for (var i = 0; i < 10; i++)
        {
            var paragraph = (HTMLParagraphElement)_document.CreateElement("p");
            paragraph.Id = $"par{i}";
            paragraph.Style.SetProperty("font-weight", i % 2 == 0 ? "700" : "400", "");
            paragraph.Style.SetProperty("color", colors[i % 7], "");
            paragraph.Style.SetProperty("text-align", alignment[i % 3], "");
            paragraph.TextContent = LoremNET.Lorem.Paragraph(10, 5);
            _document.DocumentElement.LastElementChild.AppendChild(paragraph);
        }
        var img = (HTMLImageElement)_document.CreateElement("img");
        img.Src = "http://lorempixel.com/400/200/sports/1";
        img.Alt = "Placeholder 400x200";
        img.Title = "Placeholder image";
        _document.DocumentElement.LastElementChild.AppendChild(img);
        //Adding an ordered list
        var orderedListElement = (HTMLOListElement) _document.CreateElement("ol");
        for (var i = 0; i < 10; i++)
        {
            HTMLLIElement listItem = (HTMLLIElement) _document.CreateElement("li");
            listItem.TextContent = $"Item {i + 1}";
            orderedListElement.AppendChild(listItem);
        }
        _document.DocumentElement.LastElementChild.AppendChild(orderedListElement);
        // Adding simple table 4x3 
        var table = (HTMLTableElement) _document.CreateElement("table");
        var tBody = (HTMLTableSectionElement) _document.CreateElement("tbody");
        for (var i = 0; i < 4; i++)
        {
            var row = (HTMLTableRowElement) _document.CreateElement("tr");
            row.Id = "trow_" + i;
            for (var j = 0; j < 3; j++)
            {
                var cell = (HTMLTableCellElement) _document.CreateElement("td") ;
                cell.Id = $"cell{i}_{j}";
                cell.TextContent = "Cell " + j;
                row.AppendChild(cell);
            }
            tBody.AppendChild(row);
        }
        table.AppendChild(tBody);
        _document.DocumentElement.LastElementChild.AppendChild(table);        
    }

The first steps

Let's try to render PDF document with default rendering options and file to store output. In this example we use following classes:

Class Description
PdfRenderingOptions Represents rendering options for PdfDevice.
PdfDevice Represents a target device for rendering document.
HtmlRenderer Represents an HTML document renderer.

So, to render pdf document we need to create instances of PdfRenderingOptions, PdfDevice and HtmlRenderer and run the rendering process by calling Render method of HtmlRenderer object.


    private static void RenderSimplePdf()
    {
        var options = new PdfRenderingOptions();
        Console.WriteLine(options.PageSetup.AnyPage.Margin.Top.IsAuto);
        Console.WriteLine(options.PageSetup.AnyPage.Margin.Bottom.IsAuto);
        Console.WriteLine(options.PageSetup.AnyPage.Margin.Left.IsAuto);
        Console.WriteLine(options.PageSetup.AnyPage.Margin.Right.IsAuto);
        Console.WriteLine(options.PageSetup.AnyPage.Size.Width);
        Console.WriteLine(options.PageSetup.AnyPage.Size.Height);
        const string outputfile = @"C:\aspose\pdf\output01.pdf";            
        Console.WriteLine("Render PDF file started...");
        var device = new PdfDevice(options, outputfile);
        var renderer = new HtmlRenderer();
        renderer.Render(device, _document);
        Console.WriteLine("Render PDF file finished.");
    }          

We’ve generated a very simple PDF document here, but that’s not very practical. In reality we’ll often have requirements about paper size, page orientation, margins, etc. There are number of configuration options that we can set to make PdfDevice more suitable for our real-world needs. All of them are listed and explained in following table:

Property Description
Encryption Gets or sets a encryption details. If not set, then no encryption will be performed.
JpegQuality Specifies the quality of JPEG compression for images (if JPEG compression is used).
PageSetup Gets a page setup object is used for configuration output page-set.

Advanced Usage

Now let’s talk about advacend settings PdfRenderingOptions. Assume, we need to get the document with paper size A4 and margins: top - 20mm, bottom - 15mm, left/right - 15mm and these settings will be applied for any page.

In order to setup page settings and margins for any pages, we'll use PageSetup.AnyPage property. This is property is the instance of Page class. To define the page layout we need to set up Size and Margin. In both cases we'll use Unit class to get appropiate measurement units.

Following example shows how to set up page settings to any page:


private static void RenderAdvancedPdf()
{
    var width = Unit.FromMillimeters(210);
    var height = Unit.FromMillimeters(297);
    var pageSizeA4 = new Size(width, height);
    var margins = new Margin(
        Unit.FromMillimeters(15), // left
        Unit.FromMillimeters(10), // top
        Unit.FromMillimeters(15), // right
        Unit.FromMillimeters(20));// bottom
    var options = new PdfRenderingOptions { PageSetup = { AnyPage = new Page(pageSizeA4, margins) } };
    const string outputfile = @"C:\aspose\pdf\output02.pdf";
    Console.WriteLine("Render PDF file started...");
    var device = new PdfDevice(options, outputfile);
    var renderer = new HtmlRenderer();
    renderer.Render(device, _document);
    Console.WriteLine("Render PDF file finished.");
}
    

The PdfRenderingOptions also offers the feature to set mirror pages and their rendering. When using this approach, we need to specify the Page settings for both Left and Right pages. Note, that values are set simultaneously for the left and right pages by calling SetLeftRightPage method.


private static void RenderMirrorPages()
{            
    var marginsLeft = new Margin(
        Unit.FromMillimeters(30), // left
        Unit.FromMillimeters(10), // top
        Unit.FromMillimeters(15), // right
        Unit.FromMillimeters(20));// bottom
    var marginsRight = new Margin(
        Unit.FromMillimeters(15), // left
        Unit.FromMillimeters(10), // top
        Unit.FromMillimeters(30), // right
        Unit.FromMillimeters(20));// bottom
    var options = new PdfRenderingOptions();
    options.PageSetup.SetLeftRightPage(
        new Page(PageSizeA4, marginsLeft),
        new Page(PageSizeA4, marginsRight));
    const string outputfile = @"C:\aspose\pdf\output03.pdf";
    Console.WriteLine("Render PDF file started...");
    var device = new PdfDevice(options, outputfile);
    var renderer = new HtmlRenderer();
    renderer.Render(device, _document);
    Console.WriteLine("Render PDF file finished.");
}

Setting the Cover Page

The last feature of PdfRenderingOptions, described in this article, is the FirstPage property. This property is used to set the cover page configuration. The values of this property are set similarly to AnyPage. To set the page break we used a CSS rule "#coverPage {page-break-after: always; }".


private static void RenderWithCoverPage()
{
    Console.WriteLine(_document.DocumentElement.InnerHTML);
    var margin = new Margin(Unit.FromMillimeters(30)); //all margins set to 30 mm
    var options = new PdfRenderingOptions();
    options.PageSetup.FirstPage=new Page(PageSizeA4, margin);
    const string outputfile = @"C:\aspose\pdf\output04.pdf";
    Console.WriteLine("Render PDF file started...");
    var device = new PdfDevice(options, outputfile);
    var renderer = new HtmlRenderer();
    renderer.Render(device, _document);
    Console.WriteLine("Render PDF file finished.");
}    

Conclusion

In this article we discussed how to convert HTML to PDF. It’s really difficult to explain all of the features provided by a Aspose.HTML library in one article this, so be sure to check out the documentation as well to learn about other features like adjact to widest page, encryption, using custom fonts, etc.