Angular HTML to PDF htm2canvas jsPDF : Sometimes we need to export our HTML page into a PDF file. So how can we do this?

There are two helpful tools that we can use to do this.

The first is jsPDF that help us to produce a PDF file from an HTML content. The following is the simple example reported into the npm page:

// Default export is a4 paper, portrait, using milimeters for units
let doc = new jsPDF()
doc.text('Hello world!', 10, 10)
doc.save('a4.pdf')

Unfortunately this tools doesn’t support CSS page settings, so if we need to support it, we should use the html2canvas.

After we had import the npm packages of this tool, into our class we can create a method that esports the HTLM content into PDF:

import * as jsPDF from 'jspdf'
import * as html2canvas from "html2canvas"; export class MyComponent
{ public printPdf() { // Get the element to export into pdf let pdfContent = window.document.getElementById("pdfContent"); // Use html2canvas to apply CSS settings html2canvas(pdfContent).then(function (canvas) { var img = canvas.toDataURL("image/png"); var doc = new jsPDF(); doc.addImage(img, 'JPEG', 20, 20); doc.save('test.pdf'); }); }
}

If we had a CSS file with @media print queries, the solution is to write JavaScript code to set the the CSS settings to the elements that we wan to export into the PDF file.

// Get the element to export into pdf
let pdfContent = window.document.getElementById("pdfContent"); // Set the style like in the CSS print @media query
pdfContent.style.margin = "auto";
pdfContent.style.padding = "2px";
// and so on

Read also : How to click on html button from the type script file in Angular 2 ?

Laisser un commentaire