Aswartha
Aswartha

Reputation: 66

jsPDF muliple pages with div height - unable to determine the height

I am trying to generate a pdf from html divs with dynamic height and width. Below is the code.

let pages = this.rootDataContainer.nativeElement.getElementsByClassName('pdfpage');

  for (let i = 0; i < pages.length; i++) { 
            this.pdfDoc.addHTML(pages[i], 0, 0, options, () => {
                let pxHeight = pages[i].offsetHeight / scaleFactor; 
                this.pdfDoc.addPage(0, pxHeight);
                this.counter = this.counter - 1;
            });
        }

There are couple of issues I am facing.

  1. As addHTML is async, pages are added to pdf in random way.
  2. height of the pdf page is either getting more or less height.

is there any way to set pdf size and sync the order of pages.

Upvotes: 2

Views: 1252

Answers (1)

zameb
zameb

Reputation: 840

To sync I would use a recursive approach as in:

EDITED:

var pages = document.getElementsByClassName("pdfpage");
var pdfDoc = new jsPDF('p', 'pt', [0, 0]);
pdfDoc.deletePage(1);
pdfDoc.addPage(pages[0].clientWidth, pages[0].clientHeight);

var addDivToPdf = function(pageNr) {
  pdfDoc.addHTML(pages[pageNr], 0, 0, {background:"#FFF"}, () => {
    if (++pageNr < pages.length) {
      //New added DIV dimensions here
      pdfDoc.addPage(pages[pageNr].clientWidth, pages[pageNr].clientHeight);
      addDivToPdf(pageNr);
    } else {
      pdfDoc.save("sample-file.pdf");
    }
  });
};

Notice I haven't use a for loop. This way the next page is added only when the previous is complete.

For the height, I'm not sure, scaleFactor must have the wrong units. It is not really clear if you want all pages to have the same size or you want different sizes to match the DIV height.

UPDATE: To control the widht and height according with the DIVs sizes, I have indicated 'pt' in the pdfDoc constructor:

var pdfDoc = new jsPDF('p', 'pt', [0, 0]);

However the first page appears to have always an standard size, so I have deleted it and added again with the desired size before adding the first DIV. The other pages can follow the normal flow:

pdfDoc.deletePage(1);
pdfDoc.addPage(pages[0].clientWidth, pages[0].clientHeight);

The CodePen is updated: https://codepen.io/zameb/pen/BdbEVr

Upvotes: 2

Related Questions