Bibek Kakati
Bibek's Blog

Bibek's Blog

Generate PDF of HTML Element in Browser

Generate PDF of HTML Element in Browser

HTML to PDF using JavaScript

Bibek Kakati

Published on Jun 4, 2021

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Hello everyoneπŸ‘‹

In this article, we are going to see how we can generate a PDF of any HTML element in the browser i.e, entirely client-side.

We will use the package html2pdf to generate the PDF.

html2pdf is using html2canvas to convert the HTML element to canvas and then into an image. Then it generates the PDF of the image with the help of jsPDF.

If you want to know more about html2canvas, check out this article.

Implementation

Let us see a small implementation of the package html2pdf.

index.html

A basic HTML page, where the package's bundle link is included.

Created a div block of simple content and a export PDF button. We will be generating a PDF of the div whose id is view on clicking the export PDF button.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML2PDF</title>
    <script src="https://raw.githack.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.js" defer></script>
    <script src="./script.js" defer></script>
</head>

<body onload="main()" align="center">
    <div id="view" align="center">
        <h1>Export PDF</h1>
        <h3>Using HTML2PDF</h3>
    </div>
    <button id="export-pdf">Export PDF</button>
</body>

</html>

script.js

JavaScript file containing the main method which will be invoked once the site loads and listening for the onclick event on the export PDF button.

On clicking the export PDF button, the html2pdf method will be called which takes the reference to the element (div) as its argument.

function main() {
    var view = document.getElementById("view");
    var exportPDF = document.getElementById("export-pdf");
    exportPDF.onclick = (e) => html2pdf(view);
}

After clicking the button, the PDF will be generated and downloaded directly to your system.

We can also pass some configuration options in the html2pdf method to handle image type, quality, filename etc. To know more about it, check here.

Note: Image-based PDF's are non-searchable.


Github repo: PDF-Generator

Try it out: Live


Thank you for reading πŸ™

If you enjoyed this article or found it helpful, give it a thumbs-up πŸ‘

Feel free to connect πŸ‘‹

Twitter | Instagram | LinkedIn

Did you find this article valuable?

Support Bibek Kakati by becoming a sponsor. Any amount is appreciated!

See recent sponsors |Β Learn more about Hashnode Sponsors