Skip to content

Cannot sign flattened PDFs using a certificate (error: There was a problem reading this document (14)) #1757

@IonelLupu

Description

@IonelLupu

What were you trying to do?

We are trying to sign flattened PDFs using a certificate. The PDFs were flattened using pdf-lib after filling them in. (filling doesn't matter. We can skip filling and we still get the same error.)

How did you attempt to do it?

We just load the PDF (code below) and then we flatten it. That's it.

What actually happened?

Getting the below error suggesting the PDF is corrupt. Do you have any idea why?

Image

What did you expect to happen?

To not get this error.

How can we reproduce the issue?

here is the function that generates the flattened PDF:

 function report() {
    const pdfPath = join(__dirname, "wh347.pdf");
    const pdfBuffer = await fs.readFile(pdfPath);

    const outputPdfDoc = await PDFDocument.create();

    const templatePdfDoc = await PDFDocument.load(pdfBuffer);
    const templateForm = templatePdfDoc.getForm();

    templateForm.flatten();

    // Copy both pages from the filled template
    const [filledPage1] = await outputPdfDoc.copyPages(templatePdfDoc, [0]);
    outputPdfDoc.addPage(filledPage1);

    // Save the PDF
    const pdfBytes = await outputPdfDoc.save();

    return {
      type: "pdf" as const,
      data: Buffer.from(pdfBytes),
    };

You can use the buffer to save the file on disk.

I attached the unfilled PDF (file pdf-A.pdf) which can be signed using a certificate. I also attached the flattened pdf (file pdf-B.pdf) which was flattened using pdf-lib. This one cannot be signed using a certificate.

pdf-A.pdf
pdf-B.pdf

Version

1.17.1

What environment are you running pdf-lib in?

Node

Checklist

  • My report includes a Short, Self Contained, Correct (Compilable) Example.
  • I have attached all PDFs, images, and other files needed to run my SSCCE.

Additional Notes

I did a test and I opened the fillable PDF (file pdf-A.pdf) in Chrome, filled it and printed (so it gets flattened). Then, I went to Acrobat to sign it using a certificate as I did before and it works.

It seems there is a problem in how pdf-lib flattens PDFs, since signing works when I flatten using Chrome.

Also, if I don't flatten the PDF, signing works. But opening the PDF in Acrobat doesn't display the values in the fillable fields unless I click on that field, which is weird:

Screen.Recording.2025-08-29.at.23.27.12.mov

But, we need to flatten the PDFs, so not flattening is not an option.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions