Reputation: 49
const doc = new PDFDocument();
// do stuff here
const writeStream = fs.createWriteStream('output.pdf')
doc.pipe(writeStream);
doc.end();
above code generating pdf file but cannot open pdf, it is showing an error that file has damaged.
Upvotes: 1
Views: 3114
Reputation: 23
Building on top of AlienWebguy's answer, if you are in an async function, you can do the following:
import { once } from 'events'
async function main () {
const doc = new PDFDocument();
// do stuff here
const writeStream = fs.createWriteStream('output.pdf')
doc.pipe(writeStream);
doc.end();
await once(writeStream, 'finish');
}
When main()
finishes executing, you are garanteed that the stream is done writing to disk and can safely manipulate the file again, or exit the process.
Upvotes: 0
Reputation: 78046
You probably have an async issue where you're trying to access/return the doc before it's done writing to disk.
Fix with a handler :
writeStream.on('finish', () => { .. your code here .. });
Upvotes: 5