SelectPdf Free Html To Pdf Converter for .NET Core - Control Page Breaks with Html to Pdf Converter - C# / ASP.NET 10 Sample

This sample shows how to use SelectPdf html to pdf converter to convert a raw html code to pdf and also how to control the page breaks from the html code.

To insert a page break in pdf, the html code must have an element with the style page-break-before: always or page-break-after: always. Before or after that specific element, a page break will be inserted into the generated pdf document. The element can be anything (image, table, table row, div, text, etc).

To instruct a certain section from the content to remain on the same page in the generated pdf document, an element with the style page-break-inside: avoid must be used.

Html Code:


Base Url:


Rendering Engine:

Sample code · C#
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using SelectPdf.Universal;

namespace SelectPdf.Samples.Pages
{
    public class PageBreaksModel : PageModel
    {
        public void OnGet()
        {
            DdlRenderingEngine = "Chromium";
            TxtHtmlCode = Helper.PageBreaksText();
        }

        [BindProperty]
        public string TxtHtmlCode { get; set; }

        [BindProperty]
        public string TxtBaseUrl { get; set; }

        [BindProperty]
        public string DdlRenderingEngine { get; set; }

        public List<SelectListItem> RenderingEngines { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "Chromium", Text = "Chromium" },
        };

        public IActionResult OnPost()
        {
            RenderingEngine renderingEngine =
                SampleForm.ParseEnum(DdlRenderingEngine, RenderingEngine.Chromium);

            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();
            converter.Options.NavigationTimeout = Startup.NavigationTimeout;
            converter.Options.RenderingEngine = renderingEngine;

            converter.Options.MarginTop = 10;
            converter.Options.MarginBottom = 10;
            converter.Options.MarginLeft = 10;
            converter.Options.MarginRight = 10;

            // create a new pdf document converting an url
            PdfDocument doc = converter.ConvertHtmlString(TxtHtmlCode, TxtBaseUrl);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;

        }
    }
}