node-signpdf icon indicating copy to clipboard operation
node-signpdf copied to clipboard

Invalid object ref: 23 0 R when inserted fields and `pdf-lib.save()` then signing PDF

Open taitrd opened this issue 2 months ago • 1 comments

const pdfDocItem = await PDFDocument.load(pdfDataItem);
const insertedFields = fields.filter((f) => f.inserted);
for (const field of insertedFields) {
  await insertFieldInPDF(pdfDocItem, { ...field, page: 1 });
}

const pdfItemBytes = await pdfDocItem.save({ useObjectStreams: false });

const insertedSignatures = insertedFields.filter(
  (f) => f.type === "SIGNATURE",
);

const pdfItemBuffer = await insertedSignatures.reduce(
  async (promise, field) =>
    promise.then(async (buffer) => {
      return signPdf({
        pdf: buffer,
        signedBy: `${field.recipient.email}`,
      });
    }),
  Promise.resolve(Buffer.from(pdfItemBytes)),
);
# signPdf function

export type SignWithLocalCertOptions = {
  pdf: Buffer;
  signedBy: string;
};

export const signPdf = async ({ pdf, signedBy }: SignWithLocalCertOptions) => {
  try {
    const pdfWithPlaceholder = plainAddPlaceholder({
      pdfBuffer: pdf,
      reason: signedBy,
      contactInfo: signedBy,
      name: signedBy,
      location: signedBy,
      signatureLength: 8192,
      subFilter: 'adbe.pkcs7.detached',
      signingTime: new Date(),
    });

    const signer = new P12Signer(fs.readFileSync('/cert.p12'), {
      passphrase: '',
    });

    const signPdf = new SignPdf();

    const signedPdf = await signPdf.sign(pdfWithPlaceholder, signer);

    return signedPdf;
  } catch (error) {
    console.error(error);
    return pdf;
  }
};

I got this error, just text is Invalid object ref: 23 0 R make the file corrupted after called signPdf.

When insertFieldInPDF from here (too long lines to put it here) calls some functions to draw text or shape. and signPdf is function for signing multiple signatures.

I found and used multiple signature using placeholder-pdf-lib package that resolved multiple signatures issue.

but i recognized that only works for original PDF without inserted fields with pdf-lib

taitrd avatar Oct 24 '25 03:10 taitrd

Hi @taitrd , It would really help if you can provide some reproduction PDF. The error doesn't tell much on its own. The only other (not very helpful probably) thing I can suggest is: https://github.com/vbuch/node-signpdf/issues?q=is%3Aissue%20label%3Apdf-lib

vbuch avatar Oct 24 '25 14:10 vbuch