From 8d3076482d13e1d31a54a5d7147cb1a3390b59bc Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Fri, 3 Jun 2022 18:45:34 +0100 Subject: [PATCH] fix(index): set correct "file size" if `pdfInfo()` passed a buffer (#427) --- src/index.js | 14 ++++++++++++++ src/index.test.js | 41 +++++++++++++++++++++++++++-------------- 2 files changed, 41 insertions(+), 14 deletions(-) diff --git a/src/index.js b/src/index.js index c1552dd0..3a6f98b7 100644 --- a/src/index.js +++ b/src/index.js @@ -439,9 +439,16 @@ class Poppler { versionInfo ); + /** + * Poppler does not set the "File size" metadata value if passed + * a Buffer via stdin, so need to retrieve it from the Buffer + */ + let fileSize; + return new Promise((resolve, reject) => { if (Buffer.isBuffer(file)) { args.push("-"); + fileSize = file.length; } else { args.push(file); } @@ -469,6 +476,13 @@ class Poppler { child.on("close", async () => { if (stdOut !== "") { + if (fileSize) { + stdOut = stdOut.replace( + /(File\s+size:\s+)0(\s+)bytes/, + `$1${fileSize}$2bytes` + ); + } + if (options.printAsJson === true) { /** * Thanks to @sainf for this solution diff --git a/src/index.test.js b/src/index.test.js index 11aa29fd..a9d67bce 100644 --- a/src/index.test.js +++ b/src/index.test.js @@ -364,6 +364,21 @@ describe("Node-Poppler Module", () => { }); describe("pdfInfo Function", () => { + const pdfInfoObject = { + tagged: "yes", + userProperties: "no", + suspects: "no", + form: "AcroForm", + javaScript: "no", + pages: "16", + encrypted: "no", + pageSize: "595.276 x 841.89 pts (A4)", + pageRot: "0", + fileSize: "583094 bytes", + optimized: "no", + pdfVersion: "1.3", + }; + test("Should list info of PDF file", async () => { const poppler = new Poppler(testBinaryPath); @@ -379,20 +394,7 @@ describe("Node-Poppler Module", () => { printAsJson: true, }); - expect(res).toMatchObject({ - tagged: "yes", - userProperties: "no", - suspects: "no", - form: "AcroForm", - javaScript: "no", - pages: "16", - encrypted: "no", - pageSize: "595.276 x 841.89 pts (A4)", - pageRot: "0", - fileSize: "583094 bytes", - optimized: "no", - pdfVersion: "1.3", - }); + expect(res).toMatchObject(pdfInfoObject); }); test("Should list info of PDF file as Buffer", async () => { @@ -404,6 +406,17 @@ describe("Node-Poppler Module", () => { expect(res).toEqual(expect.stringContaining("Pages:")); }); + test("Should list info of PDF file as Buffer as a JSON object", async () => { + const poppler = new Poppler(testBinaryPath); + const attachmentFile = await fs.promises.readFile(file); + + const res = await poppler.pdfInfo(attachmentFile, { + printAsJson: true, + }); + + expect(res).toMatchObject(pdfInfoObject); + }); + test("Should return an Error object if file passed not PDF format", async () => { const poppler = new Poppler(testBinaryPath); const testTxtFile = `${testDirectory}test.txt`;