How to convert HTML to PDF using Angular

_mnavarros

Manuel Navarro

Posted on September 29, 2021

How to convert HTML to PDF using Angular

Yesterday, I was working on Hyperpanels' dashboard feature and my coworker @albertobeiz said the sentence every front-end developer fears:

Alt Text

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
Enter fullscreen mode Exit fullscreen mode

Once we have this two packages, we can use them in our code

import { jsPDF } from 'jspdf';
import domtoimage from 'dom-to-image';
Enter fullscreen mode Exit fullscreen mode

Add an ID to the HTML element you want to print:

<ion-content class="grid-container">
    <div id="dashboard">
Enter fullscreen mode Exit fullscreen mode

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');
    });
}
Enter fullscreen mode Exit fullscreen mode

This will create a PDF that will be saved from your browser:

image

And voilá, your HTML turned into a PDF:

image

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()
Enter fullscreen mode Exit fullscreen mode

Now we can add some text with another simple function

doc.text('My PDF Tutorial', 20, 20);
Enter fullscreen mode Exit fullscreen mode

Also, we can add links with the following code:

doc.textWithLink('Vist DEV.to', 35, 35, { url: 'https://dev.to/' });
Enter fullscreen mode Exit fullscreen mode

As a result we get the following PDF:

Image description

Let me know if you have any doubts or comments.

Happy coding!

💖 💪 🙅 🚩
_mnavarros
Manuel Navarro

Posted on September 29, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to convert HTML to PDF using Angular
angular How to convert HTML to PDF using Angular

September 29, 2021