rkusa / pdfjs

A Portable Document Format (PDF) generation library targeting both the server- and client-side.
MIT License
774 stars 142 forks source link

Already ended #288

Closed StuartMarshHISC closed 2 years ago

StuartMarshHISC commented 2 years ago

I'm getting the error "Error: already ended" when trying to add additional text to a referenced fragment. You can see the error in this test code:

doc.pipe(fs.createWriteStream(`template.pdf`));
doc.text("Text at the start!");
const outer = doc.cell({ backgroundColor: 0xeeeeee });
outer.text('Hello World');
doc.text('Hello World');
outer.text('Some more text'); // <<< This is where the error is produced
doc.text("Text at the end!");
await doc.end();

I'm trying to build a PDF doc dynamically so I need to have references to cells at certain parts of the document that I can update at various points of the code. Is there anything I can do to stop this behaviour?

rkusa commented 2 years ago

I am afraid that this is not possible. The cell outer is closed/finished as soon as you add something else to the document after it. This is due to how pdfjs works. It writes everything to the PDF as soon as possible instead of building up the whole document first.

The following is the only order that will work:

doc.pipe(fs.createWriteStream(`template.pdf`));
doc.text("Text at the start!");
const outer = doc.cell({ backgroundColor: 0xeeeeee });
outer.text('Hello World');
- doc.text('Hello World');
outer.text('Some more text'); // <<< This is where the error is produced
+ doc.text('Hello World');
doc.text("Text at the end!");
await doc.end();