Add comment annotations programmatically

You can programmatically add comment annotations to a PDF. However, it requires creating both the annotation and its associated comment thread logic to work properly.

How to programmatically create a comment thread

When adding a comment annotation programmatically, you need to:

  • Create the comment marker annotation.

  • Create a comment with the annotation’s id as its rootId.

  • Add both to your document instance.

Playground example

  • This has been tested with Nutrient Web SDK 2024.8.0.

The following steps provide a detailed walkthrough that breaks down the Playground example above.

  1. Create the desired username variable:

const userName = "user name";
PSPDFKit.load({
  ...baseOptions,
  toolbarItems: [{ type: "comment" }]
});
  1. Create a comment marker annotation with specific positioning:

const annotation = new PSPDFKit.Annotations.CommentMarkerAnnotation({
  id: "test",
  pageIndex: 0,
  boundingBox: new PSPDFKit.Geometry.Rect({
    top: 100,
    left: 100,
    width: 10,
    height: 10
  }),
  customData: { circleId: "my-circle" }
});
  1. Add the comment’s content:

const comment = new PSPDFKit.Comment({
  id: "commentId",
  rootId: "test",
  pageIndex: 0,
  text: { format: "plain", value: "Hello" }
});
  1. Apply changes by setting the creator name and creating the annotations:

instance.setAnnotationCreatorName(userName);
instance.create([annotation, comment]);
  1. Add an event listener to track comment creation:

instance.addEventListener("annotations.create", (annotations) => {
  // Show the properties of the first annotation.
  console.log(annotations.first().toJS());
});

Important notes

  • The rootId of the comment must match the annotation’s id.

  • Comment creation dates are automatically set to the browser’s local date/time.

  • It’s not possible to manually override the comment creation date.

  • Both the annotation and its comment must be created together in the same instance.create() call, like in the example above.

Conclusion

By properly linking a comment marker annotation with its associated comment using the rootId, you can programmatically add comments to your PDF documents. Remember that the comment’s creation date will always reflect the current date and time of the browser.

If you need additional assistance or have questions about implementing comment annotations programmatically, don’t hesitate to reach out to our Support team.