Wednesday, July 25, 2018

How to Export/Generate html to pdf in web application

In this article, We are going to see the tutorials and examples to convert HTML to PDF using javascript and angular. In Web applications, Normally we have a data/images render 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 in client side.
We will see the below tutorial about converting HTML elements like div or tables  to PDF document and download to it your system

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 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 canvas using Html2Canass library, then copy this canvas/image file to pdf using jsPDF library
Steps for the conversion process
1. Create and initialize jspdf object
2. Add image to this document javascript code to generate pdf

button exportButton is clicked, using jquery we called convertPDF javascript method. JsPDF is the class used and syntax is jsPDF(orientation, unit, format) Parameters are
orientation - p portrait -l landscape these are basically 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 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 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 geneated with 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 output of code Export html to pdf using typescript javascript