How to generate PDF from HTML using Javascript

How to generate PDF from HTML using Javascript

Generate PDF from HTML

Step:1 : Add Jquery, JsPDF and html2Canvas libraary, using below links:

  <script src=""
    integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script type="text/javascript" src=""></script>
  <script type="text/javascript" src=""></script>

Step:2 : Add HTML Code

<button id="clickbind">Click</button>
 <div id="content" class="html-content">
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Island Trading</td>
    <td>Helen Bennett</td>


Step:3 Add Javascript code to generate and download PDF:


    function CreatePDFfromHTML() {
      var HTML_Width = $(".html-content").width();
      var HTML_Height = $(".html-content").height();
      var top_left_margin = 15;
      var PDF_Width = HTML_Width + (top_left_margin * 2);
      var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
      var canvas_image_width = HTML_Width;
      var canvas_image_height = HTML_Height;

      var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

      html2canvas($(".html-content")[0], {
        allowTaint: true,
        useCORS: true
      }).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) {
          pdf.addPage(PDF_Width, PDF_Height);
          pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4),
            canvas_image_width, canvas_image_height);

    var element = document.getElementById("clickbind");
    element.addEventListener("click", CreatePDFfromHTML);

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment