Example: Zoom to a specific level programmatically
The Zoom plugin provides the Zoom
component that can be used to zoom to a particular level.
However, there is a case that you want to create a custom zoom button that is displayed outside of the Viewer
component. This example demonstrates how we can archive that requirement by creating a custom plugin.
Create a plugin definition
Our plugin provides one function that zooms the document to particular level:
import { Plugin, SpecialZoomLevel } from '@react-pdf-viewer/core';
interface CustomZoomPlugin extends Plugin {
zoomTo(scale: number | SpecialZoomLevel): void;
}
Implement the plugin
Our plugin needs to store the zoom
function provided by the PluginFunctions
. You can think of the store as the central management that the plugin and the components in the plugin can interact with.
Our store is quite simple:
import { SpecialZoomLevel } from '@react-pdf-viewer/core';
interface StoreProps {
zoom?(scale: number | SpecialZoomLevel): void;
}
The store is initialized when we create the plugin:
import { createStore, PluginFunctions, SpecialZoomLevel } from '@react-pdf-viewer/core';
const customZoomPlugin = (): CustomZoomPlugin => {
const store = React.useMemo(() => createStore<StoreProps>({}), []);
};
When we register a plugin with the Viewer
component, the plugin's install
will be invoked. It is the right place to set the initial value for our store.
In the following sample code, we just call the update
function to set the zoom
property:
const customZoomPlugin = (): CustomZoomPlugin => {
...
return {
install: (pluginFunctions: PluginFunctions) => {
store.update('zoom', pluginFunctions.zoom);
},
};
}
Now, since the customZoomPlugin
function has to implement the CustomZoomPlugin
interface, we have to implement the zoomTo
function. We can retrieve the store properties here as following:
const customZoomPlugin = (): CustomZoomPlugin => {
...
return {
zoomTo: (scale: number | SpecialZoomLevel) => {
const zoom = store.get('zoom');
if (zoom) {
// Zoom to that scale
zoom(scale);
}
},
};
}
Use the plugin
We need to create an instance of the plugin and register it with the Viewer
component:
const customZoomPluginInstance = customZoomPlugin();
const { zoomTo } = customZoomPluginInstance;
// Register the plugin
<Viewer
fileUrl={fileUrl}
plugins={[
customZoomPluginInstance,
]}
/>
The zoomTo
function provided by the plugin instance can be used at anywhere to zoom the document:
<button onClick={() => zoomTo(SpecialZoomLevel.ActualSize)}>
Actual size
</button>
<button onClick={() => zoomTo(1.5)}>
150%
</button>