Convert HTML to PDF using jsPDF JavaScript Library

by Vincy. Last modified on May 31st, 2021.

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

The HTML to PDF converter tool helps to generate PDF with the content and format shown in the source HTML file.

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

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

This article creates an example code for converting HTML to PDF using 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 HTML to PDF converter
  2. Features of jsPDF library
  3. About this example
  4. File structure
  5. jsPDF Installation and Imports
  6. Create HTML template source
  7. Convert HTML to PDF using jsPDF JavaScript

jsPDF is the popular online HTML to PDF converter 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 jsPDF for implementing HTML to PDF conversion. We have already seen how to generate PDF with FPDF in PHP.

Features of jsPDF library

The jsPDF 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 convert a simple HTML to PDF format. It uses the jsPDF library to do the conversion process on the client-side with JavaScript.

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

By clicking this button, it imports and instantiates the jsPDF library.

Then, it set the options and HTML source then invokes the method to convert into PDF format.

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

File structure

The HTML to 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 created with the dependencies of using the jsPDF library.

The convert.js contains the import and the instantiation script. Then, the actual conversion process follows with this reference.

The source HTML to be converted into the PDF is in the Template/html-template.php file.

The landing page contains the source HTML and includes the node_modules required.

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

jsPDF Installation and Imports

Installation of jsPDF 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 this library into the 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 trigger the HTML to PDF conversion on click.

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

As we use the .html() method, this file has htmltocanvas dependency included.

index.php

<HTML>
<HEAD>
<TITLE>Convert HTML to 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()">Convert HTML to PDF</button>
		</div>
		<div id="html-template">
		<?php require_once __DIR__ . '/Template/html-template.php'; ?>
	</div>
	</div>
</BODY>

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

Convert HTML to PDF using jsPDF JavaScript

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

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

This script instantiates the jsPDF and invokes the functions to convert HTML to PDF.

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 conversion job. This article has listed the available options to implement PDF conversion. Also, it stated the applicable source type (HTML) for the conversion.

I hope the example code will make you clear about how to generate PDF on the client-side.

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

Comments to “Convert HTML to PDF using jsPDF JavaScript Library”

  • 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

Leave a Reply

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

↑ Back to Top