Converting HTML into Multi-page PDF using JavaScript library

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

Creating PDF via coding is an important functionality in a web application. A data-centric application needs this for creating reports. The PDF may have any kind of data like tables, charts, image graphics and more.

It is very simple to generate a single-page PDF from HTML. But splitting a long UI template into a multi-page PDF is slightly tedious to implement.

There are online converter tools to generate PDF from Word and HTML documents.

Also, there are many integrative libraries to generate PDF from HTML via programming. But, this example is with a simple code for generating multi-page PDF on the client-side.

I used the jsPDF JavaScript library to convert the HTML to PDF. In a previous example, we have seen how to create a simple PDF by using this library.

The jsPDF library contains more features to generate PDF documents on the client-side with JavaScript.

Multi Page PDF Auto Split

What is inside?

  1. About this example
  2. File structure
  3. Ways to split HTML source to multi-page PDF
  4. HTML template source to convert into PDF
  5. Building interface with source template and conversion controls
  6. Converting HTML into PDF in JavaScript
  7. Multi-page PDF conversion output

About this example

The example code is for converting a HTML source document into a multi-page PDF.

The input HTML will display a lengthy UI in the browser. It shows a mixed type of HTML elements like images, heading, links and more.

This code contains three HTML templates to include in the landing page.  The PDF content splitting can be template-based or overall content-based.

The landing page will have a dropdown field. It has options to choose the type of splitting mechanism to generate a multi-page PDF. It contains a button control to trigger PDF conversion.

It uses the jsPDF library and its dependencies to implement the PDF generation. I used htmltocanvas dependency to prepare the canvas from the HTML template view.

The generated PDF is to download and save by using the jsPDF save action on the client-side.

File structure

The below image shows the example file structure. It contains the client-side UI templates, CSS and JavaScript assets, and images.

The index.php is the home that includes the three HTML templates from the /Template/ directory.

It has a custom JavaScript convert.js file. It instantiates the js PDF library and invokes the multi-page PDF generation process.

HTML to Multi-Page PDF Files

Ways to split HTML source into multi-page PDF

Breaking a lengthy HTML to multiple PDF pages can be done by two types of splitting mechanisms.

  1. Auto splitting by setting the PDF per-page length
  2. Add HTML chunks to the target PDF resource.

This code handles both the methods for splitting the document into a multi-page PDF.

HTML template source to convert into PDF

This section shows the three HTML templates created for this example. These templates show content using HTML elements.

It shows heading, image, paragraphs and bordered box containers. It shows sample HTML content styled with CSS. After conversion, this style will be replicated in the output multi-page PDF.

Template/html-template.php

<h1>Welcome to visit our event portal</h1>
<img class="banner" src="event-banner.jpeg" width="100%" height="400px" />
<p class="description">Donec id leo quis felis vehicula bibendum sit amet ut tellus. Sed
	sagittis aliquet rhoncus. Pellentesque vulputate nunc ultricies,
	egestas augue ac, ullamcorper dui. Etiam diam mauris, molestie in purus
	a, venenatis pretium leo. Sed id metus eleifend, scelerisque neque id,
	posuere arcu. Nunc cursus et dui quis fringilla. In in turpis feugiat
	diam porttitor tempus. In hendrerit diam dolor, id pellentesque ante
	volutpat a. Nam tortor sapien, semper ut justo et, accumsan imperdiet
	sem. Sed euismod nunc vitae dolor porttitor ullamcorper. Donec sed
	lacinia dui. Nunc sed suscipit erat. Phasellus euismod ultrices velit,
	hendrerit tempor diam elementum ut.
</p>

Template/html-template1.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>

Template/html-template2.php

<h2>Contact Us</h2>
<p>
	T2, Ruth Isabel Villa<br /> 12, RGT Street,<br /> New york.
</p>

<h2>Contact Numbers</h2>
<p>
	Phone: 8909878.<br /> Fax: 678965.<br /> Mobile: 9878978.
</p>

Building interface with source template and conversion controls

This is the landing page HTML that includes all template files we have seen in the last section.

It displays a dropdown option to choose the HTML content splitting mechanism.

There are two options, auto splitting and template-based splitting. The auto splitting is a default one that skips to the next page once the specified length is reached.

By clicking the button, it generates the multi-page PDF and shows the overlay to save the document.

index.php

<!doctype html>
<HTML>
<HEAD>
<TITLE>Convert HTML to multi-page Pdf</TITLE>
<link href="assets/css/style.css" type="text/css" rel="stylesheet" />
</HEAD>
<BODY>
	<div id="container">
		<div class="link-container">
			<select id="convertion-type">
    			<option value="split">Split HTML to Multi-Page PDF</option>
    			<option value="">Add HTML to PDF Page</option>
			</select>
			<button class="btn-convert">Convert
				HTML to PDF</button>
		</div>
		<div class="single-html-block">
			<div id="html-template">
				<?php require_once __DIR__ . '/Template/html-template.php'; ?>
			</div>

			<div id="html-template1">
			<?php require_once __DIR__ . '/Template/html-template1.php'; ?>
			</div>

			<div id="html-template2">
				<?php require_once __DIR__ . '/Template/html-template2.php'; ?>
			</div>

		</div>
	</div>
