Toggle PDF viewer theme | Nutrient
By default, Nutrient 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.
Use changing theme at runtime in the dark theme guide instead. The workaround below doesn’t run on a current default configuration; it needs the viewer to render inside an iframe, which is no longer the default, and it needs the viewer to have been loaded with the dark theme already.
Even where it does run, it only swaps the theme stylesheet, so it rethemes the annotation toolbar, toolbar buttons, dropdown menus, sidebar headers, and the older dialogs — not the document area, the primary toolbar, or the dialogs that follow the design tokens.
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; } }}
NutrientViewer.load({ ...defaultConfiguration, toolbarItems: NutrientViewer.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;});