Skip to content

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

@taitrd

Description

@taitrd
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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions