Remove all annotations from pdf
Hi,
is there a way to delete all annotations from a pdf file?
Thanks!
Best Clemens
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 😂
Thank you! It works!
@vegarringdal @cle1000 This approach looks fine to me 👍
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?
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 Just ignore the error
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