Create a New Inline Text Selection Tool in the Viewer Toolbar

PSPDFKit for Web comes with a customizable inline text selection toolbar that, by default, includes some predefined items. You can customize the toolbar items using the API.

You can customize a number of UI elements such as the annotation toolbar, the color picker, and the sidebar.

The items in the toolbar are plain JavaScript objects with the shape of a PSPDFKit.ToolItem. Usually, they’re buttons that perform an action upon being clicked.

The main differentiator between built-in and user-defined toolbar items is the type. The type of built-in toolbar items is one of the predefined items. The type of user-defined toolbar items is custom.

The predefined item types are:

  • comment

  • highlight

  • redact-text-highlighter

  • squiggle

  • strikeout

  • underline

Optionally, custom items can also have an id to uniquely identify them:

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

When the icon for an item is missing, the title will be displayed instead. This is useful if you want to create text-only buttons.

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

After creating the custom button, add it to the current list:

instance.setInlineTextSelectionToolbarItems(
  ({ defaultItems, hasDesktopLayout }, selection) => {
    console.log(selection);
    // Add custom button only on desktop.
    if (hasDesktopLayout) {
      return [...defaultItems, item];
    }
    return defaultItems;
  }
);

Alternatively, pass the custom button to the list of toolbar items when loading the SDK:

PSPDFKit.load({
  inlineTextSelectionToolbarItems: (
    { defaultItems, hasDesktopLayout },
    selection
  ) => {
    console.log(selection);
    // Add custom button only on desktop.
    if (hasDesktopLayout) {
      return [...defaultItems, item];
    }
    return defaultItems;
  }
});

Adding a Custom DOM Node

You can specify the node property and provide your own DOM node for the custom toolbar item you’re adding:

const node = document.createElement("node");
node.innerText = "Custom Node Item";

const item = {
  type: "custom",
  id: "author",
  node: node,
  onPress: () => alert("Custom node pressed!")
};

instance.setInlineTextSelectionToolbarItems(({ defaultItems }) => {
  return [...defaultItems, item];
});