Convert HTML to PDF in JavaScript

  1. Use the jsPDF library to convert HTML to PDF
  2. Use a window object to convert HTML to PDF

When downloading massive data from a web application, the PDF file format comes in handy. It enables users to download dynamic material as a file for offline consumption. HTML material is transformed to a PDF document and downloaded as a PDF file using the export to PDF capability. A server-side script converts HTML to PDF in the dynamic web application.

In this tutorial, we will perform such conversion using JavaScript.

Use the jsPDF library to convert HTML to PDF

In this method, we will use jsPDF library to convert HTML to PDF. It is one of the best libraries to use. The jsPDF library offers several techniques and options for customizing PDF generation.

Check the code below.

  • HTML
<!DOCTYPE html>
      <p>Convert this text to PDF.</p>
    <div id="hidden-element">This will not be printed</div>
var source = window.document.getElementsByTagName("body")[0];
var specialElementHandlers = {
    '#hidden-element': function (element, renderer) {
        return true;
var doc = new jsPDF({
    orientation: 'landscape'
doc.fromHTML(elementHTML, 15, 15, {
    'width': 170,
    'elementHandlers': specialElementHandlers

The orientation property sets the orientation of the paper. The setFont() and setFontType() option are used to set the font and font-style of the Text. The setFontSize() and setTextColor() functions are used to set font size and color of the text.

Use a window object to convert HTML to PDF

In this method, we will create a window object, which we will use to create an associated document and write the HTML text in the file to export it as a PDF.

See the code below

  <script type="text/javascript" src=""></script>
  <script type="text/javascript">
    $("#btnPrint").live("click", function () {
      var divContents = $("#text").html();
      var printWindow ='', '', 'height=400,width=800');
      printWindow.document.write('<html><head><title>Html to PDF</title>');
      printWindow.document.write('</head><body >');
    <form id="form1">
    <div id="text">
      Convert this text to PDF.
      <input type="button" value="Print Div Contents" id="btnPrint" />

In the above example, the function will open a document with the specified dimensions, and document.write() method is used to write text in the opened document.

DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.