Merging pdfs in a loop results in a blank page
Closed this issue · 3 comments
jerry-flam commented
I am using the following code to merge the pdfs of a folder, inspired from this comment: #24 (comment)
const path = require('path');
const glob = require('glob');
const PDFMerger = require('pdf-merger-js');
const merger = new PDFMerger();
const pdfsFolder = path.join(__dirname, 'files');
glob(pdfsFolder + '/*.pdf', {}, (_err, files) => {
files.forEach((file) => {
merger.add(file);
});
merger.save('merged.pdf');
});
The result is an empty pdf file.
On the other hand, the following works fine:
const PDFMerger = require('pdf-merger-js');
const merger = new PDFMerger();
const pdfsFolder = path.join(__dirname, 'files');
(async () => {
await merger.add(pdfsFolder + '/file1.pdf');
await merger.add(pdfsFolder + '/file2.pdf');
await merger.save('merged.pdf');
})();
Am I missing something or it is a bug?
Software versions:
node: v16.17.0
glob: v8.0.3
pdf-merger-js: v4.1.0
jerry-flam commented
Here is a repo reproducing the issue: https://github.com/jerry-flam/pdf-merger-js-issue-98
mojoaxel commented
I had a quick look. It looks to me like you forgot to await the (newly introduced) add
promise.
Try this:
glob(pdfsFolder + '/*.pdf', {}, async (_err, files) => {
for (let file of files) {
await merger.add(file);
});
await merger.save('merged.pdf');
});
jerry-flam commented
Thank you very much! This solved it!