How do I limit the number of annotations in a PDF?

Q: How do I limit the number of annotations in a PDF?

A: First we will need to add an event listener to the annotations.create event, so each time an annotation is created we can check how many there are in the document. This can be achieved by using getAnnotations, which gives you the annotations for a given pageIndex. We then need to iterate over every page in the document and count them all together. Once we reach the limit we will disable editing for the document by setting the view state to [readOnly] to disable annotation creation and editing.

instance.addEventListener("annotations.create", async (createdAnnotations) => {
  const annotations = await Promise.all(
    Array.from({ length: instance.totalPageCount }).map((_, pageIndex) =>
      instance.getAnnotations(pageIndex)
    )
  );

  const annotationCount = annotations.flatMap(annotations =>
    annotations.toArray()
  ).length;

  if (annotationCount > 9) {
    instance.setViewState(v => v.set("readOnly", true));
  } 
});

[readOnly]https://pspdfkit.com/api/web/PSPDFKit.ViewState.html#readOnly