Restore the Last Seen Page When Reopening a Document

If you want to jump to the last seen page of a document, follow the steps outlined below.

  1. Add a listener for viewState.currentPageIndex.change events.

  2. On the event listener, store the current visited page. If you only need to keep it client-side, you can use local storage. Otherwise, send the information to your backend.

  3. Once the user returns to the same document, retrieve the last seen pageIndex and move the instance to it:

const STORAGE_KEY = "lastViewedPageMap";

// In production, this might come as input.
const documentId = "7KQ5466P9XZ4KCG1MFHQBAMC21";

PSPDFKit.load({
  documentId,
  container: "#main"
  // ...
}).then((instance) => {
  // `localStorage` is used as an example.
  const lastViewedPageString = localStorage.getItem(STORAGE_KEY);
  if (lastViewedPageString) {
    const map = JSON.parse(lastViewedPageString);
    const page = map[documentId];
    if (page) {
      instance.setViewState((v) =>
        v.set("currentPageIndex", parseInt(page))
      );
    }
  }

  instance.addEventListener(
    "viewState.currentPageIndex.change",
    (page) => {
      const current = localStorage.getItem(STORAGE_KEY);

      const map = current ? JSON.parse(current) : {};

      localStorage.setItem(
        STORAGE_KEY,
        JSON.stringify({ ...map, [documentId]: page })
      );
    }
  );
});

This has been tested with PSPDFKit for Web 2020.3.0.