This is based on the example detailed here: https://www.freakyjolly.com/multipage-canvas-pdf-using-jspdf/

Its OK for some uses, but its an image-based output, so if your HTML is full of text, that text gets converted to an image grab before being added to the pdf and will get sliced for page joins anywhere, including in the middle of a line of text.

Include in your header
    <script type="text/javascript" src="/wp-content/themes/hello-theme-child-master/odac-libaries/canvasjs/canvasjs.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>   <!--Include for export to pdf-->
    <script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
Export button
  <button id="exportButton" type="button">Export as PDF</button>
Div containing all that you want to export
  <div class="canvas_div_pdf">

    <h4>Your content here...</h4>

  </div> <!-- <div class="canvas_div_pdf"> -->
Javascript code to do the export when the button is clicked
    <script type="text/javascript">
      jQuery("#exportButton").click(function()
      {

        var HTML_Width = jQuery(".canvas_div_pdf").width();
        var HTML_Height = jQuery(".canvas_div_pdf").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(jQuery(".canvas_div_pdf")[0],{allowTaint:true}).then(function(canvas) {
          canvas.getContext('2d');

          console.log(canvas.height+"  "+canvas.width);


          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);
          }

            pdf.save("HTML-Document.pdf");
            });

      });
    </script>
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

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