generate pdf to html in javascript

How to Generate PDF from HTML Using JavaScript

These days most websites and applications allow users to export entire web pages or certain parts of a web page as PDF. So web developers often need to generate PDF from HTML. Typically, this is done by sending HTML code that you want to convert, to server side and do the HTML to PDF conversion there. But due to recent developments in web browsers, this can also be done on client side using JavaScript. In this article, we will learn how to generate PDF from HTML using JavaScript.

How to Generate PDF from HTML Using JavaScript

You can do this using plain JavaScript as well as using third party plugins. We will look at both the approaches. There are several JavaScript plugins that allow you to save HTML as PDF. For our purpose, we will use jspdf.

1. Using JSPDF

If you are using server side JS frameworks like NodeJS, then the first step is to download JSPDF plugin to your server from its download link.

Next, include the following plugins to your project.

  • jspdf.js
  • jspdf.plugin.from_html.js
  • jspdf.plugin.split_text_to_size.js
  • jspdf.plugin.standard_fonts_metrics.js

The above approach is required if you are using it in server side JS frameworks like NodeJS. If you are using it directly on web browser, you can simply import the file using script tag.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

Let us say you have the following HTML code that you want to convert to PDF.

<!DOCTYPE html>
<html>
  <body>
    <p id="ignorePDF">don't convert this to pdf</p>
    <div>
      <p><font size="3" color="red">print this to pdf</font></p>
    </div>
  </body>
</html>

Then you can add the following JavaScript code to your page to implement the PDF generation.

var doc = new jsPDF();          
var elementHandler = {
  '#ignorePDF': function (element, renderer) {
    return true;
  }
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(source, 15, 15,
    {
      'width': 180,'elementHandlers': elementHandler
    });

doc.output("dataurlnewwindow");

In the above code, we first create a new document using jsPDF() constructor. We also specify element with id=ignorePDF should be ignored. Next, we call fromHTML() function to specify the HTML DOM element that we want to convert to PDF. In our case, we are converting the entire body tag. In it, we also specify the element handler for DOM elements that we want to ignore. Lastly, we call doc.output() function to open generated PDF in new window.

2. Using JavaScript

You can also do this using plain JavaScript. Let us say you have the following HTML that you want to print to PDF.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <form id="form1">
    <div id="dvContainer">
        This content needs to be printed.
    </div>
    <input type="button" value="Print Div Contents" id="btnPrint" />
    </form>
</body>
</html>

Next, we add JavaScript as shown below.

<script type="text/javascript">
document.getElementById("btnPrint").addEventListener("click", function(){
let mywindow = window.open('', 'PRINT', 'height=650,width=900,top=100,left=150');

  mywindow.document.write(`<html><head><title></title>`);
  mywindow.document.write('</head><body >');
  mywindow.document.write(document.getElementById("#dvContainer").innerHTML);
  mywindow.document.write('</body></html>');

  mywindow.document.close(); // necessary for IE >= 10
  mywindow.focus(); // necessary for IE >= 10*/

  mywindow.print();
  mywindow.close();

  return true;
});
</script>

In this case, we open print window, write different DOM elements into it such as head, title, and also the page’s HTML content obtained using document.write() function. Once we have written all the content, we call print() function followed by close() function. Please note, this will not copy the CSS styling or images. If you want to do that, you need to write a style or img tag with full URL, instead of relative URLs.

This whole approach is similar to clicking and configuring ‘Save As…Print’ dialog box opened by web browser. It will open the Save As dialog box and user will need to click Save button.

In this article, we have learnt a couple of simple ways to generate PDF from HTML. You can use it to add ‘Export as PDF’ functionality to your websites and applications.

Also read:

How to Auto Resize IFrame Based on Content
How to Count Substring Occurrence in JS String
How to Convert Comma Separated String to JS Array
How to Suppress Warning Messages in MySQL
How to Show JS Date in AM/PM Format

Leave a Reply

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