Convert HTML to PDF in JavaScript

Kushank Singh Oct 12, 2023
  1. Use the jsPDF Library to Convert HTML to PDF
  2. Use a Window Object to Convert HTML to PDF
Convert HTML to PDF in JavaScript

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>
  • JavaScript
var source = window.document.getElementsByTagName('body')[0];
var specialElementHandlers = {
  '#hidden-element': function(element, renderer) {
    return true;
var doc = new jsPDF({orientation: 'landscape'});
    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.

Related Article - JavaScript PDF