How to use jsPDF In HTML
On the client side PDF file creation is possible thanks to the jsPDF JavaScript library. It provides a simple approach for creating and downloading PDF files directly in the browser by combining HTML, CSS, and JavaScript. Documents like reports, invoices, tickets, etc. that need to be printed or delivered are routinely created using this library.
Syntax:
// Loading the jsPDF library
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js">
</script>
// Getting the HTML element to convert into PDF
var element = document.getElementById("element selector");
// Creating a new jsPDF object
var pdf = new jsPDF();
// Use jsPDF's 'fromHTML' method to add HTML element to PDF
pdf.fromHTML(element);
// Saving the PDF with specified file name
pdf.save("file");
Example: In this example, we will see how we will convert the HTML and CSS code into a pdf document using the jsPDF library in javascript. jsPDF offers a straightforward API to produce PDF files and has capabilities like text formatting, font embedding, and picture support. By simply clicking on the DOWNLOAD PDF button we will able to download the pdf version of the HTML and CSS document. We have initialized some text which should be there in the pdf. The syntax of using jsPdf is already defined.
HTML
<!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" > < script src = "https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js" > </ script > </ head > < body > < div class = "GFG" > < h1 style = "color: tomato;" > w3wiki </ h1 > < h2 >Founded by Sandeep Jain</ h2 > < p >A Computer Science portal for geeks.</ p > < p > It contains well written, well thought and well explained computer science and programming articles. </ p > </ div > < button id = "btn" > PDF MAKER </ button > < script > var button = document.getElementById("btn"); button.addEventListener("click", function () { var doc = new jsPDF(); var pdf = document.querySelector(".GFG"); doc.fromHTML(pdf); doc.save("GFG.pdf"); }); </ script > </ body > </ html > |
Output:
How to Add HTML and CSS into PDF ?
HTML and CSS must now regularly be converted into PDF format during web development. PDFs enable the creation of printable documents, information exchange across several platforms, and preserving a webpage’s original layout. There are several ways to convert HTML and CSS to PDF files, from simple online tools to complex programming libraries.
These techniques may generate PDFs automatically using HTML and CSS code or manually using third-party applications. Hence, interactive, visually beautiful web pages that are straightforward to convert to PDF for sharing or archiving may be created by combining HTML and CSS. In this article, we’ll see how to add HTML and CSS to PDF.