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!
Top comments (3)
El tamaño de mi pdf es considerablemente alto, alguna idea de como solucionarlo? Pesan 7mb :c
Does this approach works with generating reports, that involves more than one pages? Is the text selectable in pdf and does it have clickable links?
Hi!
Thank you for your comment, I'll expand the article with your questions answered and some examples.
Yes, by using the addPage function included with jsPDF
In my example it isn't since I'm appending the complete image of my report but you can do as follows:
I think it's possible but I've haven't done it myself, I'll try and let you know.
Thanks for your comment! :)