In previous article, we have explained about how to convert html to word using javascript or how to read pdf using Javascript or to read excel using Javascript, but in this article we will read about how to convert html into pdf using JS easily with jsPDF library or without using any javascript library.

Convert HTML to PDF using jsPDF

Let's consider example, for html to pdf using jsPDF library first, so in this example, we will use jsPDF, you can download it from https://github.com/MrRio/jsPDF or you can also use cdn link 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js'

Once we have have downloaded jsPDF, just create it's object "var doc = new jsPDF()" and then directly export HTML to PDF as shown below

function generatePDF() {
 var doc = new jsPDF();  //create jsPDF object
  doc.fromHTML(document.getElementById("test"), // page element which you want to print as PDF
  15,
  15, 
  {
    'width': 170  //set width
  },
  function(a) 
   {
    doc.save("HTML2PDF.pdf"); // save file name as HTML2PDF.pdf
  });
}

Let's consider checking complete example, here is the HTML

<!DOCTYPE html>
<html>
<head>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js" ></script>
</head>
  <body>
    <div id="test">
       <p><font size="3" color="red">This is p one</font></p>
       <p><font size="10" color="green">More Text to be printed on PDF</font></p>
  
    </div>
    
<a href="javascript:generatePDF()">Dowload PDF</a>
  </body>
</html>

If you want to include image in HTML to PDF conversion using Javascript in jsPDF, you can include base64 code of the image, so here is the complete fiddle example, which includes image also in conversion.

Output:

convert-html-to-pdf-using-javascript-min.png

More configuration using jsPDF

If you want to remove a part of PDF from complete page you can mention it in specialElementHandler function, here is the more explanation of configuration using jsPDF in comments with example

         var pdf = new jsPDF('p', 'pt', 'letter'); //letter = letter size pdf

        // source can be HTML-formatted string, or a reference
        // to an actual DOM element from which the text will be scraped.
        source = $('#content')[0];

        // we support special element handlers. Register them with jQuery-style 
        // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
        // There is no support for any other type of selectors 
        // (class, of compound) at this time.
        specialElementHandlers = {
            // element with id of "bypass" - jQuery style selector
            '#bypassme': function (element, renderer) {
                // true = "handled elsewhere, bypass text extraction"
                return true
            }
        };
        margins = {
            top: 80,
            bottom: 60,
            left: 40,
            width: 522
        };
        // all coords and widths are in jsPDF instance's declared units
        // 'inches' in this case
        pdf.fromHTML(
            source, // HTML string or DOM elem ref.
            margins.left, // x coord
            margins.top,   // y coord
            {
                'width': margins.width, // max width of content on PDF
                'elementHandlers': specialElementHandlers
            },

            function (dispose) {
                // dispose: object with X, Y of the last line add to the PDF 
                //          this allow the insertion of new lines after html
                pdf.save('Filename.pdf');
            }, margins
        );

Converting images to base64 using html2canvas

If you don't have base64 image code, then you can convert html to pdf with images using HTML2Canvas with jsPDF.

HTML2Canvas will convert your images into base64 code and then it will help you print pdf more easily.

Here is the fiddle demo for it

Other plugins which can be useful for html to pdf conversion are

  1. PDFMake
  2. PDFKit

HTML to PDF without using any Javascript library

In the above example, we were using jsPDF library, but now we will convert it using simple Javascript code, although this code doesn't directly converts HTML to PDF, but it will open dialog to print or save HTML as PDF, here is the sample code

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
   
</head>
<body>
    <form id="form1">
    <div id="dvContainer">
       Your HTML content which needs to be printed
    </div>
    <input type="button" value="Print Contents" id="PrintNow" />
    </form>
    <script>
    $("#PrintNow").on("click", function () {
            var divContents = $("#dvContainer").html();
            var printWindow = window.open('', '', 'height=400,width=800');
            printWindow.document.write('<html><head><title>DIV Contents</title>');
            printWindow.document.write('</head><body >');
            printWindow.document.write(divContents);
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.print();
        });
        </script>
</body>
</html>

You can take a look at fiddle sample here

Fiddle example may ask you to allow pop-up.