Toggle PDF viewer theme | Nutrient
Nutrient Web SDK resolves the theme once, when the viewer loads, from NutrientViewer.Configuration#theme — there’s no API for retheming a running instance. ViewState has no theme property either, so setViewState can’t change it. To offer a light/dark toggle, unload the instance and load a new one with the other theme.
The example below tracks the current theme and disables the toggle while a reload is in flight:
import NutrientViewer from "@nutrient-sdk/viewer";
const container = document.getElementById("nutrient-container");const toggle = document.getElementById("toggle-theme");
let instance = null;let currentTheme = NutrientViewer.Theme.LIGHT;
async function loadWithTheme(theme) { // Loading is asynchronous, so block a second switch until this one settles. toggle.disabled = true;
try { // `load()` throws if the container already holds an instance; `unload()` is a no-op when it doesn't. const initialViewState = instance?.viewState; NutrientViewer.unload(container);
instance = await NutrientViewer.load({ container, document: "document.pdf", initialViewState, theme, }); currentTheme = theme; } catch (error) { console.error("Failed to load viewer:", error); } finally { toggle.disabled = false; }}
loadWithTheme(currentTheme);
toggle.addEventListener("click", () => { loadWithTheme( currentTheme === NutrientViewer.Theme.LIGHT ? NutrientViewer.Theme.DARK : NutrientViewer.Theme.LIGHT );});Because the reload creates a new instance, the sample hands the view state across as initialViewState. Annotations and document edits aren’t carried over automatically — in Standalone, calling instance.save() alone won’t protect them either. See changing theme at runtime for the steps specific to your backend.
This example toggles between Theme.LIGHT and Theme.DARK. To follow the operating system’s setting instead of a button, load the viewer with NutrientViewer.Theme.AUTO. For every theme value — including the high-contrast ones — plus custom themes, see the dark theme guide.