vbuch / node-signpdf

Simple signing of PDFs in node.
MIT License
676 stars 174 forks source link

Error when using node JS pdf-lib: Expected xref at NaN but found other content #249

Open CristiCh opened 2 months ago

CristiCh commented 2 months ago

I am using pdf-lib in a node JS project and I get the same error when trying to modify the pdf. Does anyone know why this is happening? Thanks!

exports.transformPdf = onObjectFinalized({}, async (event) => {
    const bucket = admin.storage().bucket()
    const fileBucket = event.data.bucket; // Storage bucket containing the file.
    const filePath = event.data.name; // File path in the bucket.
    const contentType = event.data.contentType; // File content type.
    console.log(filePath);
    const file = await bucket.file(filePath);
    const fileDir = path.dirname(filePath);
    const fileBasename = path.basename(filePath);
    console.log(fileDir);
    if (fileDir != 'uploads') { return; }

    getRawBody(file.createReadStream())
    .then(async (pdfBuffer) => {
        console.log(pdfBuffer.length + ' bytes submitted');
        const pdfDoc = await PDFDocument.load(pdfBuffer, { capNumbers: true });
        console.log(pdfDoc);

        const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman);
        // const page = pdfDoc.addPage();
        const pagesCount = pdfDoc.getPageCount();
        const page = pdfDoc.getPage(pagesCount-1);
        const { width, height } = page.getSize();
        const fontSize = 20;
        page.drawText('Signed By Cristi C.', {
            x: width - 10 * fontSize,
            y: height - 40 * fontSize,
            size: fontSize,
            font: timesRomanFont,
            color: rgb(0, 0.53, 0.71),
        });
        const pdfBytes = await pdfDoc.save();
        bucket.file('transformed/'+fileBasename).save(pdfBytes).then(function (res) {}); //Save file in folder signed with the original name
        console.log('Document transformed');
    });

The error is: Expected xref at NaN but found other content

Thanks!