Control Page Breaks in PDF with CSS Attributes

Page breaks in the generated PDF document can be controlled using the following CSS properties:

  • page-break-before : always style forces a page break in the PDF right before the box where the element is rendered.

  • page-break-after : always style forces a page break in the PDF right after the box where the element is rendered.

  • page-break-inside : avoid style causes the converter to generate the PDF so that the element with this style is not split across PDF pages, if possible.

Below is an HTML document that demonstrates the usage of the three styles controlling page breaks in the generated PDF document, along with the code of a demo application used to convert that HTML document to PDF.

HTML Document with PDF Page Breaks Control

 
<html>
<head>
    <title>Page Breaks Control</title>
    <style type="text/css">
        body
        {
            font-family: Times New Roman;
            font-size: 15px;
        }
    </style>
</head>
<body style="margin: 1px">
    <div style="width: 750px">
        <table style="page-break-after: always; width: 100%; height: 300px; border: 1px solid black;
            background-color: #F5F5F5">
            <tr>
                <td style="vertical-align: middle; text-align: center">
                    A page break will be forced in PDF right after this TABLE element
                </td>
            </tr>
        </table>
        <br />
        This text there is on a new PDF page because a page break was forced right after
        the TABLE above<br />
        <table style="page-break-before: always; width: 100%; height: 300px; border: 1px solid black;
            background-color: #F5F5F5">
            <tr>
                <td style="vertical-align: middle; text-align: center">
                    A page break was forced in PDF right before this TABLE element
                </td>
            </tr>
        </table>
        <br />
        <table style="page-break-before: always; width: 100%; border: 1px solid black; background-color: #F5F5F5">
            <tr>
                <td style="page-break-inside: avoid; border: 1px solid black;">
                    <b>The text inside this table row should not be cut between PDF pages.</b><br />
                    <br />
                    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
                    incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                    exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
                    irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
                    pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
                    deserunt mollit anim id est laborum.
                </td>
            </tr>
            <!-- ..........-->
            <tr>
                <td style="page-break-inside: avoid; border: 1px solid black;">
                    <b>The text inside this table row should not be cut between PDF pages.</b><br />
                    <br />
                    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
                    incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                    exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
                    irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
                    pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
                    deserunt mollit anim id est laborum.
                </td>
            </tr>
        </table>
    </div>
</body>
</html>

PDF Page Breaks Control Demo

In this demo you learn how to control the page breaks in the generated PDF document using the three CSS styles described above.

Demo Source Code

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

using HiQPdf.Next;

namespace HiQPdf_Next_AspNetDemo.Controllers
{
    public class PdfPageBreaksControlController : Controller
    {
        IWebHostEnvironment m_hostingEnvironment;

        public PdfPageBreaksControlController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

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

        [HttpPost]
        public ActionResult ConvertToPdf(PdfPageBreaksControlViewModel 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 the HTML to PDF converter
            HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

            // set browser width
            htmlToPdfConverter.BrowserWidth = model.BrowserWidth;

            // convert HTML to PDF
            byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(model.HtmlCode, model.BaseUrl);

            FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
            fileResult.FileDownloadName = "PageBreaksControl.pdf";

            return fileResult;
        }

        private PdfPageBreaksControlViewModel SetViewModel()
        {
            var model = new PdfPageBreaksControlViewModel();

            var contentRootPath = Path.Combine(m_hostingEnvironment.ContentRootPath, "wwwroot");

            var htmlFile = Path.Combine(contentRootPath, "DemoFiles", "Html", "PageBreaksControl.html");
            model.HtmlCode = System.IO.File.ReadAllText(htmlFile);

            HttpRequest request = ControllerContext.HttpContext.Request;
            UriBuilder uriBuilder = new UriBuilder();
            uriBuilder.Scheme = request.Scheme;
            uriBuilder.Host = request.Host.Host;
            if (request.Host.Port != null)
                uriBuilder.Port = (int)request.Host.Port;
            uriBuilder.Path = request.PathBase.ToString() + request.Path.ToString();
            uriBuilder.Query = request.QueryString.ToString();

            string currentPageUrl = uriBuilder.Uri.AbsoluteUri;
            string rootUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "PdfPageBreaksControl".Length);

            model.BaseUrl = rootUrl;

            return model;
        }
    }
}

See Also