HTML to PDF in Javascript using jsPDF with Example Download

by Vincy. Last modified on July 13th, 2021.

HTML to PDF in JavaScript is easier than a server-side implementation to PDF creation.

PDF creation is one of the most important feature in building websites. These are some of the PDF creator tools I built for my clients while providing freelance services.

  1. Client assessment tool – Medication plan report
  2. Sales assessment tool – API via Amazon sales report
  3. Material management tool – Stock report

These tools convert HTML templates or database backed dynamic data into a PDF and provide download.

When adding a feature to create PDF from HTML, it should be flexible to get the source in any form. The different forms of HTML source for the PDF creation process can be,

  1. HTML string
  2. HTML object with selector reference
  3. HTML files

jsPDF JavaScript library supports different forms of input to create a PDF. For example, it uses dompurify dependency to create PDF from HTML.

The jsPDF is the best JavaScript library to create PDF on the client side.  We have seen jsPDF example already for converting HTML source into PDF. This article will create an example to get HTML file to create PDF in JavaScript.

Existing tools to create PDF

There are some popular tools that exist online to convert PDF from HTML. You may find the best PDF readers and converters in the linked article.

Dompdf is a HTML to PDF converter library that converts HTML files to PDF. It also accepts the manually entered HTML markup. Download Dompdf from Github to install it into an application.

About this jsPDF example

This example is for converting HTML files into a PDF in JavaScript. It uses the jsPDF library to build a custom PDF converter tool on the client side.

We have already seen some jsPDF examples of converting HTML into PDF.  We saw how to create multi-page PDF from a long HTML document.

This example allows users to browse the input HTML file. The landing page shows a form UI with a file input field to choose the source HTML file.

This example code includes 2 steps to create PDF in JavaScript.

  1. Step1: Show preview
  2. Step2: Create and save PDF

It handles JavaScript validation and file type restriction before start generating PDF. It contains JavaScript to import and instatiate jsPDF. It uses htmltocanvas dependency to convert uploaded HTML file content into PDF.

Example Script File structure

The below image shows the file structure of this JavaScript PDF creation example.

It contains a sample HTML template in the Template directory. You may use this for testing this example script.

The index.php file has the HTML form UI to browse the file resource.

It processes the two-step PDF creation with the convert.js file. It reads HTML file and sends the content to the jsPDF dependent library function. It uses HTML content to create the output PDF in JavaScript.

JavaScript PDF Generation File

The node_modules includes all the required dependencies of the jsPDF. By running the appropriate npm command it generates the node_modules.

npm install jspdf --save

Create UI to upload source HTML

Add this script to show a form to choose the HTML files for the PDF creation. It contains a submit button that calls the JavaScript to read the uploaded HTML content.

It has a target container to show the preview of the uploaded file content. Below preview, the UI will show control to trigger the JavaScript PDF creation.

index.php

<HTML>
<HEAD>
<TITLE>Convert HTML file to PDF</TITLE>
<link href="./assets/css/style.css" type="text/css" rel="stylesheet" />
<script src="./vendor/jquery/jquery-3.2.1.min.js"></script>
</HEAD>
<BODY>
    <div id="container">
        <h1>Convert HTML file to PDF</h1>
        <form name="foo" method="post" class="input-form"
            enctype="multipart/form-data">
            <div class="row">
                <label class="form-label">Upload HTML file: </label> <input
                    type="file" id="fileUpload" name="file"
                    class="input-file" accept=".html,.htm">
            </div>
            <div class="preview">
                <div id="temp-target"></div>
            </div>
            <div class="row">
                <input type="button" value="Show Preview"
                    class="btn-preview" onclick="readHTML()"><span
                    id="error-message" class="error"></span> 
                
                <input
                    type="button" value="Create PDF"
                    class="btn-generate" onclick="converHTMLFileToPDF()">
            </div>

        </form>
    </div>
    <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>
</BODY>
</HTML>

This is a sample HTML template created for this Javascript PDF example. You may choose any example HTML file from your computer. This is just to support you to save your effort of creating a source HTML to test this example. The download below also contains this HTML template.

Template/html-template.html

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

