HTML to PDF in Javascript using jsPDF with Example Download

by Vincy. Last modified on August 22nd, 2022.

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

PDF creation is one of the most important features in building websites. Generate a PDF from HTML format will be useful in many places while building a website for generating reports.

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 a download.

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

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

The jsPDF JavaScript library supports different forms of input to create a PDF. For example, it uses “dompurify” dependency to implement HTML to PDF conversion.

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

Existing tools to create PDF

There are some popular tools that exist online to process HTML to PDF conversion. 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 simply converting HTML to PDF in JavaScript with few lines of code.

It uses the jsPDF library to build a custom PDF generator tool on the client-side.

We have already seen some jsPDF examples of converting HTML to PDF.  If you want an example of creating a 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.

It includes 2 steps to achieve the HTML to PDF generation in JavaScript.

  1. Step1: Read HTML data and show preview in the UI.
  2. Step2: Generate PDF and give the option to download the output file.

It handles JavaScript validation and file type restrictions before starting PDF generation. It contains JavaScript to import and instantiate jsPDF. It uses htmltocanvas dependency to convert uploaded HTML file content into PDF.

HTML to PDF example files

The below image shows the file structure of this HTML to PDF generation example.

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

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

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

JavaScript PDF Generation File

The node_modules contain all the required dependencies of the jsPDF library. 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 source of the HTML to PDF backend operation. 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. In the preview screen, the UI contains the “Generate” button to download the output PDF file to the browser.

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 will save your effort of creating a source for the initial testing of the HTML to PDF generation code.

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 preview page HTML to PDF format from it.

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 “Generate PDF” button in the below image is initially hidden. Then, on preview, the script will toggle it on.

The “Generate PDF” button’s on-click event will trigger the HTML to 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 HTML to PDF generation in JavaScript using jsPDF.

We have seen the possible types of input HTML sources for a PDF generation process.

The jsPDF is the best suitable library to implement the HTML to PDF generation tool.

This jsPDF example has a clear separation of reading the source content and generating HTML to 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

Share this page