pdf-lib icon indicating copy to clipboard operation
pdf-lib copied to clipboard

Expected instance of PDFArray, but got instance of PDFDict

Open FlawaCLV opened this issue 3 years ago • 1 comments
trafficstars

What were you trying to do?

Remove all annotations

How did you attempt to do it?

const removePdfAnnotations = async (filePath: string): Promise<Uint8Array> => {
  const uint8Array = await readFile(filePath);
  const pdfDoc = await PDFDocument.load(uint8Array);
  const pages = pdfDoc.getPages();

  pages.forEach((page) => {
    const annotations = page.node.Annots();
    const size = annotations?.size();
    if (size) {
      for (let i = 0; i < size; i++) {
        annotations?.remove(i);
      }
    }
  });

  return pdfDoc.save();
};

What actually happened?

It works fine on 99% of the PDFs I used. But recently, it fails at const annotations = page.node.Annots(); with Expected instance of PDFArray, but got instance of PDFDict

What did you expect to happen?

List annotations

How can we reproduce the issue?

Here is the PDF type-source-error.pdf

Version

1.17.1

What environment are you running pdf-lib in?

Node

Checklist

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

Additional Notes

No response

FlawaCLV avatar Mar 16 '22 17:03 FlawaCLV

@FlawaCLV, I faced with a similar issue.. As a quick fix I just added some check before using Annots(). If it throws an error I just create expected pdf object type for this and set it back. After that Annots() works as expected on this page

try {
  page.node.Annots();
} catch (err: unknown) {
  const annotsArray = page.node.context.obj([]);
  page.node.set(PDFName.Annots, annotsArray);
}

IOuser avatar Jun 08 '22 10:06 IOuser