Generate PDF from HTML in a browser is one of the most wanted utilities. There are many hosted solutions generating PDF online from the posted source.
When using online tools the required features are not available with one tool. The users have to compromise some of their needs when depending on the online tools.
But, developers like us need not compromise. We can create a custom utility to generate PDF from HTML on our own.
There is a quick solution to generate PDF from an HTML page. The browser’s print wizard has the “Save as PDF” option along with the preview panel.
This JavaScript triggers the browser’s print action. Then, it supplies a particular portion of the HTM to print.
<div class="outer-content">
<div id="pdf-content">
<h2>PDF Page Title</h2>
<hr>
<p>
How to generate a pdf from the <i>UI content</i> is easy.
</p>
<p>
This describes how to <strong>generate pdf from HTML</strong> using
programming.
</p>
</div>
<hr>
<button id="btn-generate">Generate PDF</button>
</div>
<!DOCTYPE html>
<html lang="en">
<body>
<?php require_once __DIR__ . '/template.html'; ?>
</body>
<script>
var buttonElement = document.querySelector("#btn-generate");
buttonElement.addEventListener('click', function() {
var pdfContent = document.getElementById("pdf-content").innerHTML;
var windowObject = window.open();
windowObject.document.write(pdfContent);
windowObject.print();
windowObject.close();
});
</script>
</html>
I am sure this is not enough to claim that the PDF generation is implemented :-)
For creating a full-fledged solution to generate PDF from HTML we have to go for using libraries.
There are popular libraries available in the market to build a PDF generation tool for an application.
In this tutorial, we will see some of the top libraries that support PDF generation. For each library, we will see how-to steps for the integration and development.
This section listed the libraries used to generate PDF from HTML in this article. It interlinks the appropriate example code below to land you in the right place.
The HTML to pdf and jspdf sections have more than one example. It is to know how to generate PDF from HTML containing complex nodes or containers. Example: HTML tables, image galleries and etc.
The HTML to pdf library method is a way to generate PDF from HTML. It is a two-step process to get a standard PDF output.
First, get the CDN URL of this library from an authentic source. Then, follow these two steps to get an output PDF file.
The basic life cycle to generate PDF from HTML using this library is shown in the below flow chart.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Generate PDF from HTML using html to pdf library</title>
<!-- CDN URL - html2pdf library -->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
</head>
<body>
<?php require_once __DIR__ . '/template.html'; ?>
<script>
var buttonElement = document.querySelector("#btn-generate");
buttonElement.addEventListener('click', function() {
var pdfContent = document.querySelector("#pdf-content");
html2pdf().from(pdfContent).save();
});
</script>
</body>
</html>
Unlike the above example, it sends an array of options to generate PDF from HTML. It overrides the default file name, margin, orientation and more defaults as specified.
var pdfContent = document.querySelector("#pdf-content");
var optionArray = {
margin: 10,
filename: 'output.pdf',
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
// html to pdf generation with the reference of PDF worker object
html2pdf().set(optionArray).from(pdfContent).save();
In old monolithic method, the html2pdf() accepts the HTML reference and options. To generate PDF from HTML DOM object reference and JSON options are supplied like,
html2pdf(pdfContent, optionArray);
To generate PDF from HTML some libraries need a document definition of the markup. The jsPDF is popularly known for its feature of getting the HTML input in any format.
For example, it is capable of accepting HTML in the following formats.
This example creates a basic usage reference of jsPDF to generate PDF from HTML template. It includes an external template source in the UI container.
The JavaScript maps an event handler to the “Generate PDF” button found in the HTML template.
On clicking the button, the script initiates jsPDF with the appropriate PDF specification. It uses .html() handling of the jsPDF library tp generate PDF from HTML object supplied as an argument.
This hander defines a callback function that executes the HTML to PDF conversion. It saves or opens the generated PDF document in the callback.
This script uses the jsPDF CDN URL. If you want to download this jsPDF, the official documentation contains the npm command to install this library.
<!DOCTYPE html>
<html>
<head>
<title>jsPDF Example</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
</head>
<body>
<?php require_once __DIR__ . '/template.html'; ?>
<script>
var buttonElement = document.querySelector("#btn-generate");
buttonElement.addEventListener('click', function() {
const { jsPDF } = window.jspdf;
var doc = new jsPDF("p", "pt", 'a4');
var pdfContent = document.querySelector("#pdf-content");
// Generate PDF from HTML using right id-selector
doc.html(pdfContent, {
callback: function(doc) {
doc.save("download.pdf");
},
x: 10,
y: 19
});
});
</script>
</body>
</html>
The jsPDF library is one of the best libraries used to generate PDF from HTML on the client-side. We have seen more examples in previous articles.
This example is for generating a multipage document from lengthy HTML to PDF format.
It uses the jsPDF’s page handlers like addPage, setPage, insertPage and more.
It calculates the PDF page content height and width and split the HTML source content. It creates chunks of page content from the HTML markup.
It calculates the total pages to paginate split chunks of HTML to PDF multi-page document. The addPage() generates a page instance to render the page content chunk into it.
It loops through the same process to generate PDF from HTML containing long content.
<!doctype html>
<HTML>
<HEAD>
<TITLE>Generate multi-page PDF from HTML - jsPDF</TITLE>
<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://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<style>
.description {
font-size: 2em;
line-height: 4;
}
</style>
</HEAD>
<BODY>
<div class="outer-content">
<div id="pdf-content">
<img src="cherry.jpeg" />
<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>
<hr>
</div>
<button id="btn-generate">Generate PDF</button>
</div>
</BODY>
<script>
$(document).ready(function(){
$("#btn-generate").click(function(){
var htmlWidth = $("#pdf-content").width();
var htmlHeight = $("#pdf-content").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($("#pdf-content")[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("output.pdf");
});
});
});
</script>
</HTML>
It is a command-line tool to generate PDFs from HTML. Find the latest suitable release. Then, install this library before running the command in the terminal.
It requires supplying a sanitized HTML source to create a PDF output.
After installation, add the library path to the system classpath. Then, run the following command.
wkhtmltopdf sanitised_html_source_path output.pdf
The best practice is to read the remote page content and sanitize the HTML. Then write the sanitized content into a local HTML to pass it to the PDF generation command. The PHP cURL post will be best to read the remote content compared to the file_get_contents().
It provides a C library to get used to it via programming.
If you want to execute the command via a program, the PHP exec() function may help.
There is a third-party interface to generate PDF from HTML using the wkHTMLtoPDF. Visit the Github page to install the PHP library used to content HTML to PDF.
This code shows the command to install this library into your vendor directory.
composer require mikehaertl/phpwkhtmltopdf
This simple usage example may initiate to start with this PHP library to generate PDF from HTML.
<?php
use mikehaertl\wkhtmlto\Pdf;
$pdf = new Pdf('html-source-file.html');
if (!$pdf->saveAs('output.pdf')) {
$error = $pdf->getError();
// return error to the request handler
}
The pdfmake library has both client-side and server-side integrations. Both methods generate PDF from HTML by accessing the element content from JavaScript.
This example uses pdfmake CDN URL to import dependencies. The documentation has alternate methods of installing and integrating the library.
For example, it gives npm commands to download node_modules with required dependencies.
This example uses the pdfmake’s client-side method to generate PDF from HTML objects.
It accesses HTML element content from JavaScript and prepares the document definition object.
The document definition can supply the following types of content.
The HTML contains a heading, text, and image content. The docDefinition object is built with the content of these HTML elements.
Images will be supplied as encoded binary data. In this example, the JavaScript getDataUrl()
converts the image into a binary data URL.
Then the pdfmake.createPDF() handler code generate PDF from HTML. The below code opens the HTML to PDF output in the browser screen. The pdfmake library also allows to print, and download the PDF document.
<!DOCTYPE html>
<html>
<head>
<title>PDFMake Example</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.5/pdfmake.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.5/vfs_fonts.min.js"></script>
</head>
<body>
<div class="outer-content">
<h2 id="heading">PDF Page Title</h2>
<div id="pdf-content">How to generate a pdf from the UI content description and example.
</div>
<img src="cherry.jpeg" id="image-preview" />
<hr>
<button id="btn-generate">Generate PDF</button>
</div>
<script>
var buttonElement = document.querySelector("#btn-generate");
buttonElement.addEventListener('click', function() {
var pdfHeading = document.querySelector("#heading").innerText;
var pdfContent = document.querySelector("#pdf-content").innerText;
var pdfImage = getDataUrl(document.querySelector("#image-preview"));
var docDefinition = {
content: [
{
text: pdfHeading,
style: 'heading'
},
{
text: pdfContent,
style: 'vspace'
},
{
image: pdfImage
}
],
styles: {
vspace: {
lineHeight: 3
},
heading: {
fontSize: 18,
lineHeight: 2
}
}
};
pdfMake.createPdf(docDefinition).open();
});
function getDataUrl(imgSource) {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = imgSource.width;
canvas.height = imgSource.height;
context.drawImage(imgSource, 0, 0);
return canvas.toDataURL('image/jpeg');
}
</script>
</body>
</html>
Thus, we have seen various methods to generate PDF from HTML source code or files. I hope the usage examples of the libraries may give choices to enable PDF generation.
Share your thoughts about the PDF generation concept we have seen. Also, share your comments on the example codes to generate PDF from HTML.
As always a great tutorial!
Thank you very much.
There are probably many more, but I think FPDF is also worth diving into.
Best regards,
Cor van Dooren
The Netherlands
Hi Dooren,
Yes, you are right in a way. I have already written about FPDF. I am continuing to use FPDF in my projects and freelance services work. It is a great tool. It is good for server-side PHP-based PDF generation. For PDF generation, I am using FPDF for the server-side and JSPDF for the client-side predominantly. Thank you.
can u make a tutorial for creating a pdf with multiple line of text stored in database using php
Yes Bindumol, I will soon write it. Thanks.