Muhammad Naeem Akhtar
Muhammad Naeem Akhtar

Reputation: 182

Multiple pages with jspdf using HTML2CANVAS?

I am using jspdf with html2canvas for creating pdf of my invoice. It is creating only one page for the complete invoice. What I want is that I should be able to create multiple A4 Size pages for larger data. Can you please let me know the solution of this problem?

Here is the link for the online code.

https://stackblitz.com/edit/angular-1zwnqh

  html2canvas(document.querySelector(".printformClass")).then(canvas => {

       let totalPages=canvas.height/842;
       var pdf = new jsPDF('p', 'pt',[canvas.width, 842]);
       console.log(pdf);
       for(let i=1;i<=totalPages;i++)
       {
        var imgData  = canvas.toDataURL("image/jpeg", 1.0);
        pdf.addImage(imgData,0,0,canvas.width, 842*i);
        pdf.addPag(canvas.width,842*i);
       }
        pdf.save('converteddoc.pdf');
      })

The pdf should be in multiple A4 Size Pages?

Upvotes: 1

Views: 5931

Answers (2)

GauthamK
GauthamK

Reputation: 188

I had the same requirement and I settled it with the following workaround

var doc = new jsPDF('p', 'px',[x,y]);
var adjust = -1050; //1050 is my assupmtion of how many pixels each page holds vertically
var extraNo=Math.ceil(heightOfElement/1050); //Lets me know how many page are needed to accommodate this image

for(r=0;r<extraNo;r++){

                doc.addImage(canvas, 'JPEG', 0,(adjust)*r, undefined, undefined);
                doc.addPage();

               }

After this block, I would exit the loop and proceed to save the PDF.

(adjust)*r would increment on each iteration allowing the same image to be positioned in such a way that each page continues from where the previous page left.

Please note that I've used px because my requirement is very specific and the target screen resolution does not change. You may use inches or something to approx the A4 print size.

Upvotes: 0

JamesKidd
JamesKidd

Reputation: 11

Here you have a spelling mistake:

pdf.addPag(canvas.width,842*i);

I would use the jsPDF auto table so that half a row isn't between both pages and would look more professional and you can avoid using html2Canvas

Using ViewChild

@ViewChild('table')table: ElementRef;

Inside your function:

pdf.autoTable({ html: this.table.nativeElement });

Upvotes: 1

Related Questions