Skip to content

usePrintContext

The usePrintContext hook provides functionalities for printing the currently loaded PDF file within the React PDF.

It enables you to create custom print buttons or other UI elements that can trigger printing, monitor print progress, and handle print-related events.

Return Type

NameTypeDescription
cancel() => voidTo cancel the print operation if it is in progress
print() => voidTo initiate the print process
progressPreparePrintProgressThe current progress of the print preparation. It contains information like the number of pages loaded and the current percentage of progress.
setOnComplete() => voidA callback function that is triggered when the print preparation is completed successfully and the document is ready for printing.
setOnError(error: Error) => voidA callback function that is triggered when an error occurs during the print preparation. It is called with an Error object that describes what went wrong.
setOnProgress(progress: PreparePrintProgress) => voidA callback function that is triggered to provide updates on the progress of the printing preparation. It is called with a PreparePrintProgress object that contains information like the number of pages loaded and the current percentage of progress.

Usage

To ensure the print context can be accessed, you will need to use usePrintContext inside a component which is a child of RPProvider.

This example shows how to create a CustomPrintLayout component which uses usePrintContext hook to handle the print functionality.

import { RPConfig, RPProvider, RPDefaultLayout, RPPages, usePrintContext } from '@pdf-viewer/react'
import { useEffect } from 'react'
const CustomPrintLayout = () => {
const { print, cancel, setOnProgress, setOnComplete, setOnError } = usePrintContext()
useEffect(() => {
// Called when print preparation is complete and document is ready to print
setOnComplete(() => {
console.log('Print Completed!')
})
// Called if an error occurs during print preparation
setOnError((error) => {
if (error) {
alert('Error occurred while printing')
}
})
// Called periodically with progress updates during print preparation
setOnProgress((progress) => {
console.log('Print progress', progress.percentage, progress.loadedPages)
})
}, [])
return (
<div>
<button onClick={print}>Print</button>
<button onClick={cancel}>Cancel Print</button>
</div>
)
}
export const AppPdfViewer = () => {
return (
<RPConfig>
<RPProvider src="https://cdn.codewithmosh.com/image/upload/v1721763853/guides/web-roadmap.pdf">
<CustomPrintLayout />
<RPDefaultLayout>
<RPPages />
</RPDefaultLayout>
</RPProvider>
</RPConfig>
)
}