html2pdf.js Documentation

repository·main·Indexed 26 days ago

https://github.com/ekoopmans/html2pdf.js

A client-side JavaScript library for converting HTML elements or entire webpages into printable PDF files using html2canvas and jsPDF. It provides a simple function for quick generation and a Promise-based Worker API for advanced workflows, including control over page-break behavior, image quality, and PDF configuration options.

Tokens
3.8K
Snippets
11
Records
15
Agent score
39%

What's inside html2pdf.js

  1. Install dependencies for unbundled usage

    main

    If you are using the unbundled dist/html2pdf.min.js (or the un-minified version) instead of NPM, you must manually include jsPDF and html2canvas. The order of inclusion is critical to prevent html2canvas from being overridden by jsPDF's internal implementation.

    <script src="jspdf.min.js"></script>
    <script src="html2canvas.min.js"></script>
    <script src="html2pdf.min.js"></script>
  2. Capture a screenshot via Browser Console

    main

    If you cannot modify a webpage directly, you can inject html2pdf.js via the browser console to capture a PDF of the page:

    1. Open the browser console.
    2. Paste and run the following code to load the library:
    function addScript(url) {
        var script = document.createElement('script');
        script.type = 'application/javascript';
        script.src = url;
        document.head.appendChild(script);
    }
    addScript('https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js');
    1. Execute the capture command:
    html2pdf(document.body);
  3. Install html2pdf.js via CDN, NPM, or Bower

    main

    You can integrate html2pdf.js into your project using several methods:

    CDN

    Include the bundled script in your HTML via cdnjs:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js" integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    NPM

    Install via npm. Note that html2pdf.js must be run in a browser and will not run in Node.js:

    npm install --save html2pdf.js

    Bower

    Install via Bower:

    bower install --save html2pdf.js

    Raw JS

    Download dist/html2pdf.bundle.min.js directly and include it:

    <script src="html2pdf.bundle.min.js"></script>
  4. Configure image type and quality

    main

    To customize the image type and quality exported from the canvas, use the image option. This is useful for controlling the balance between PDF file size and visual clarity.

    Supported Types:

    • png (Note: quality setting is ignored for png unless using a compression shim).
    • jpeg (Supports quality from 0 to 1).
    • webp (Supported on Chrome; supports quality from 0 to 1).
    var opt = {
      image: { type: 'jpeg', quality: 0.98 }
    };
  5. Configure html2pdf.js options

    main

    You can configure html2pdf.js using an opt object. The library supports two usage styles: a modern Promise-based API and an older monolithic style.

    Promise-based usage (Recommended):

    html2pdf().set(opt).from(element).save();

    Monolithic-style usage:

    html2pdf(element, opt);
    var element = document.getElementById('element-to-print');
    var opt = {
      margin:       1,
      filename:     'myfile.pdf',
      image:        { type: 'jpeg', quality: 0.98 },
      html2canvas:  { scale: 2 },
      jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
    };
    
    // New Promise-based usage:
    html2pdf().set(opt).from(element).save();
    
    // Old monolithic-style usage:
    html2pdf(element, opt);
  6. Configure page-break behavior

    main

    You can control how page breaks are applied using the pagebreak object within your options. You can use CSS rules, specific selectors, or the avoid-all mode to prevent elements from being split across pages.

    Page-break modes:

    • avoid-all: Automatically adds page-breaks to avoid splitting any elements across pages.
    • css: Adds page-breaks according to the CSS break-before, break-after, and break-inside properties. (Recognizes always/left/right for before/after, and avoid for inside).
    • legacy: Adds page-breaks after elements with class html2pdf__page-break.
    // Avoid page-breaks on all elements, and add one before #page2el.
    html2pdf().set({
      pagebreak: { mode: 'avoid-all', before: '#page2el' }
    });
    
    // Enable all 'modes', with no explicit elements.
    html2pdf().set({
      pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
    });
    
    // No modes, only explicit elements.
    html2pdf().set({
      pagebreak: { before: '.beforeClass', after: ['#after1', '#after2'], avoid: 'img' }
    });
  7. Use the Worker API for advanced workflows

    main

    For fine-grained control, call html2pdf() without arguments to receive a Worker object. The Worker uses a Promise-based API that allows you to chain tasks sequentially.

    Standard Workflow: .from() -> .toContainer() -> .toCanvas() -> .toImg() -> .toPdf() -> .save()

    Example of implicit workflow:

    var worker = html2pdf().from(element).save();
  8. Configure html2pdf options

    main

    The opt object passed to html2pdf(src, opt) or .set(opt) allows you to configure the generation process. The following top-level keys are supported:

    • margin: Sets the page margins.
    • filename: The name of the generated PDF file.
    • image: An object containing type and quality for the image conversion.
    • html2canvas: Options passed directly to the html2canvas library.
    • jspdf: Options passed directly to the jsPDF library.
  9. Reference: Global configuration options

    main

    The following options can be passed to html2pdf.js via the opt parameter to control the PDF generation process.

    |Name        |Type            |Default                         |Description                                                                                                 |
    |------------|----------------|--------------------------------|------------------------------------------------------------------------------------------------------------|
    |margin      |number or array |`0`                             |PDF margin (in jsPDF units). Can be a single number, `[vMargin, hMargin]`, or `[top, left, bottom, right]`. |
    |filename    |string          |`'file.pdf'`                    |The default filename of the exported PDF.                                                                   |
    |pagebreak   |object          |`{mode: ['css', 'legacy']}`     |Controls the pagebreak behaviour on the page. See [Page-breaks](#page-breaks) below.                                |
    |image       |object          |`{type: 'jpeg', quality: 0.95}` |The image type and quality used to generate the PDF. See [Image type and quality](#image-type-and-quality) below.| 
    |enableLinks |boolean         |`true`                          |If enabled, PDF hyperlinks are automatically added ontop of all anchor tags.                                |
    |html2canvas |object          |`{ }`                           |Configuration options sent directly to `html2canvas` ([see here](https://html2canvas.hertzen.com/configuration) for usage).|
    |jsPDF       |object          |`{ }`                           |Configuration options sent directly to `jsPDF` ([see here](http://rawgit.com/MrRio/jsPDF/master/docs/jsPDF.html) for usage).|
  10. Reference: Image configuration

    main

    The image configuration object contains the following fields:

    |Name        |Type            |Default          |Description |
    |------------|----------------|------------------|------------|
    |type        |string          |'jpeg'            |The image type. HTMLCanvasElement only supports 'png', 'jpeg', and 'webp' (on Chrome). |
    |quality     |number          |0.95             |The image quality, from 0 to 1. This setting is only used for jpeg/webp (not png). |
  11. Worker API Reference

    main

    The Worker object provides methods to control the PDF generation pipeline. Many methods have aliases.

    MethodAliasArgumentsDescription
    fromsrc, typeSets the source (HTML string or element). type can be 'string', 'element', 'canvas', or 'img'.
    totargetConverts source to target ('container', 'canvas', 'img', or 'pdf').
    toContainerTarget method for container conversion.
    toCanvasTarget method for canvas conversion.
    toImgTarget method for image conversion.
    toPdfTarget method for PDF conversion.
    outputexporttype, options, srcRoutes to outputPdf or outputImg based on src ('pdf' or 'img').
    outputPdftype, optionsSends data to jsPDF's output method. Returns a Promise.
    outputImgtype, optionsReturns image data as a Promise. Supported types: 'img', 'datauristring', 'dataurlstring', 'datauri', 'dataurl'.
    savesaveAsfilenameSaves the PDF with an optional filename (triggers download).
    setusingoptSets specified properties.
    getkey, cbkReturns property specified by key (via Promise or callback).
    thenrunonFulfilled, onRejectedStandard Promise method (includes progress-tracking). Returns a Worker.
    thenCoreonFulfilled, onRejectedStandard Promise method (no progress-tracking). Returns a Worker.
    thenExternalonFulfilled, onRejectedTrue Promise method. Exits the Worker chain.
    catchonRejectedStandard Promise method.
    catchExternalonRejectedTrue Promise method. Exits the Worker chain.
    errormsgThrows an error in the Worker's Promise chain.