I am using a Node.js module named pdf-lib to try to modify a PDF uploaded to the webpage. When I upload the PDF to the script, I get an error stating:
pdf-lib@1.4.0:1 Uncaught (in promise) Error: Failed to parse PDF document (line:0 col:0 offset=0): No PDF header found
Some forum posts by other uses with the same issue seemed to narrow it down to loading the PDF as a binary string but I can't seem to get it to work because I am doing everything they have said solved their issue.
If I had a guess, the error is caused by one of 2 lines:
fr.readAsBinaryString(file)
or var bytes = new Uint8Array(input)
Any help would be greatly appreciated. If you have any questions let me know.
Code:
const { degrees, PDFDocument, rgb, StandardFonts } = PDFLib
document.querySelector("input[type=file]").addEventListener("change", function() {
file = this.files[0];
fr = new FileReader();
fr.readAsBinaryString(file)
fr.onload = function() {
modifyPdf(fr.result)
};
});
async function modifyPdf(input) {
var bytes = new Uint8Array(input);
const pdfDoc = await PDFDocument.load(bytes)
//below should be irrelevant because it doesn't get past the above line
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica)
const pages = pdfDoc.getPages()
const firstPage = pages[0]
const { width, height } = firstPage.getSize()
firstPage.drawText('This text was added with JavaScript!', {
x: 5,
y: height / 2 + 300,
size: 50,
font: helveticaFont,
color: rgb(0.95, 0.1, 0.1),
rotate: degrees(-45),
})
const pdfBytes = await pdfDoc.save()
download(pdfBytes, "pdf-lib_modification_example.pdf", "application/pdf");
}