PDF Creator ASP.NET Core samples · .NET 10 and .NET 11

HTML to PDF

Adds the HTML of a web page or of an HTML string to a PDF document, at a given location and size, as selectable text (HtmlToPdfElement) or as an image (HtmlToImageElement), with a header, a footer and more content after it. Choose the rendering engine: Chromium is recommended for modern pages.


           
Location and size in points. A width of -1 is the available width and a height of -1 is the height of the whole content.

C# code of this sample

Pages/HtmlToPdfDemo.cshtml.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.Globalization;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

using ExpertPdf.PdfCreator;

namespace ExpertPdf.PdfCreator.Samples.Pages
{
    public class HtmlToPdfDemoModel : PageModel
    {
        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string Source { get; set; } = "Url";

        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string PageUrl { get; set; } = "https://www.html-to-pdf.info";

        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string Html { get; set; } = SampleHtml;

        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string BaseUrl { get; set; } = "";

        [BindProperty]
        public int Engine { get; set; } = 0;

        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string Output { get; set; } = "SelectablePdf";

        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string X { get; set; } = "0";

        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string Y { get; set; } = "0";

        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string Width { get; set; } = "-1";

        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string Height { get; set; } = "-1";

        [BindProperty]
        public bool FitWidth { get; set; } = true;

        [BindProperty]
        public bool EmbedFonts { get; set; } = false;

        [BindProperty]
        public bool LiveLinks { get; set; } = true;

        [BindProperty]
        public bool Scripts { get; set; } = true;

        [BindProperty]
        public bool RightToLeft { get; set; } = false;

        [BindProperty]
        public bool AddHeader { get; set; } = true;

        [BindProperty]
        public bool AddFooter { get; set; } = true;

        [BindProperty]
        public bool AdditionalContent { get; set; } = false;

        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string Selector { get; set; } = "";

        public string Message { get; set; }

        public void OnGet()
        {
        }

        public IActionResult OnPost()
        {
            try
            {
                return File(CreatePdf(), "application/pdf", "HtmlToPdf.pdf");
            }
            catch (Exception ex)
            {
                Message = "The PDF document was not created. " + ex.Message;
                return Page();
            }
        }

        // a small HTML document with a forced page break, to try the HTML string conversion
        private const string SampleHtml =
            "<html>\r\n<head>\r\n    <title>HTML string</title>\r\n</head>\r\n" +
            "<body style=\"font-family: Arial\">\r\n" +
            "    <h1>Hello from an HTML string</h1>\r\n" +
            "    <p>The relative URLs of this HTML (images, CSS) are resolved against the base URL.</p>\r\n" +
            "    <p><a href=\"https://www.html-to-pdf.info\">A live link</a></p>\r\n" +
            "    <!-- page-break-after: always starts a new PDF page after this element -->\r\n" +
            "    <div style=\"page-break-after: always\">The end of the first page.</div>\r\n" +
            "    <p>This text is on the second page.</p>\r\n" +
            "</body>\r\n</html>\r\n";

