Convert HTML to PDF using JavaScript

PDF file format is very useful to download bulk data in the web application. It helps the user to download dynamic content in file format for offline use. With export to PDF functionality, the HTML content is converted to a PDF document and downloaded as a PDF file. In the dynamic web application, a server-side script is used to convert HTML to PDF and generate PDF file using PHP.

If you want a client-side solution to generate PDF documents, JavaScript is the easiest way to convert HTML to PDF. There are various JavaScript library is available to generate PDF from HTML. The jsPDF is one of the best library to convert HTML to PDF using JavaScript. In this tutorial, we will show you how to generate PDF document and convert HTML to PDF using JavaScript and jsPDF library.

In this example script, we will share code snippets to handle PDF creation and HTML to PDF conversion related operations using JavaScript.

Include jsPDF Library

The jQuery library is not required, just include the jsPDF library file to use the jsPDF class.

<!-- jsPDF library -->
<script src="js/jsPDF/dist/jspdf.umd.js"></script>

Note that: You don’t need to download the jsPDF library separately, all the required files are included in our source code package.

Load and Initiate jsPDF Class

Use the following line of code to initiate the jsPDF class and use the jsPDF object in JavaScript.

window.jsPDF = window.jspdf.jsPDF;

var doc = new jsPDF();

Generate PDF using JavaScript

The following example shows how to use the jsPDF library to generate PDF file using JavaScript.

  • Specify the content in text() method of jsPDF object.
  • Use the addPage() method to add new page to PDF.
  • Use the save() method to generate and download PDF file.
var doc = new jsPDF();
	
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript to generate a PDF.');

// Add new page
doc.addPage();
doc.text(20, 20, 'Visit CodexWorld.com');

// Save the PDF
doc.save('document.pdf');

Use the addImage() method to add image to PDF using jsPDF object.

  • The source image path/URL must be specified in first parameter in the addImage() method.
doc.addImage("path/to/image.jpg", "JPEG", 15, 40, 180, 180);

Convert HTML Content to PDF using JavaScript

The following example shows how to use the jsPDF library to convert HTML to PDF and generate PDF file from HTML content using JavaScript.

  • Retrieve the HTML content from the specific element by ID or class.
  • Convert HTML content of the specific part of the web page and generate PDF.
  • Save and download the HTML content as a PDF file.

HTML Code:

<div id="content">
    <!-- HTML contnet goes here -->
</div>

JavaScript Code:

window.jsPDF = window.jspdf.jsPDF;

var doc = new jsPDF();
	
// Source HTMLElement or a string containing HTML.
var elementHTML = document.querySelector("#contnet");

doc.html(elementHTML, {
    callback: function(doc) {
        // Save the PDF
        doc.save('sample-document.pdf');
    },
    x: 15,
    y: 15,
    width: 170, //target width in the PDF document
    windowWidth: 650 //window width in CSS pixels
});

Useful Configurations

The jsPDF library provides various methods and options to configure the PDF creation. Some of the useful methods of jsPDF class are given below that are commonly used to export HTML to PDF using jQuery.

Change Paper Orientation:
Use the orientation option to set the paper orientation of the PDF.

var doc = new jsPDF({
    orientation: 'landscape'
});

doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript to generate a PDF.');

// Add new page
doc.addPage();
doc.text(20, 20, 'Visit CodexWorld.com');

// Save the PDF
doc.save('document.pdf');

Change Text Font:
Use setFont() method to set text font faces, text alignment and rotation in the PDF.

var doc = new jsPDF();
	
doc.text(20, 20, 'This is the default font.');

doc.setFont("courier", "normal");
doc.text("This is courier normal.", 20, 30);

doc.setFont("times", "italic");
doc.text("This is times italic.", 20, 40);

doc.setFont("helvetica", "bold");
doc.text("This is helvetica bold.", 20, 50);

doc.setFont("courier", "bolditalic");
doc.text("This is courier bolditalic.", 20, 60);

doc.setFont("times", "normal");
doc.text("This is centred text.", 105, 80, null, null, "center");
doc.text("And a little bit more underneath it.", 105, 90, null, null, "center");
doc.text("This is right aligned text", 200, 100, null, null, "right");
doc.text("And some more", 200, 110, null, null, "right");
doc.text("Back to left", 20, 120);

doc.text("10 degrees rotated", 20, 140, null, 10);
doc.text("-10 degrees rotated", 20, 160, null, -10);

// Save the PDF
doc.save('document.pdf');

Convert HTML Content to PDF with Images and Multiple Pages

In this example code snippet, we will show how to use the jsPDF library to convert HTML to PDF and generate PDF file from HTML content including images using JavaScript.

  • The absolute or relative file paths can be used in the image src.
  • The html2canvas library is required to convert HTML content (with images) to PDF document.
  • The autoPaging option helps to break PDF document in multiple pages automatically.

JavaScript:

window.jsPDF = window.jspdf.jsPDF;

// Convert HTML content to PDF
function Convert_HTML_To_PDF() {
    var doc = new jsPDF();
	
    // Source HTMLElement or a string containing HTML.
    var elementHTML = document.querySelector("#contentToPrint");

    doc.html(elementHTML, {
        callback: function(doc) {
            // Save the PDF
            doc.save('document-html.pdf');
        },
        margin: [10, 10, 10, 10],
        autoPaging: 'text',
        x: 0,
        y: 0,
        width: 190, //target width in the PDF document
        windowWidth: 675 //window width in CSS pixels
    });
}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>

<!-- html2canvas library -->
<script src="js/html2canvas.min.js"></script>

<!-- jsPDF library -->
<script src="js/jsPDF/dist/jspdf.umd.js"></script>

<script>
    /* Place custom JavaScript code here */
</script>
</head>
<body>

<!-- Trigger button -->
<button onclick="Convert_HTML_To_PDF();">Convert HTML to PDF</button>

<!-- HTML content for PDF creation -->
<div id="contentToPrint">
    <h1>What is Lorem Ipsum?</h1>
	
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
	
    <img src="path/to/image.jpg">

    <img src="path/to/image_2.jpeg">
</div>

</body>
</html>

Create PDF with Watermark in PHP using Dompdf

Conclusion

Our example code helps you to convert HTML to PDF and generate PDF file using JavaScript. You can easily add the Export to PDF functionality on the web page without depending on the server-side script. The PDF creation functionality can be enhanced with jsPDF configuration options as per your needs. Download our source code package to get all the required files including the jsPDF JavaScript library.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

11 Comments

  1. Lalli Said...
  2. Rahamani Said...
  3. Shinan Atim Said...
  4. ZeeZee Said...
  5. Saikrishna Said...
  6. Kevin Clark Said...
  7. Chetan Allapur Said...
  8. Surendra Narayan Roy Said...
  9. Ravi Kumar Said...
  10. Abhijit Said...
  11. Shaalan Said...

Leave a reply

keyboard_double_arrow_up