Print two or more pages using jsPDF

Asked

Viewed 896 times

1

I’m generating my own html in PDF with JsPDF. My html is larger than an A4 sheet. To solve the problem I need to create paging in Jspdf.

Code I have that only generates pdf with a page:

window.html2canvas = html2canvas; 

function demoFromHTML() { 

const html_source = document.getElementById('employee_detail'); // O id do elemento que contém o Html que quer imprimir. 
const filename = 'Test.pdf';

html2canvas(html_source).then(function(canvas) { 
let imgData = canvas.toDataURL('image/png'); 

let pdf = new jsPDF('p', 'mm', 'a4'); // Essas demissões [297, 210] correspondem a um A4 

// addImage(imageData, format, x, y, width, height, alias, compression, rotation) 
// x: Coordenada (em unidades declaradas no início do documento PDF) contra a borda esquerda da página 
// y: Coordenada (em unidades declaradas no início do documento PDF) contra a borda superior da página 
pdf.addImage(imgData, 'PNG', 10, 10);
pdf.save(filename);
}) 

}

To create this pagination I need to use the pagesplit, but I am unable to generate pdf with more than one page.

1 answer

2


This solution breaks a large page into multiple pages automatically.

window.html2canvas = html2canvas;

function demoFromHTML() {

  const html_source = document.getElementById('employee_detail'); // O id do elemento que contém o Html que quer imprimir.
  const filename = 'Test.pdf';


  html2canvas(html_source).then(function(canvas) {
    /*
    [210,297] Sao os números (largura e altura do papel a4) que eu encontrei para trabalhar com eles.
    Se você puder encontrar números oficiais do jsPDF, usa.
     */
    let imgData = canvas.toDataURL('image/png');
    let imgWidth = 210; // Largura em mm de um a4
    let pageHeight = 297; // Altura em mm de um a4

    let imgHeight = canvas.height * imgWidth / canvas.width;
    let heightLeft = imgHeight;
    let position = 0;
    let pdf = new jsPDF('p', 'mm');
    let fix_imgWidth = 15; // Vai subindo e descendo esses valores ate ficar como queres
    let fix_imgHeight = 15; // Vai subindo e descendo esses valores ate ficar como queres

    pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
    heightLeft -= pageHeight;

    while (heightLeft >= 0) {
      position = heightLeft - imgHeight;
      pdf.addPage();
      pdf.addImage(imgData, 'PNG', 0, position, imgWidth + fix_imgWidth, imgHeight + fix_imgHeight);
      heightLeft -= pageHeight;
    }

    pdf.save(filename);
  })

}
  • the code is working and generates the 3 pages in pdf, there is only one problem, does not break correctly, cut the lines in half, example link

  • I needed your help, we can chat link

  • can view the chat

Browser other questions tagged

You are not signed in. Login or sign up in order to post.