Reputation: 41
Im using pdfkit to generate pdf invoice. When all my content fit in one page I have no issue.
However when it doesn't fit and need an extra page, I have a strange behaviour: Instead of adding the elements in the second page, it only add one line and the rest of the page is blank. Then on 3rd page I have another element, and the rest it blank, then 4th page, 5th etc.
Here is the code corresponding to this part:
for (let i = 0; i < data.items.length; i++) {
const item = data.items[i];
this.itemPositionY = this.itemPositionY + 20;
if (item.bio) this.containBioProduct = true;
let itemName = item.bio ? `${item.item}*` : item.item;
this.generateTableRow(
doc,
this.itemPositionY,
itemName,
"",
this.formatCurrency(item.itemPriceDf.toFixed(2)),
item.quantity,
this.formatCurrency(item.itemPriceTotalDf.toFixed(2))
);
this.generateHr(doc, this.itemPositionY + 15);
}
Basically I just iterate over an array of products. For each line my Y position has +20.
Thanks for your help.
Upvotes: 0
Views: 1744
Reputation: 329
you need reset the position per page with other variable:
let j = 0;
for (i = 0; i < invoice.items.length; i++) {
const item = invoice.items[i];
let position = position + 20 * j;
j++;
....
....
if (position > 740) {
doc.addPage();
j = 0;
}
}
Upvotes: 0
Reputation: 41
In case someone has this issue, here is a solution:
Everywhere in the code I know that an extra page could be generated, I add this:
if (this.position > 680) {
doc.addPage();
this.position = 50;
}
It allows you to control the generation of new pages (instead of pdfkit doing it automatically with potential problems)
You just need to track the position from the initialization of "this.position". In that way, evertime it's superior than an Y position (680 in my case, it's a bit less than a page with pdfkit), you just do "doc.addPage()", which will create another page, and you reinitialize your position to the beginning of the new page.
Upvotes: 2