DEV Community

Cover image for Generate PDF of HTML Element in Browser

Posted on • Originally published at


Generate PDF of HTML Element in Browser

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.


Let us see a small implementation of the package html2pdf.


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">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="" defer></script>
    <script src="./script.js" defer></script>

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

Enter fullscreen mode Exit fullscreen mode


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

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

Originally published on

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

If you like my work and want to support it, you can do it here. I will really appreciate it.

Top comments (0)