Convert HTML Document Into PDF – html2PDF

Category: Javascript | February 11, 2020
Author: Mackkkk
Views Total: 1,461 views
Official Page: Go to website
Last Update: February 11, 2020
License: MIT

Preview:

Convert HTML Document Into PDF – html2PDF

Description:

A configurable and user-friendly HTML to PDF converter built with pure JavaScript.

Features:

  • Split PDF into several pages or not.
  • Supports both Portrait and Landscape orientations.
  • Custom output type and file name.
  • Allows you to decide whether or not to load images from a server using CORS.
  • Custom PDF header & footer.
  • Callback functions.

How to use it:

1. Download and insert the ‘html2pdf.js’ script into the HTML document.

<!-- from local -->
<script src="src/html2pdf.js"></script>
<!-- from CDN -->
<script src="https://unpkg.com/html-pdf-adaptive"></script>

2. Or install the package via NPM and import the html2PDF as an ES module.

# NPM
$ npm install html-pdf-adaptive --save
import html2PDF from "html-pdf-adaptive"

3. Convert any content within the document into a PDF file.

const el = document.querySelector(".container");
html2PDF(el);

4. Possible options to config the HTML to PDF converter.

html2PDF(el,{

  // split PDF into several pages
  pagesplit: false,

  // p = portrait
  // l = for landscape
  orientation: "p",

  // unit
  unit: "pt",

  // PDF size: A1, A3, B1, Letter, Legal, ...
  format: "a4",

  // x/y offsets
  offset: {},

  // save, bloburl, file
  outputType: "save",

  // custom header/footer
  header: createHeaderAndFooterElement,
  footer: createHeaderAndFooterElement,
  useDefaultFoot: true,

  // or 'fixed'
  mode: "adaptive",

  // file name
  filename: "demo",
  
  // toggle CSS styles
  isToggleStyle: false,
  
  // attempt to load images from a server using CORS
  useCORS: false
  
});

5. Event handlers.

html2PDF(el,{

  onProgress: (percent, pageNum, bloburl) => {
    console.log(`${percent}%, ${pageNum}, ${bloburl}`)
  },

  onComplete: (bloburl) => {
    console.log(bloburl)
  }

});

You Might Be Interested In:


One thought on “Convert HTML Document Into PDF – html2PDF

Leave a Reply