3

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>
anees ma kader
  • 87
  • 1
  • 1
  • 10

2 Answers2

5

try to use particular size of a4

var pdf = new jsPDF('p','mm',[297, 210]);

also see this page How to set image to fit width of the page using jsPDF?

Moufeed Juboqji
  • 690
  • 4
  • 11
  • 1
    Hi @moufed, this i already tried. As in the question, it seems to be working for the first page of the document since the size of the first page of the pdf seems to be A4(even if the html contents cuts away from the right side). But other pages are not and the pdf page size is wider than the first page. – anees ma kader Jul 13 '20 at 16:58
-1

In

pdf.addImage(pdfEle.pageData, 'JPEG', 0, posYInCurrentPage, pdfW, imgHeight)

"posYInCurrentPage" you should set it as fol:-

  1. the first element in current page, posYInCurrentPage = 0
  2. the second element in current page, posYInCurrentPage = first element Height
NSNoob
  • 5,548
  • 6
  • 41
  • 54
crab
  • 1