Hiding Annotations in Our Viewer

In PSPDFKit for Web, annotations can be hidden using the API. There are different methods and approaches, depending on the use case.

In Server-Backed mode, Instant layers can be used to apply your business logic to decide which user can see what annotations, depending on the layer each user has access to. For more on this, please refer to the Instant Layers guide.

Hiding Individual Annotations

The most straightforward way to hide individual annotations is to set the annotation’s noView flag, which is shared across all annotation types:

// Hide the first annotation on page 0.
const annotations = await instance.getAnnotations(0);
const annotation = annotations.first();
instance.update(annotation.set("noView", true));

Setting the noView flag as shown in the code above only hides the annotation from the screen, but it doesn’t prevent it from being printed. Meanwhile, setting an opacity value of 0 hides the annotation from the printed version of the document:

// Hide the first annotation on page 0 when viewing on the screen and when printing.
const annotations = await instance.getAnnotations(0);
const annotation = annotations.first();
instance.update(annotation.set("opacity", 0));

However, that same effect can be achieved more expressively by setting the corresponding noPrint flag along with noView:

// Hide the first annotation on page 0 when viewing on the screen and when printing.
const annotations = await instance.getAnnotations(0);
const annotation = annotations.first();
instance.update(annotation.set("noView", true).set("noPrint", true));

Using Business Logic for Hiding Annotations

In practice, you may need to enable or disable viewing specific annotations for specific users following more complicated rules. In these cases, you can make use of an annotation’s customData property to assign different capabilities to different user roles:

const delayedAnnotation = annotation
  .set("customData", {
    forUserRoles: ["manager", "editor"]
  })
  .set("opacity", 0);

instance.update(delayedAnnotation);

When you display your annotations, you can filter them by your user’s role:

const annotations = await instance.getAnnotations(0);

const annotationsToUpdate = annotations
  .map((annotation) => {
    const customData = annotation.get("customData");

    if (!customData || !customData.forUserRoles) {
      return;
    }

    if (customData.forUserRoles.includes(currentUser.role)) {
      return annotation.set("opacity", 1);
    }
  })
  .filter(Boolean);

if (annotationsToUpdate.size > 0) {
  instance.update(annotationsToUpdate);
}

Now an annotation will only be displayed when its forUserRoles array contains the role of the currentUser.