Enabling dark theme in our JavaScript PDF viewer
With Nutrient Web SDK, it’s possible to change the interface to dark mode programmatically or based on device information.
The NutrientViewer.Configuration#theme property accepts one of six values:
NutrientViewer.Theme.LIGHT— Light theme (default)NutrientViewer.Theme.DARK— Dark themeNutrientViewer.Theme.AUTO— Automatically matches system preferenceNutrientViewer.Theme.HIGH_CONTRAST_LIGHT— High contrast light theme for accessibilityNutrientViewer.Theme.HIGH_CONTRAST_DARK— High contrast dark theme for accessibility- Custom theme object — Your own custom theme
The default value is NutrientViewer.Theme.LIGHT, which is the light theme.
You can set your preferred theme in the configuration object passed to NutrientViewer.load (try it in the Playground(opens in a new tab)).
Applying dark theme
Here’s a complete example of applying the dark theme:
import NutrientViewer from "@nutrient-sdk/viewer";
// Get the container element where the viewer will be mounted.const container = document.getElementById("nutrient-container");
NutrientViewer.load({ container, document: "document.pdf", theme: NutrientViewer.Theme.DARK,}).catch((error) => { console.error("Failed to load viewer:", error);});Automatic theme based on system preference
NutrientViewer.Theme.AUTO will automatically choose the theme based on the user preferences and the prefers-color-scheme media query, which isn’t available in every browser. You can check the current browser support for the prefers-color-scheme media query here(opens in a new tab).
import NutrientViewer from "@nutrient-sdk/viewer";
const container = document.getElementById("nutrient-container");
NutrientViewer.load({ container, document: "document.pdf", theme: NutrientViewer.Theme.AUTO,}).catch((error) => { console.error("Failed to load viewer:", error);});High contrast themes
For improved accessibility, you can use the high contrast themes:
import NutrientViewer from "@nutrient-sdk/viewer";
const container = document.getElementById("nutrient-container");
// High contrast dark theme.NutrientViewer.load({ container, document: "document.pdf", theme: NutrientViewer.Theme.HIGH_CONTRAST_DARK,}).catch((error) => { console.error("Failed to load viewer:", error);});Changing theme at runtime
You can also change the theme after the viewer has loaded by using the setViewState method:
import NutrientViewer from "@nutrient-sdk/viewer";
const container = document.getElementById("nutrient-container");
NutrientViewer.load({ container, document: "document.pdf", theme: NutrientViewer.Theme.LIGHT,}) .then((instance) => { // Toggle to dark theme later. document.getElementById("dark-mode-toggle").addEventListener("click", () => { instance.setViewState((viewState) => viewState.set("theme", NutrientViewer.Theme.DARK) ); }); }) .catch((error) => { console.error("Failed to load viewer:", error); });