Create a New Annotation Tool in Our Viewer Toolbar

Items in the toolbar are plain JavaScript objects with the shape of a PSPDFKit.AnnotationToolbarItem. Most of the time, they’re buttons that perform an action upon being clicked.

Launch Demo

The main differentiator between built-in toolbar items and user-defined ones is the type; for the former, it’s one of the predefined items, and for the latter, it’s custom.

The custom items should have an id property, which is used to identify the item in the toolbar. Also, you have to specify the node property and provide your own DOM node for the custom toolbar item you’re adding:

const selectNode = document.createElement("select");

selectNode.innerHTML = `
	<option value="alice">Alice</option>
	<option value="Bob">Bob</option>
	<option value="carol">Carol</option>
	<option value="john">John</option>
`;

selectNode.addEventListener("change", (event) => {
  console.log(`Selected option: ${event.target.value}`);
});

const item = {
  type: "custom",
  id: "my-button",
  node: selectNode,
  onPress: (event) => {
    alert("hello from my button");
  }
};

onPress is a callback invoked when the item is either clicked or tapped (on touch devices).

Once the custom button is ready, it’s possible to insert it into the current list:

instance.setAnnotationToolbarItems(
  (annotation, { defaultAnnotationToolbarItems }) => {
    return [...defaultAnnotationToolbarItems, item];
  }
);

Or, it can be passed to the list of toolbar items when loading the SDK:

PSPDFKit.load({
  annotationToolbarItems: (
    annotation,
    { defaultAnnotationToolbarItems }
  ) => {
    return [...defaultAnnotationToolbarItems, item];
  }
});

Toolbar Layout and the Spacer Item

The items list is rendered as a flat list of sibling elements that are separated by a special toolbar item called spacer. This solution makes the toolbar layout flexible and easy to customize.

The spacer is an empty element with flex: 1 that can be used to add space in between or around the toolbar items.

You can insert as many spacers as you want, or create a custom toolbar spacer (item) to fit your needs.