I am fully aware that my problem most likely has something to do with me doing something wrong, but I can't seem to figure it out. Here is my code:
for (let i = 0; i < formContentArray.length; i++) {
rowPosition = doc.y
columnPosition = doc.x
if (formContentArray[i].type == 'text' ) {
doc
.fill('#89cff0')
.fontSize(13)
.text(formContentArray[i].text, columnPosition, rowPosition, { align: "left" });
if (i == 0) {
doc.text('Done/Not Done', columnPosition, rowPosition, {align: 'right'})
}
}
else {
doc
.fill('#212121')
.fontSize(11)
.text(formContentArray[i].text,columnPosition, rowPosition, { align: "left" })
if (formContentArray[i].value) {
doc.text('Done', columnPosition, rowPosition, {align: 'right'})
}
else {
doc.text('Not Done', columnPosition, rowPosition, {align: 'right'} )
}
}
}
This works perfectly until the data fills out the page at which point PDFkit makes a new page. The next time it loops, it only does one loop, adds one line of text at the top of the 2nd page, and then adds a 3rd page. The loop then works perfectly on the 3rd page, finishing off the data. This obviously leaves the 2nd page though that is almost completely empty. I don't understand? It has something to do with my rowPosition and columnPosition, I think. However, I need those in order to align text on the right-hand side with that on the left
When you reach the bottom of the page, it triggers a new page automatically, but you've stored doc.y
in rowPosition
, but the value isn't updated when skipping to a new page, so it attempts to print a second time at rowPosition
triggering another page to be added before it iterates again resetting rowPosition
. There are several different ways to approach this, but the easiest might be to adjust the doc.x after you print your first text. If it's smaller than rowPosition, reset it to the page margin.
for (let i = 0; i < formContentArray.length; i++) {
rowPosition = doc.y
columnPosition = doc.x
if (formContentArray[i].type == 'text' ) {
doc
.fill('#89cff0')
.fontSize(13)
.text(formContentArray[i].text, columnPosition, rowPosition, { align: "left" });
if (i == 0) {
doc.text('Done/Not Done', columnPosition, rowPosition, {align: 'right'})
}
}
else {
doc
.fill('#212121')
.fontSize(11)
.text(formContentArray[i].text,columnPosition, rowPosition, { align: "left" })
if (doc.x < rowPosition) {
rowPosition = doc.page.margins.top;
}
if (formContentArray[i].value) {
doc.text('Done', columnPosition, rowPosition, {align: 'right'})
}
else {
doc.text('Not Done', columnPosition, rowPosition, {align: 'right'} )
}
}
}
You could also check for a change in page number or on each iteration, check the rowPosition against the pageSize (minus bottom margin) to see if there's enough space for the row and manually trigger a new page.