Generate PDF of HTML Element in Browser
Bibek
Posted on June 4, 2021
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
Originally published on blog.bibekkakati.me
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.
Posted on June 4, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.