How to use js PDF Library to generate PDF from HTML

by Vincy. Last modified on December 3rd, 2022.

In many websites, report generation will be a key component and core focus. For that, it will essentially include PDF conversion. The conversion process gets the source data from HTML, CSV or database.

The PDF generation tools help to create PDF with the content and format shown in the source HTML file. The js PDF library is one of the popularly used for generating PDF in JavaScript.

There are popular online tools for generating PDF from HTML. Also, there are integrable plugins that support PDF generation from the source template.

Those plugins can either be client-side or server-side libraries. Previously, we have used TCPDF for generating invoice PDF on the server-side.

In this article, we will see how to use the js PDF library for converting HTML to PDF in JavaScript.

It uses a popular and easy-to-use client-side library to generate PDF from HTML. Let’s step forward to see more in this tutorial.

HTML to PDF Result

What is inside?

  1. Popular online PDF conversion tool
  2. Features of js PDF library
  3. About this example
  4. File structure
  5. js PDF Installation and Imports
  6. Create HTML template source
  7. Generate PDF using js PDF in JavaScript

The js PDF is the popular PDF generation software available on the Internet.

If you want to generate a custom PDF with complex, multi-page documents, PDFKit is one of the best JavaScript libraries.

This example uses the client-side library js PDF for implementing the PDF conversion. We have already seen how to generate PDF with FPDF in PHP.

Features of js PDF library

The js PDF is one of the best client-side libraries used for generating PDF documents.

It has very good documentation, usage examples. The documentation shows code for running in React, Node and many.

Features:

  • It generates PDF with Unicode characters by setting fonts to create appropriate glyphs.
  • There are two API modes compact and advanced modes based on which the features vary. Default: compact.
  • The library files are in different formats used based on the type of loading mechanism.
  • It prepares PDF with basic text to graphical content.
  • It allows setting metadata on the PDF document by using the setProperties() method.

About this example

This example is to create code for generating PDF in JavaScript from a HTML source. It uses the js PDF library to do the conversion process on the client side.

A home page displays the UI template. It shows a button control to trigger the function to convert the HTML template into PDF. It’s like generating text/image watermark on a page.

The JavaScript created for this example imports and instantiates the js PDF library.

On clicking the “Generate” button, it set the conversion options and HTML source. Then it invokes the method to convert the source into a PDF format.

The js PDF callback specifies the filename to download and save the generated document.

File structure

The PDF conversion example has a minimal number of files. It has created to convert a simple HTML UI template into PDF.

The node_modules are generated by running the appropriate npm command. It contains all the dependencies required.

The convert.js contains the script to import js PDF and instantiate it.

The Template/html-template.php file contains the source HTML template to be converted.

The index.php is the landing page that renders the source HTML. It includes the node_modules and the js PDF instantiation script.

If you want to use additional font add the font file to this folder and supply it while generating PDF. When creating a custom captcha image we set the font for the captcha text.

HTML to PDF Conversion Files

js PDF Installation and Imports

Installation of js PDF is very simple. The manual recommends using the npm or yarn commands to install this package.

npm install jspdf --save
# or
yarn add jspdf

There is also CDN URL for loading the js PDF JavaScript library into your application.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.1/jspdf.umd.min.js"></script>

Or, you may use the UNPKG URL, yet another content delivery network for npm packages.

<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>

Create HTML template source

This HTML template is created for showing the event registration receipt. It contains registration acknowledgment, event details, contact information.

The information is static. You may also embed PHP scripts to show events from database results into the UI.

Template/html-template.php

<div class="event-detail">
	<h1>Thank you for registering with us.</h1>
	<h2>This is the acknowledgement of your registeration for attending the
		event.</h2>
	<p class="row">
		Event Name:<br />Machine learning introduction for kids
	</p>
	<p class="row">
		Event Date:<br />27 May 2021
	</p>
	<p class="row">
		Time:<br />10:30 AM
	</p>
	<p class="row">
		Venue:<br />AMC Graduate Center,<br>25, AMC Street,<br>New York, USA.
	</p>
	<p class="pdf-content">
		Contact our <a href="#">Organizers' Team</a> if you need any support.
	</p>
</div>

Below index.php includes this HTML template on the landing page. This page contains a button to invoke the PDF conversion on the click event.

It includes the required node modules of the js PDF package. It uses the UMD format files of the distribution.

As we use the .html() method, this file loads htmltocanvas package into the HTML head section.

index.php

<HTML>
<HEAD>
<TITLE>Generate PDF from HTML with js PDF</TITLE>
<link href="assets/css/style.css" type="text/css" rel="stylesheet" />
</HEAD>
<BODY>
	<div id="container">
		<div class="link-container">
			<button class="btn-generate" onclick="convertHTMLToPDF()">Generate</button>
		</div>
		<div id="html-template">
		<?php require_once __DIR__ . '/Template/html-template.php'; ?>
	</div>
	</div>
</BODY>
<-- Includes js PDF JavaScript files into the HTML -->
<script src="./node_modules/jspdf/dist/jspdf.umd.min.js"></script>
<script type="text/javascript"
	src="./node_modules/html2canvas/dist/html2canvas.js"></script>

<script src="assets/js/convert.js"></script>
</HTML>

Generate PDF using  js PDF in JavaScript

After loading the library and the template, it’s time to generate the script to convert HTML the PDF.

The following script imports js PDF by simply specifying the package name. It is not needed to specify the particular file name from the node modules.

This script instantiates the js PDF and invokes the functions to generate PDF in JavaScript.

It uses the .html() method which receives the selector object that contains the HTML source.  The second parameter of this function is the callback.

The callback invokes the method to save the PDF file with the specified filename.

function convertHTMLToPDF() {
	const { jsPDF } = window.jspdf;

	var doc = new jsPDF('l', 'mm', [1200, 1210]);
	var pdfjs = document.querySelector('#html-template');

	doc.html(pdfjs, {
		callback: function(doc) {
			doc.save("output.pdf");
		},
		x: 10,
		y: 10
	});
}

This image shows the UI for the event registration receipt displayed in the browser. It shows the default overlay by populating the specified filename and target directory.

If you want to open the PDF in a new tab instead of saving, the following line instead of the doc.save()

doc.output('dataurlnewwindow');

Generate and Save PDF

Conclusion

We have seen a lot related to the HTML to PDF JavaScript conversion job. This article has listed the available libraries to generate PDF from HTML. Also, it stated the possible input source types (HTML) for the conversion process.

I hope the example code will make you clear about how to use js PDF to generate PDF in JavaScript.

This example will save the developers’ effort to create conversion endpoints and handlers.

We have also seen few links to the examples of generating PDF in PHP with the help of alternative libraries.

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “How to use js PDF Library to generate PDF from HTML”

  • anurag gupta says:

    good,thank you so much ma’am,if you have any youtube channel,then please share .i am following your php blogs from last 5 years.

    • Vincy says:

      Hi Anurag,

      Thank you. As of now, I do not have a channel. Occasionally I publish videos within the article itself. I plan to soon launch a channel and will inform. Thanks.

  • redouane sehbani says:

    thank you very much vincy for your generosite , we love you so much what kind of women you are , you are helpfull thank you thank you thank you

  • Daniel Chiemelu says:

    Wow this would really help me for faster client side HTML to pdf conversion than server side

    Both are good but I’ll really try this out
    Love your tutorials Vincy

  • Shiv says:

    Will it help to convert dynamic html table (ex.invoice table) to pdf?

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page