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

Remove all annotations from pdf

Open cle1000 opened this issue 6 years ago • 7 comments

Hi,

is there a way to delete all annotations from a pdf file?

Thanks!

Best Clemens

cle1000 avatar Jul 15 '20 10:07 cle1000

const { PDFDocument } = require("pdf-lib");
const fs = require("fs");

// use path if you need more advanced path..
const importFilename = "./test.pdf";
const exportFilename = "./test-annofree.pdf";

async function removeAnnots() {
  const uint8Array = fs.readFileSync(importFilename);
  const pdfDoc = await PDFDocument.load(uint8Array);
  const pages = pdfDoc.getPages();

  pages.forEach((page) => {
    const annots = page.node.Annots();
    const size = annots?.size();
    if (size) {
      for (let i = 0; i < size; i++) {
        annots.context.delete(annots.get(i));
      }
    }
  });

  const pdfBytes = await pdfDoc.save();
  fs.writeFileSync(exportFilename, pdfBytes);
}

removeAnnots();
console.log("annotations removed");

Looks like this works.. @Hopding can tell us if this is doing something bad 😂

vegarringdal avatar Jul 15 '20 14:07 vegarringdal

Thank you! It works!

cle1000 avatar Jul 15 '20 16:07 cle1000

@vegarringdal @cle1000 This approach looks fine to me 👍

Hopding avatar Sep 20 '20 14:09 Hopding

On version 1.11.1 experiencing this error when calling pdfDoc.getForm() after pdfDoc.load():

Error: Expected instance of PDFDict, but got instance of undefined

But if I remove pdfDoc.getForm() call, everything works as expected. Any ideas?

chislin avatar Oct 14 '20 11:10 chislin

This seems to have stopped working. When I do annots.context I get "Property 'context' is private and only accessible within class 'PDFArray'."

(I'm using TypeScript--I don't know if that's related?)

JHarrisGTI avatar May 08 '23 19:05 JHarrisGTI

@JHarrisGTI Just ignore the error

Sharcoux avatar Jul 10 '23 15:07 Sharcoux

i'm also trying to remove the rectangle drawn to represent the link annotation or AP for the annotation. how can it be done. it only remove the context

jasrajk avatar Nov 07 '24 22:11 jasrajk