I have used simple CSS for designing the source template. It helps to form an event registration receipt in HTML.

assets/css/style.css

#container {
    -webkit-font-smoothing: antialiased;
    font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
    font-size: .9em;
    color: #1e2a28;
    width: 740px;
    margin: 0 auto;
    padding: 12px 12px 0px 36px;
}

.input-form {
    background: #ffffff;
    padding: 10px 25px;
    border-radius: 3px;
    text-align: left;
    border: #ccc 1px solid;
}

.row {
    margin: 18px 0;
}

.input-file {
    border-radius: 3px;
    border: #a6a6a6 1px solid;
    padding: 10px;
    margin-bottom: 10px;
}

.btn-preview {
    padding: 10px 30px;
    border-radius: 3px;
    display: inline-block;
    cursor: pointer;
    color: #211c1c;
    background-color: #36de5c;
    border: #27a544 1px solid;
}

.btn-generate {
    padding: 10px 30px;
    border-radius: 3px;
    display: inline-block;
    cursor: pointer;
    color: #211c1c;
    background-color: #36de5c;
    border: #27a544 1px solid;
    display: none;
}

.preview {
    display: none;
    padding: 20px;
    border-radius: 3px;
    box-shadow: 0 1px 6px rgb(32 33 36/ 28%);
    border-color: rgba(223, 225, 229, 0);
}

.heading {
    text-align: center;
}

.form-label {
    display: block;
    margin-bottom: 5px;
}

.error {
    color: #ee0000;
    margin-left: 10px;
}

jsPDF function to create PDF in JavaScript

In JavaScript, the PDF conversion is implemented in two steps. First, it reads the file content and shows the preview in the UI. Then, it gets the preview content and creates PDF in JavaScript.

The convert.js file do this using two functions readHTML() and convertHTMLToPDF().

The readHTML() gets the uploaded file temp path and reads the content using FileReader(). It loads the preview into the specified target. This step helps users assure of the content before calling the JavaScript PDF conversion.

The convertHTMLFileToPDF() imports the jsPDF library and instatiate it. It calls the .html() that depends on htmltocanvas. It converts the HTML shown in the preview into PDF in JavaScript.

Then finally, the .save() method in the callback prompts to download the created PDF document.

assets/js/convert.js

function readHTML() {
	// get the HTML source file path
	var path = document.getElementById("fileUpload").files[0];
	var contents;
	$("#error-message").html("");
	$("#fileUpload").css("border", "#a6a6a6 1px solid");
	if ($(path).length != 0) {
		var r = new FileReader();
		r.onload = function(e) {
			// read HTML file content
			contents = e.target.result;
			// show JavaScript PDF preview
			$(".preview").show();
			$("#temp-target").html(contents);
			
			$(".btn-preview").hide();
			$(".btn-generate").show();
		}
		r.readAsText(path);
	} else {
		$("#error-message").html("required.").show();
		$("#fileUpload").css("border", "#d96557 1px solid");
	}
}

function converHTMLFileToPDF() {
	const { jsPDF } = window.jspdf;
	var doc = new jsPDF('l', 'mm', [1200, 1210]);

	var pdfjs = document.querySelector('#temp-target');

	// Convert HTML to PDF in JavaScript
	doc.html(pdfjs, {
		callback: function(doc) {
			doc.save("output.pdf");
		},
		x: 10,
		y: 10
	});
}
   

Output screenshot to upload HTML file

This screenshot shows the UI frontend with the file upload option. It displays a sample preview of the uploaded HTML.

The “Create PDF” button in the below image is initially hidden. Then, on preview, the script will toggle it on.

The “Create PDF” on-click event will trigger the JavaScript PDF conversion to save the .pdf file.

javascript pdf generation from html file

Conclusion

The example script created in this article explains how easy it is to perform PDF conversion in JavaScript using jsPDF.

We have seen the possible types of input HTML sources to a PDF creation process.

The jsPDF is the best suitable library to implement the JavaScript PDF creation tool.

This jsPDF example has a clear separation of reading the source content and create PDF in JavaScript. The show-preview step may help to have a glance before downloading the PDF. You download the example script below.

Download

↑ Back to Top