How to convert HTML to PDF using Angular
Manuel Navarro
Posted on September 29, 2021
Yesterday, I was working on Hyperpanels' dashboard feature and my coworker @albertobeiz said the sentence every front-end developer fears:
Can we generate a PDF from that?
Let's see how I did it.
First, you'll need some help, so run the following commands:
npm i --save dom-to-image
npm i --save jspdf
Once we have this two packages, we can use them in our code
import { jsPDF } from 'jspdf';
import domtoimage from 'dom-to-image';
Add an ID to the HTML element you want to print:
<ion-content class="grid-container">
<div id="dashboard">
Finally, the function to turn that HTML into a PDF:
toPdf() {
const dashboard = document.getElementById('dashboard');
const dashboardHeight = dashboard.clientHeight;
const dashboardWidth = dashboard.clientWidth;
const options = { background: 'white', width: dashboardWidth, height: dashboardHeight };
domtoimage.toPng(dashboard, options).then((imgData) => {
const doc = new jsPDF(dashboardWidth > dashboardHeight ? 'l' : 'p', 'mm', [dashboardWidth, dashboardHeight]);
const imgProps = doc.getImageProperties(imgData);
const pdfWidth = doc.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
doc.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
doc.save('Dashboard for hyperpanels.pdf');
});
}
This will create a PDF that will be saved from your browser:
And voilá, your HTML turned into a PDF:
But as the comment show, not everyone is printing just a dashboard image, so let's improve our PDF.
First, let's add a new page:
doc.addPage()
Now we can add some text with another simple function
doc.text('My PDF Tutorial', 20, 20);
Also, we can add links with the following code:
doc.textWithLink('Vist DEV.to', 35, 35, { url: 'https://dev.to/' });
As a result we get the following PDF:
Let me know if you have any doubts or comments.
Happy coding!
Posted on September 29, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.