        private byte[] CreatePdf()
        {
            // LicensingManager.LicenseKey = "your license key";

            Document document = new Document();

            // optional document settings: compression, document information, viewer preferences, security...
            document.CompressionLevel = CompressionLevel.NormalCompression;
            document.DocumentInformation.Title = "HTML to PDF";
            document.DocumentInformation.Author = "ExpertPdf PDF Creator";
            document.ViewerPreferences.DisplayDocTitle = true;

            // the default margins of the pages, also used by the pages added for the rest of the HTML content
            document.Margins = new Margins(20, 20, 10, 10);
            PdfPage page = document.Pages.AddNewPage(PageSize.A4, document.Margins, PageOrientation.Portrait);

            PdfFont font = document.AddFont(new Font("Arial", 10, GraphicsUnit.Point), true);
            RenderingEngine engine = SelectedEngine();

            // the header and the footer are templates repeated on each page: add them before the content,
            // so that the content flows in the space left between them
            if (AddHeader)
                AddHtmlHeader(document, engine);
            if (AddFooter)
                AddPageNumbersFooter(document, font);

            // the location and the size of the content in the page, in points: a width of -1 means the available width
            // of the page and a height of -1 the height needed to render the whole content, on as many pages as needed
            float x = float.Parse(X, CultureInfo.InvariantCulture);
            float y = float.Parse(Y, CultureInfo.InvariantCulture);
            float width = float.Parse(Width, CultureInfo.InvariantCulture);
            float height = float.Parse(Height, CultureInfo.InvariantCulture);

            AddElementResult result;
            if ((Output == "SelectablePdf"))
            {
                // the HTML is converted to PDF text, vector graphics and images: the text can be selected and searched
                HtmlToPdfElement html = (Source == "Url")
                    ? new HtmlToPdfElement(x, y, width, height, PageUrl.Trim()) { AllowLocalAccess = false }
                    : new HtmlToPdfElement(x, y, width, height, Html, BaseUrl.Trim()) { AllowLocalAccess = false };

                html.RenderingEngine = engine;
                html.FitWidth = FitWidth;
                html.EmbedFonts = EmbedFonts;
                html.LiveUrlsEnabled = LiveLinks;
                html.ScriptsEnabled = Scripts;
                html.RightToLeftEnabled = RightToLeft;

                // Chromium: an element that starts lower on a page continues on the next pages, and its last page ends where
                // the content ends (no blank space below it); a page that never finishes loading fails after MaxConversionTime
                html.ManagedContentTrimming = true;
                html.ManagedContentTrimmingMode = ManagedContentTrimmingMode.Ink;
                html.MaxConversionTime = 60;

                // convert only a part of the page, for example "#content" or "table.data" (Blink and Chromium engines)
                if (Selector.Trim().Length > 0)
                    html.RenderElementSelector = Selector.Trim();

                result = page.AddElement(html);
            }
            else
            {
                // the HTML is rendered to an image and the image is added to the PDF
                HtmlToImageElement image = (Source == "Url")
                    ? new HtmlToImageElement(x, y, width, height, PageUrl.Trim()) { AllowLocalAccess = false }
                    : new HtmlToImageElement(x, y, width, height, Html, BaseUrl.Trim()) { AllowLocalAccess = false };

                image.RenderingEngine = engine;
                image.FitWidth = FitWidth;
                image.ScriptsEnabled = Scripts;
                if (Selector.Trim().Length > 0)
                    image.RenderElementSelector = Selector.Trim();

                result = page.AddElement(image);
            }

            if (AdditionalContent)
            {
                // the result of AddElement tells on which page and where the content ended:
                // more elements can be placed right after it
                PdfPage endPage = document.Pages[result.EndPageIndex];
                TextElement text = new TextElement(0, result.EndPageBounds.Bottom + 10,
                    "Below this text there is a second HTML element", font);
                text.ForeColor = Color.Green;
                result = endPage.AddElement(text);

                endPage = document.Pages[result.EndPageIndex];
                HtmlToPdfElement more = new HtmlToPdfElement(0, result.EndPageBounds.Bottom + 10,
                    "<h2>A second HTML element</h2><p>It starts where the text above ended.</p>", null) { AllowLocalAccess = false };
                more.RenderingEngine = engine;
                endPage.AddElement(more);
            }

            byte[] pdf = document.Save();
            document.Close();
            return pdf;
        }

        private void AddHtmlHeader(Document document, RenderingEngine engine)
        {
            document.HeaderTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);

            HtmlToPdfElement header = new HtmlToPdfElement(FileUrl("header.html"));
            header.RenderingEngine = engine;
            document.HeaderTemplate.AddElement(header);
        }

        private static void AddPageNumbersFooter(Document document, PdfFont font)
        {
            document.FooterTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 40);
            float width = document.FooterTemplate.ClientRectangle.Width;

            document.FooterTemplate.AddElement(new LineElement(0, 5, width, 5));

            // &p; and &P; are replaced with the page number and the page count
            TextElement pageNumber = new TextElement(0, 12, width, "Page &p; of &P;", font);
            pageNumber.TextAlign = HorizontalTextAlign.Right;
            document.FooterTemplate.AddElement(pageNumber);
        }

        private static string FileUrl(string fileName)
        {
            return new Uri(Path.Combine(Helper.FilesFolder, fileName)).AbsoluteUri;
        }

        // The HTML rendering engines, each deployed next to the application by its NuGet package: WebKit (built in,
        // ExpertPdf.PdfCreator.NetCore), Blink (ExpertPdf.PdfCreator.NetCore.Blink) and Chromium
        // (ExpertPdf.PdfCreator.NetCore.Chromium.Windows), the one recommended for modern pages.
        public static readonly string[] EngineNames = { "Chromium", "Blink", "WebKit" };

        private RenderingEngine SelectedEngine()
        {
            switch (Engine)
            {
                case 1:
                    return RenderingEngine.Blink;
                case 2:
                    return RenderingEngine.WebKit;
                default:
                    return RenderingEngine.Chromium;
            }
        }
    }
}