jsPDF HTML Example with html2canvas for Multiple Pages PDF

by Vincy. Last modified on February 24th, 2024.

The jsPDF with html2canvas library is one of the best choices, giving the best output PDF from HTML.

You need to understand the dependent libraries to get better out of it. Effort-wise, it is easier to create a PDF from HTML.

Before getting into the theory part, I want to give the solution directly to save you time :-). Then, I will highlight the area to strengthen the basics of jsPDF and html2canvas.

View Demo

Quick solution

window.jsPDF = window.jspdf.jsPDF;
function generatePdf() {
    let jsPdf = new jsPDF('p', 'pt', 'letter');
    var htmlElement = document.getElementById('doc-target');
    // you need to load html2canvas (and dompurify if you pass a string to html)
    const opt = {
        callback: function (jsPdf) {
            jsPdf.save("Test.pdf");
            // to open the generated PDF in browser window
            // window.open(jsPdf.output('bloburl'));
        },
        margin: [72, 72, 72, 72],
        autoPaging: 'text',
        html2canvas: {
            allowTaint: true,
            dpi: 300,
            letterRendering: true,
            logging: false,
            scale: .8
        }
    };

    jsPdf.html(htmlElement, opt);
}

jspdf html example

Steps to create the HTML example of generating a Multi-page PDF

This JavaScript imports the jsPDF and loads the html2canvas libraries. This example approaches the implementation with the following three steps.

  1. It gets the HTML content.
  2. It sets the html2canvas and jsPDF options of PDF display properties.
  3. It calls the jsPDF .html() function and invokes a callback to output the PDF.

In a previous code, we have seen some small examples of converting HTML to PDF using the jsPDF library.

HTML code for Multi-page PDF content

This example HTML has the content target styled with internal CSS properties. These styles are for setting fonts and spacing while converting this HTML to PDF.

The #doc-target is the PDF’s content target in this HTML. But, the #outer is the outer container to take care of the UI perception.

That means the PDF will reflect the styles from the #doc-target level of the HTML DOM. The #outer is for synchronizing the UI preview and the PDF result for the sake of the perception.

If you want to show a preview before PDF generation, there is an example before generating an invoice PDF.

These styles are

<HTML>
<HEAD>
    <TITLE>jsPDF HTML Example with html2canvas for Multiple Pages PDF</TITLE>
    <style>
        #doc-target {
            font-family: sans-serif;
            -webkit-font-smoothing: antialiased;
            color: #000;
            line-height: 1.6em;
            margin: 0 auto;
        }

        #outer {
            padding: 72pt 72pt 72pt 72pt;
            border: 1px solid #000;
            margin: 0 auto;
            width: 550px;
        }
    </style>
</HEAD>
<BODY>
    <div id="container">
        <p>
            <button class="btn" onclick="generatePdf()">Download PDF</button>
        </p>
        <div id="outer">
            <div id="doc-target">
                <h1>jsPDF HTML Example</h1>
                <div id="lipsum">
                    <p>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam tempor purus a congue
                        ullamcorper.
                        Nunc
                        vulputate eros nunc, sed molestie orci interdum ut. Mauris non tristique neque, ut tincidunt
                        lectus.
                        Nunc sollicitudin eros sapien. Donec metus ex, vestibulum vel pharetra in, convallis id diam.
                        Sed eu
                        tellus pulvinar, fringilla est ut, feugiat nibh. Etiam eget commodo risus. Proin faucibus
                        elementum
                        enim, ut hendrerit nisi convallis at. Pellentesque volutpat, purus faucibus varius tincidunt,
                        nulla
                        erat
                        convallis lacus, eu accumsan felis mauris eget velit. Vestibulum a neque purus. Vestibulum in
                        ultricies
                        justo. Fusce dapibus, sapien a mollis luctus, risus dolor hendrerit ex, in semper justo enim sed
                        ante.
                        Morbi ut urna et velit finibus vehicula. Vivamus elementum egestas ultrices. Proin rutrum orci
                        odio,
                        sit
                        amet hendrerit diam vulputate a.
                    </p>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"
        integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</BODY>
</HTML>

JavaScript jsPDF options for getting a multi-page PDF

In this example code, the JavaScript jsPDF code sets some options or properties. These are required for the following purposes

  • It sets the PDF content’s display properties
  • It defines the callback function to save or open the output PDF.

The list below briefly describes each option and its properties used in this example.

  • callback – It is a client-side method that is invoked when the output PDF is ready.
  • margin – It is the jsPDF option to specify the PDF’s top, right, bottom, and left margins.
  • autoPaging is required when creating a multi-page PDF from HTML with the auto page break.
  • html2canvas – The jsPDF depends on html2canvas library. Knowing how to use these properties will help to get a satisfactory PDF output.
    • allowTaint – It allows the cross-origin images to taint the canvas if it is set as true. The default is false.
    • dpi – It is dots per inch. Giving 300 will be good, which is a printing quality.
    • letterRendering – It allows rendering the letter properly with specified or supported fonts.
    • logging – It writes a log to the developer’s console while creating a PDF. The default is true, but this example disables it.
    • scale – Without specifying this option, it takes the browser’s device pixel ratio.

More references for the available options of creating a full-fledged jsPDF example

These are the library documentation links that guide to creating PDFs from HTML.

  1. jsPDF core inbuilt
  2. jsPDF html.js plugin
  3. Options – html2canvas

The jsPDF core alone has many features to create PDF documents on the client side. But, for converting HTML to a multi-page PDF document, the core jsPDF library is enough.

The latest version replaces the fromHTML plugin with the html.js plugin to convert HTML to PDF.

Above all, jsPDF depends on html2canvas for generating a PDF document. It hooks the html2canvas by supplying enough properties for creating a PDF document.

We used the html2canvas library to capture a screenshot of a webpage. It is a reputed and dependable library to generate and render canvas elements from HTML.

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “jsPDF HTML Example with html2canvas for Multiple Pages PDF”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page