jsPDF - How to generate PDF with all pages in A4 size

Viewed 11112

I am using jsPDF library for downloading a multiple page PDF which creates from an HTML div. I want the PDF in A4 size.

I am facing below issues,

  1. Only first page seems to be in A4 size, other pages not in A4 size(wider pages).
  2. Even the first page seems to be in A4 size; it does not fit in the container(contents from right side cuts away from the container).
  3. And the contents which is expected be appear in second page are not in the PDF generated.

Below is the JS code.

var HTML_Width = $("#cdpage").width();
var HTML_Height = $("#cdpage").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($("#cdpage")[0],{allowTaint:true}).then(function(canvas) {
  canvas.getContext('2d');
       
  var imgData = canvas.toDataURL("image/jpeg", 1.0);
  var pdf = new jsPDF("p", "pt", "a4");
  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");
}

And i know that the code snippet var pdf = new jsPDF("p", "pt", "a4"); is for setting A4 size, but its not working.

Below is the HTML DIV from which the pdf is generated.

<div id="cdpage">
   <div id="cdpage1"></div>
   <div id="cdpage4"></div>
   <div id="cdpage5"></div>
</div>
1 Answers
Related