Home > Mobile >  jsPDF setPage is not working with set html
jsPDF setPage is not working with set html

Time:07-07

I have created div elements which contains html of each PDF page. I try to generate PDF using jsPDF. The issue is that it puts all html pages on PDF file's first page.

I have tried this code

const list = [];
const pages = document.getElementsByName( this.pageName );
const pdf = new jsPDF("landscape", "px", [this.pageWidth, this.pageHeight]);

pages.forEach((el, i) => {
  if (i > 0) {
      pdf.addPage();
  }
  pdf.setPage(i   1);

  list.push(pdf.html(el));
});

Promise.all(list).then((res) => {
  pdf.save("test.pdf");
}).catch(error => {
  console.log('error ', error);
});

I have tried this code

const list = [];
const pages = document.getElementsByName( this.pageName );
const pdf = new jsPDF("landscape", "px", [this.pageWidth, this.pageHeight]);

pages.forEach((el, i) => {
  if (i > 0) {
     pdf.addPage();
  }

  list.push(pdf.html(el, {x: 0, y: (i * this.pageHeight)}));
});

Promise.all(list).then((res) => {
  pdf.save("test.pdf");
}).catch(error => {
  console.log('error ', error);
});

addPage works fine, it generates blank pages, but it still puts all html pages on PDF file's first page. So somehow pdf.setPage(i 1); and {x: 0, y: (i * this.pageHeight)} solutions are not working.

CodePudding user response:

Finally I was able to force jsPDF to put HTML contents on corresponding pages. Here is the solution.

...
const list = [];
const pages = document.getElementsByName( this.pageName );
const pdf = new jsPDF("landscape", "px", [this.pageWidth, this.pageHeight]);

this.setOnePage(pdf, 0, pages, list);
...


private setOnePage(pdf: jsPDF, i: number, pages: NodeListOf<HTMLElement>, list: Array<Promise<any>>): void {
  if (i < pages.length) {
    if (i > 0) {
      pdf.addPage();
    }

    list.push(pdf.html(pages.item(i), {x: 0, y: (i * this.pageHeight)}).then((e) => {
     this.setOnePage(pdf,   i, pages, list);
    }));
  } else {
    Promise.all(list).then((res) => {
      pdf.save("test.pdf");
    }).catch(error => {
      console.log('error ', error);
    });
  }
}

Solution looks a bit complicated, so if someone knows better solution, you are welcome.

  • Related