</BODY>
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script
	src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

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

assets/css/style.css

body {
	font-family: Arial;
	color: #211a1a;
	font-size: 0.9em;
	margin: 0 auto;
	line-height: 30px;
	max-width: 800px;
}

.heading {
	color: #211a1a;
	font-weight: bold;
	font-size: x-large;
	white-space: nowrap;
	margin: 20px auto;
	text-align: center;
}

#html-template {
	text-align: center;
	margin: 30px 0px 60px 0px; 
}

#html-template1 {
	background: #ffffff;
	padding: 20px;
	border: #E0E0E0 1px solid;
	border-radius: 3px;
}

#container {
	margin: 30px;
}

.btn-convert {
	padding: 10px 20px;
    border-radius: 20px;
    margin: 10px 0px;
    display: inline-block;
    cursor: pointer;
    color: #211c1c;
    background-color: #28a745;
    border: #23943d 1px solid;
}

a {
	color: #007bff;
}

.link-container {
	text-align: right;
}

#html-template2 {
	margin: 30px 0px 60px 0px; 
	padding: 20px;
	border: #E0E0E0 1px solid;
	border-radius: 3px;	
}

#convertion-type {
	border: #1d1d1d 1px solid;
    border-radius: 20px;
    PADDING: 8px 20px;
    margin-right: 15px;
}

.description {
	text-align: justify;
}

Converting HTML into PDF in JavaScript

This JavaScript applies conditional check on the form data. It gets the chosen splitting mechanism from the form. It invokes the multi-page PDF generation with different methods.

The addHTMLToPDFPage()method calls htmltocanvas by supplying the particular template object reference.

The converHTMLToCanvas() receives parameters to trigger the add-new page and save action.

The splitHTMLtoMultiPagePDF() the method applies auto splitting on the PDF document. It prepares the image canvas from the HTML document. Then carves the image canvas by PDF per-page length.

The PDF page length and the total number of pages are computed. Then, the htmltocanvas uses them to render canvas into the page.

assets/js/convert.js

$(document).ready(function(){
	$(".btn-convert").click(function(){
		var convertionType = $("#convertion-type").val();
		if(convertionType == "split") {
			splitHTMLtoMultiPagePDF();
		} else {
			addHTMLToPDFPage();
		}
	});
});

function addHTMLToPDFPage() {

	var doc = new jsPDF('p', 'pt', [$("body").width(), $("body").height()]);
	
	converHTMLToCanvas($("#html-template")[0], doc, false, false);
	
	converHTMLToCanvas($("#html-template1")[0], doc, true, false);
	
	converHTMLToCanvas($("#html-template2")[0], doc, true, true);
}

function converHTMLToCanvas(element, jspdf, enableAddPage, enableSave) {
	html2canvas(element, { allowTaint: true }).then(function(canvas) {
		if(enableAddPage == true) {
			jspdf.addPage($("body").width(), $("body").height());
		}
		
		image = canvas.toDataURL('image/png', 1.0);
		jspdf.addImage(image, 'PNG', 15, 15, $(element).width(), $(element).height()); // A4 sizes
		
		if(enableSave == true) {
			jspdf.save("add-to-multi-page.pdf");
		}
	});
}

function splitHTMLtoMultiPagePDF() {
	var htmlWidth = $(".single-html-block").width();
	var htmlHeight = $(".single-html-block").height();
	var pdfWidth = htmlWidth + (15 * 2);
	var pdfHeight = (pdfWidth * 1.5) + (15 * 2);
	
	var doc = new jsPDF('p', 'pt', [pdfWidth, pdfHeight]);

	var pageCount = Math.ceil(htmlHeight / pdfHeight) - 1;


	html2canvas($(".single-html-block")[0], { allowTaint: true }).then(function(canvas) {
		canvas.getContext('2d');

		var image = canvas.toDataURL("image/png", 1.0);
		doc.addImage(image, 'PNG', 15, 15, htmlWidth, htmlHeight);


		for (var i = 1; i <= pageCount; i++) {
			doc.addPage(pdfWidth, pdfHeight);
			doc.addImage(image, 'PNG', 15, -(pdfHeight * i)+15, htmlWidth, htmlHeight);
		}

		doc.save("split-to-multi-page.pdf");
	});
};

Multi-page PDF conversion output

This screenshot shows the PDF output. We can see the document is split based on the template.

It generates the PDF by selecting the second splitting mechanism from the dropdown.

The first page displays the template with the image element. The second and third pages show the receipt and contact details from the templates.

Add Multiple Page to PDF

Conclusion

Creating a report in PDF format is a most wanted functionality of an application. For a perfect PDF document with good screen readability/accessibility.

Thus, we have seen how to convert a lengthy HTML into a multi-page PDF document. We have shown options to the user to choose the content splitting mechanism.

The client-side jsPDF library and its dependencies made the job easy to generate the PDF. We have converted a static HTML. Previously, we also saw examples to convert dynamic data into PDF using FPDF.

I hope, this code will help you to learn this conversion process quickly and easily. Let us see more examples of PDF conversion in the upcoming tutorials.
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 “Converting HTML into Multi-page PDF using JavaScript library”

Leave a Reply

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

↑ Back to Top

Share this page