Determine the target pages to print from users input

By default, the print plugin prints all pages of the current document. This example demonstrates the scenario where the target pages can be defined by users.
An instance print plugin has the `setPages` function which can be used to indicate the pages you want to print:
import { printPlugin } from '@react-pdf-viewer/print';
const printPluginInstance = printPlugin();
const { setPages } = printPluginInstance;
It is a function that takes the current document and returns the list of zero-based indexes of pages:
The following sample code indicates that only even pages are printed:
setPages((doc) =>
.map((_, i) => i)
.filter((i) => (i + 1) % 2 === 0)
If you want to print odd pages, then here it is:
setPages((doc) =>
.map((_, i) => i)
.filter((i) => (i + 1) % 2 === 1)
You don't have to implement functions that return popular page numbers. The print plugin provides useful functions for most popular cases:
import {
} from '@react-pdf-viewer/print';
`getAllPagesNumbers`Returns all pages numbers of the document
`getCustomPagesNumbers`Returns the custom page numbers. The input is a string consisting of given pages or ranges of pages. For example:
1, 2, 3
1-3, 5, 8-11
`getEvenPagesNumbers`Returns even pages numbers
`getOddPagesNumbers`Returns odd pages numbers
Setting custom page numbers can be done such as:
const handleSetCustomPages = (value: string) => {
if (/^([0-9,-\s])+$/.test(value)) {
where the `handleSetCustomPages` function handles the `onChange` event of a text box allowing users to enter the custom page numbers:
<input type="text" onChange={handleSetCustomPages} />
After setting the target pages, you can print the document by calling the `print` function:
const printPluginInstance = printPlugin();
const { print } = printPluginInstance;
// Invoke the `print` function
<button onClick={print}>Print</button>;

See also