How do I toggle between themes?
Q: How do I toggle between themes?
A: By default PSPDFKit is using the light theme and you can change the theme in your configuration when loading your document. But how do you change to the dark theme and back at runtime? There is no simple setting for this currently, which is where the below workaround comes into play:
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; });