How to Export/Generate HTML to pdf in javascript web application

In this article, We will have a look into tutorials and examples to convert HTML to PDF using javascript and angular. In Web applications, Normally we have data/images rendered on a webpage in different format ways as below.

  • Dynamic data is populated in the table
  • Images are rendered on the web page
  • Any element under HTML DOM elements example DIV

To Export the generated HTML on the webpage to PDF, we have to write code to handle this.

JsPDF opensource library is a popular javascript framework to handle pdf/HTML manipulation on the client-side. We will see the below tutorial about converting HTML elements like div or tables to PDF documents and downloading them to it your system

How to Export/Generate HTML to PDF Using Javascript and JQuery

First configure jsPDF js file in script tag. Better use CDN package which is always the latest code, Also add JQuery in a script tag

<script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
<script
  crossorigin="anonymous"
  src="https://code.jquery.com/jquery-3.2.1.min.js"
></script>

Html table example for pdf

<div id="print-container">
  <h3>Employees List</h3>
  <table style="width:100%">
    <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Salary</th>
    </tr>
    <tr>
      <td>1</td>
      <td>John</td>
      <td>5000</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Franc</td>
      <td>50000</td>
    </tr>
    <tr>
      <td>3</td>
      <td>Ram</td>
      <td>4000</td>
    </tr>
  </table>
</div>
<button id="exportButton">Export table To PDF</button>

Table data is rendered on the page. To convert it to PDF, the first step is to convert this table to the canvas using the Html2Canvas library, then copy this canvas/image file to pdf using the jsPDF library Steps for the conversion process

  • Create and initialize jspdf object
  • Add image to this document javascript code to generate pdf
$("#exportButton").click(function () {
  convertPdf();
});
var doc = new jsPDF();

function convertPdf() {
  html2canvas($("#print-container")[0], {
    onrendered: function (canvas) {
      var imgWidth = 208;
      var pageHeight = 295;
      var imgHeight = (canvas.height * imgWidth) / canvas.width;
      var img = canvas.toDataURL("image/png");
      var doc = new jspdf("p", "mm", "a4"); // A4 size page of PDF
      doc.addImage(img, "PNG", 0, 0, imgWidth, imgHeight);
      doc.save("test.pdf");
    },
  });
}

When export button is clicked, using jquery we called convertPDF javascript method.

JsPDF is the class used. syntax is

jsPDF(orientation, unit, format);

Parameters:

  • orientation: p portrait -l landscape these are used in printing documents in windows.
  • format: pdf format like A4, A5
  • unit: coordinate points measurement - pt points, - cm centimeters using

typescript in Angular Applications

As we have seen an example using plain Javascript. The angular framework is based on typescript language. We have to do some configuration angular CLI apart from HTML/typescript component code. jsPDF provides npm packages for jsPDF. First install jsPDF and html2canvas packages html2canvas - HTML element to canvas image jspdf - canvas image to pdf document

npm install jspdf --save
npm install html2canvas --save

Install both dependencies in your angular project. Angular CLI configuration angular-cli.json”:


 "scripts": [
               "../node_modules/html2canvas/dist/html2canvas.min.js"

            ]

if you don’t configure this script element in an angular cli json file, we used to get the following error: ERROR TypeError: html2canvas_1.default is not a function

html code for generating pdf single page

import * as jspdf from 'jspdf';
import * as html2canvas from "html2canvas"

// this generates single page
convertToPdf(){
    var data = document.getElementById('print-container');
    html2canvas(data).then(canvas => {
      // Few necessary setting options
      var imgWidth = 208;
      var pageHeight = 295;
      var imgHeight = canvas.height * imgWidth / canvas.width;
      var heightLeft = imgHeight;

      const contentDataURL = canvas.toDataURL('image/png')
      let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
      var position = 0;
      pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)

      pdf.save('report.pdf'); // Generated PDF
          });

}

Generating multiple pdf pages

multiple pages can be generated with the below script of code
      heightLeft -= pageHeight;
      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        pdf.addPage();
        pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }

Component html code for export pdf

<button click="" converttopdf="" id="exportButton">Export table To PDF</button>

Output HTML to pdf pages.

Please see the below screenshot for the output of the code

Export HTML to pdf using typescript javascript