Home > Net >  Load PDF document with PDF-LIB on Node gives "No PDF header found"
Load PDF document with PDF-LIB on Node gives "No PDF header found"

Time:12-15

Im loading a PDF document I have to modify on the fly with PDF-lib.

const { PDFDocument } = require('pdf-lib');

The PDF file is built with Acrobat and its called dental_insurance.pdf.

I tried to load the file the following ways:

const pdfDoc = await PDFDocument.load("/documents/cards/dental_insurance.pdf")

const pdfDoc = await PDFDocument.load("C:/Website/test/desk_routes/documents/cards/dental_insurance.pdf")

const pdfDoc = await PDFDocument.load("./documents/cards/dental_insurance.pdf")

const pdfDoc = await PDFDocument.load("../documents/cards/dental_insurance.pdf")

But no matter how I set the route where the file is located, I get this error:

(node:15196) UnhandledPromiseRejectionWarning: Error: Failed to parse PDF document (line:4 col:2 offset=27): No PDF header found

I checked at PDF-lib documentation, they only state the following to load a file:

const pdfDoc = await PDFDocument.load("...")

I dont believe the problem is on the PDF file since I get the very same error even if I enter a file that doesn't exist:

const pdfDoc = await PDFDocument.load("blablabla.pdf")

Thanks.

CodePudding user response:

Per the documentation, PDFDocument.load() accepts a string which is the contents of the pdf file, not the name.

const fs = require('fs/promises');

const pdfData = await fs.readFile('./documents/cards/dental_insurance.pdf');

const pdfDoc = await PDFDocument.load(pdfData);
  • Related