Skip to content

Write images to PDF as soon as possible (otherwise easy to run out of memory) #291

@andrzejbl

Description

@andrzejbl

Hi!

I'm having a strange issue with a large number of images.
Looks like streaming waits for .end() to push all data to the file.
As a result, I'm getting out of memory. output.pdf is empty, for the whole time before .end() is called.
What I'm missing?

const doc = new pdf.Document({
  font: require('pdfjs/font/Helvetica'),
  width: 9 * 72,
  height: 6 * 72,
});
const writeStream = createWriteStream('output.pdf');
doc.pipe(writeStream);

const files = readdirSync('images');
const handleFiles = async () => {
  for (const image in new Array(30).fill(1)) {
      const img = new pdf.Image(
        await sharp(`images/${files[image]}`)
          .resize({ width: 2217, height: 2217, fit: 'inside' })
          .toBuffer()
      );
      doc.image(img);
  }
};
handleFiles().then(() => {
  doc.end();
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions