JsPDF Html2Canvas Tutorial to Build Multiple Pages in PDF Document and Insert Graphics Using Fabric.JS in Javascript

You are currently viewing JsPDF Html2Canvas Tutorial to Build Multiple Pages in PDF Document and Insert Graphics Using Fabric.JS in Javascript

jsPDF Html2canvas Tutorial to Build Multiple Pages in PDF Document and Insert Graphics Using Fabric.js in Javascript

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
 
    <title>JSPDF html2canvas with multiple pages</title>
  </head>
  <body>
    <h1>JSPDF html2canvas with multiple pages</h1>
<div class="col-lg-10" id="generatePDF">
<canvas id="canvas_1" width="600" height="600"></canvas>
<canvas id="canvas_2" width="600" height="600"></canvas>
</div>
    <button name="PRINT" onclick="downloadpdf()">PRINT PDF </button>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>      
<!-- jspdf lib -->
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.0.0/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.2.6/purify.min.js" integrity="sha512-rXAHWSMciPq2KsOxTvUeYNBb45apbcEXUVSIexVPOBnKfD/xo99uUe5M2OOsC49hGdUrkRLYsATkQQHMzUo/ew==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js" integrity="sha512-jzL0FvPiDtXef2o2XZJWgaEpVAihqquZT/tT89qCVaxVuHwJ/1DFcJ+8TBMXplSJXE8gLbVAUv+Lj20qHpGx+A==" crossorigin="anonymous"></script>

<script>      
$(function(){
// Do some initializing stuff
fabric.Object.prototype.set({
transparentCorners: false,
cornerColor: 'rgba(102,153,255,0.5)',
cornerSize: 12,
padding: 5
});
 
// initialize fabric canvas and assign to global windows object for debug
var canvas1 = window._canvas = new fabric.Canvas('canvas_1');
var canvas2 = window._canvas = new fabric.Canvas('canvas_2');
 
var json = '{"objects":[{"type":"rect","originX":"center","originY":"center","left":300,"top":150,"width":150,"height":150,"fill":"#29477F","overlayFill":null,"stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":{"color":"rgba(94, 128, 191, 0.5)","blur":5,"offsetX":10,"offsetY":10},"visible":true,"clipTo":null,"rx":0,"ry":0,"x":0,"y":0},{"type":"circle","originX":"center","originY":"center","left":300,"top":400,"width":200,"height":200,"fill":"rgb(166,111,213)","overlayFill":null,"stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":{"color":"#5b238A","blur":20,"offsetX":-20,"offsetY":-10},"visible":true,"clipTo":null,"radius":100}],"background":""}'
 
canvas1.loadFromJSON(json, canvas1.renderAll.bind(canvas1), function(o, object) {
fabric.log(o, object);
});
canvas2.loadFromJSON(json, canvas2.renderAll.bind(canvas2), function(o, object) {
fabric.log(o, object);
});
});
</script>
<script>
var jsPDF = window.jspdf.jsPDF;
var html2canvas = window.html2canvas;
 
function downloadpdf(){
    console.log('Inside downloadpdf ');
    var quotes = document.getElementById('generatePDF');
    html2canvas(quotes, {
        onrendered: function(canvas) {
            canvas.getContext('2d');
            var HTML_Width = canvas.width;
            var HTML_Height = canvas.height;
            var top_left_margin = 15;
            var PDF_Width = HTML_Width+parseInt(top_left_margin*2);
            var PDF_Height = parseInt(PDF_Width*1.5)+parseInt(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;
            var pages = $('#generatePDF .canvas-container').length;
 
            console.log('height => '+canvas.height+" width => "+canvas.width+'totalpage => '+pages);
            
            
            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 <= pages; i++) {
                //pdf.addPage(PDF_Width, PDF_Height);
                pdf.addPage();
                let margin=-parseInt(PDF_Height*i)+parseInt(top_left_margin*4);
                if(i>1){
                    margin= parseInt(margin+i*8);
                }
                pdf.addImage(imgData, 'JPG', top_left_margin, margin,canvas_image_width,canvas_image_height);
            }
            pdf.save("HTML-Document.pdf");
        }
    });
}
</script>
</body>
</html>

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply