How Do I Toggle between Themes?

By default, PSPDFKit uses a light theme, and you can change the theme in your configuration when loading your document. However, you may want to toggle between dark theme and light theme at runtime. Currently, there isn’t a simple setting for this, but you can use the following workaround:

let instance;
let darkCssHref;

function getDarkThemeUrl() {
  const links = instance.contentDocument.querySelectorAll("link");
  for (let i = 0; i < links.length; i++) {
    if (links[i].href.includes("/dark-")) {
      return links[i].href;
    }
  }
  throw new Error("Cannot get the dark theme URL: dark theme not set.");
}

function isCurrentThemeDark() {
  const links = instance.contentDocument.head.querySelectorAll("link");
  for (let i = 0; i < links.length; i++) {
    if (links[i].href.includes("/dark-")) {
      return true;
    }
  }
  return false;
}

function setDarkTheme() {
  if (isCurrentThemeDark()) {
    return;
  }
  const linkEl = instance.contentDocument.createElement("link");
  linkEl.setAttribute("rel", "stylesheet");
  linkEl.setAttribute("dataloaded", "true");
  linkEl.setAttribute("href", darkCssHref);
  instance.contentDocument.head.appendChild(linkEl);
}

function setLightTheme() {
  if (!isCurrentThemeDark()) {
    return;
  }
  const links = instance.contentDocument.head.querySelectorAll("link");
  for (let i = 0; i < links.length; i++) {
    if (links[i].href.includes("/dark-")) {
      links[i].remove();
      return;
    }
  }
}

PSPDFKit.load({
  ...defaultConfiguration,
  toolbarItems: PSPDFKit.defaultToolbarItems.reduce((acc, item) => {
    if (item.type === "spacer") {
      return acc.concat([
        item,
        {
          type: "custom",
          title: "Toggle theme",
          onPress: () => {
            if (isCurrentThemeDark()) {
              setLightTheme();
            } else {
              setDarkTheme();
            }
          }
        }
      ]);
    }
    return acc.concat([item]);
  }, [])
}).then((_instance) => {
  console.log("PSPDFKit for Web successfully loaded!!", instance);

  instance = _instance;
  darkCssHref = getDarkThemeUrl();

  return _instance;
});