How to Page Through a PDF with PDF.js and React
With the npm package pdfjs-dist, you can draw PDF pages onto a browser <canvas>. In React, split the PDF loading and the page rendering into separate useEffect hooks, stop the loading and cancel any unfinished rendering in the cleanup functions, and paging quickly will not cause errors.
What we build is a PdfPager component with "previous page" and "next page" buttons and a page number such as "3 / 5". In testing, forgetting to set the worker caused the PDF to fail to load, and paging quickly without cancelling the render caused errors. A Japanese PDF without embedded fonts rendered as a blank page until I specified the cMap data.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, pdfjs-dist 6.4.299, Vite 8.3.5, TypeScript 7.0.2, and Playwright 1.63.0. I made two test PDFs: a 5-page PDF that Chromium generated from HTML, and a 1-page PDF assembled without embedding a Japanese font. The app was built with Vite and served with vite preview, and I operated it with Playwright. I checked StrictMode only with the development server. The environment had a Japanese font installed (Noto Sans CJK). I did not test Firefox, Safari, mobile browsers, PDFs with many pages, or large PDFs. I also did not test setting the worker with bundlers other than Vite.

- 1. Install pdfjs-dist and specify the worker location
- 2. A component that draws a page onto a canvas
- 3. When paging quickly, an earlier render overlaps and causes an error
- 4. Render without blur on high-resolution screens
- 5. Japanese PDFs without embedded fonts need a cMap
- 6. Use a key to recreate the component when switching PDFs
Install pdfjs-dist and specify the worker location
According to the PDF.js Getting Started guide, the part that parses PDFs is called the core layer, and its file is pdf.worker.mjs. This file runs as a Web Worker, so set GlobalWorkerOptions.workerSrc to the URL of the worker file (here, the minified pdf.worker.min.mjs). In Vite, the ?url import syntax includes the file in the build output and gives you its URL.
import { GlobalWorkerOptions } from 'pdfjs-dist';
// Use Vite's ?url to include the worker file in the build and get its URL
import workerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
GlobalWorkerOptions.workerSrc = workerUrl;
In the test environment, the build output the worker file (about 1.26MB) to dist/assets/ as a separate file named pdf.worker.min-(ハッシュ).mjs.
If you forget this setting and call getDocument(), the PDF fails to load with the following error:
Error: No "GlobalWorkerOptions.workerSrc" specified.
The PDF.js official example for previous and next page also has a comment saying to set workerSrc when the worker file is located elsewhere.
A component that draws a page onto a canvas
PdfPager takes the PDF URL and the display width. Loading and rendering are split into two useEffect hooks.
import { useEffect, useRef, useState } from 'react';
import { getDocument, RenderingCancelledException } from 'pdfjs-dist';
import type { PDFDocumentProxy, RenderTask } from 'pdfjs-dist';
import './pdfjs';
type Props = { url: string; width?: number };
export function PdfPager({ url, width = 600 }: Props) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const [doc, setDoc] = useState<PDFDocumentProxy | null>(null);
const [pageNum, setPageNum] = useState(1);
const [error, setError] = useState('');
// Load the PDF. When it leaves the screen, clean up both the loading and the document together
useEffect(() => {
let ignore = false;
const task = getDocument({ url, cMapUrl: '/cmaps/' });
task.promise.then(
(pdf) => { if (!ignore) setDoc(pdf); },
(err: Error) => { if (!ignore) setError(`PDF を開けませんでした(${err.message})`); },
);
return () => {
ignore = true;
task.destroy();
};
}, [url]);
// Draw whenever the displayed page changes. If it changes while drawing, cancel the previous drawing
useEffect(() => {
if (!doc) return;
let renderTask: RenderTask | null = null;
let cancelled = false;
(async () => {
const page = await doc.getPage(pageNum);
if (cancelled) return;
// Compute the scale that fits each page's width to the width, per page (since some pages are landscape)
const scale = width / page.getViewport({ scale: 1 }).width;
const viewport = page.getViewport({ scale });
// On high-resolution screens, draw with canvas pixels multiplied by devicePixelRatio
const ratio = window.devicePixelRatio || 1;
const canvas = canvasRef.current!;
canvas.width = Math.floor(viewport.width * ratio);
canvas.height = Math.floor(viewport.height * ratio);
canvas.style.width = `${Math.floor(viewport.width)}px`;
canvas.style.height = `${Math.floor(viewport.height)}px`;
renderTask = page.render({
canvas,
viewport,
transform: ratio !== 1 ? [ratio, 0, 0, ratio, 0, 0] : undefined,
});
try {
await renderTask.promise;
} catch (err) {
if (err instanceof RenderingCancelledException) return; // When cancelled, do nothing
setError(`ページを表示できませんでした(${(err as Error).message})`);
}
})();
return () => {
cancelled = true;
renderTask?.cancel();
};
}, [doc, pageNum, width]);
if (error) return <p role="alert">{error}</p>;
if (!doc) return <p>読み込んでいます…</p>;
const last = doc.numPages;
return (
<div className="pdf-pager">
<div className="pdf-nav">
<button type="button" onClick={() => setPageNum((n) => n - 1)} disabled={pageNum <= 1}>
前のページ
</button>
<span aria-live="polite">{pageNum} / {last}</span>
<button type="button" onClick={() => setPageNum((n) => n + 1)} disabled={pageNum >= last}>
次のページ
</button>
</div>
<canvas ref={canvasRef} />
</div>
);
}
The first useEffect loads the PDF with getDocument(). The return value is a loading task object (PDFDocumentLoadingTask), and once its promise resolves, you get the document (PDFDocumentProxy). The cleanup calls task.destroy(). According to the PDF.js source code, destroy() stops all network loading and terminates the worker. When I called destroy() during loading, the promise was rejected with a Loading aborted error. ignore prevents this error, or a result that arrives later, from being shown on screen.
The second useEffect gets the page with getPage() each time pageNum changes and draws it onto the canvas with render(). The viewport passed to render() represents the page size and scale. The width returned by getViewport({ scale: 1 }) is the original PDF size (with 1 unit equal to 1/72 inch). As described on the official Examples page, to fix the width you divide the desired width by this value to get the scale.
In the test PDF, only page 4 is landscape (A4 landscape). Because the scale is computed per page, the canvas size changed per page. At a display width of 360px, the results were as follows:
| Page displayed | Canvas size |
|---|---|
| Pages 1–3 and page 5 (A4 portrait) | 360×509 |
| Page 4 (A4 landscape) | 360×254 |
The buttons are disabled for "Previous page" on page 1 and for "Next page" on the last page. The page number <span> has aria-live="polite". According to the MDN explanation of aria-live, with polite, assistive technology announces a change without usually interrupting what the user is doing (I did not test screen reader output).
When paging quickly, an earlier render overlaps and causes an error
render() does not finish immediately when called. If you call render() again on the same canvas while the previous one is still drawing, PDF.js throws an error. The official Examples page also explains that you cannot draw two pages on the same canvas at the same time.
So the cleanup of the second useEffect calls renderTask.cancel(). As described in the React official documentation on Effects, the cleanup function runs before the Effect runs again. When the page changes, the previous render is cancelled before the next page starts drawing. The promise of a cancelled render is rejected with RenderingCancelledException, and I do not show that as an error.
I compared this against a version without the renderTask?.cancel() cleanup. A script called the "Next page" button's click() four times, 10ms apart. Each condition was run three times, with these results:
| Component | Result |
|---|---|
PdfPager |
In all three runs, the page number advanced through 2, 3, 4, and 5, and page 5 was drawn on the canvas |
| Version without cancel | In all three runs, an error occurred partway through, and an error message was shown instead of the page. The error appeared twice right after the second press and once right after the fourth press |
The error shown in the version without cancel was:
ページを表示できませんでした(Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.)
Without React, calling render() on pages 1 through 5 in a row on the same canvas produced the same error. Without cancelling, the render of intermediate pages failed with this error. In three attempts, the canvas always ended up showing page 3, not page 5, which was the last one requested. When I cancelled the previous render before each new call, pages 1 through 4 were cancelled and only page 5 was drawn.
On the other hand, when I slowed the CPU by 6 times and pressed the button four times with Playwright's click(), the version without cancel did not produce an error. The error in the version without cancel sometimes occurs and sometimes does not, depending on the timing of the operations.
The official paging example takes a different approach: if rendering is in progress, it remembers the next page number and renders it after the current render finishes. In React, writing the cancellation in the cleanup function means you do not need extra variables to track whether rendering is in progress or which page is next.
Render without blur on high-resolution screens
When devicePixelRatio is 2 and the canvas pixel count matches the display size, the output is blurry. In PdfPager, the canvas pixel count is multiplied by devicePixelRatio, and the display size stays the same in CSS. In PDF.js, passing transform: [ratio, 0, 0, ratio, 0, 0] to render() draws at that scale. This is the same approach as the Hello World explanation on the official Examples page.
When I opened the page with Playwright and devicePixelRatio set to 2, the canvas pixel size was 720×1018 and the display size was 360×509. The following image compares a canvas drawn without accounting for the ratio with the same area drawn at the ratio.

According to MDN, devicePixelRatio also changes when you zoom the browser or move the window to a screen with a different resolution. PdfPager does not include logic to redraw on those changes. If needed, add a trigger for redrawing by referring to the matchMedia() example on the same MDN page, which detects changes.
Japanese PDFs without embedded fonts need a cMap
To draw a PDF in which fonts are not embedded and characters are specified with an Adobe predefined CMap (here, UniJIS-UCS2-H), set the location of the CMap data with cMapUrl in getDocument(). The data is in the cmaps folder of pdfjs-dist, so I copied it into Vite's public folder and served it as is.
$ cp -r node_modules/pdfjs-dist/cmaps public/
In the test environment, cmaps contained 168 .bcmap files. getDocument({ url, cMapUrl: '/cmaps/' }) in PdfPager points to this folder. The explanation of the getDocument() arguments in the PDF.js source code says to add / at the end of cMapUrl.
I made a PDF with Japanese text written in UniJIS-UCS2-H without embedded fonts, and compared rendering with and without cMapUrl.
cMapUrl |
Result |
|---|---|
| Not specified | No characters were drawn (the canvas was completely white). A warning appeared in the console |
| Specified | Characters were drawn (1,750 dark pixels) |
The warning in the console when it was not specified was:
Warning: Error during font loading: Ensure that the `cMapUrl` API parameter is provided.
Nothing appears on screen, so if you handle Japanese PDFs, it is safest to specify cMapUrl from the start. The 5-page test PDF with embedded fonts displayed correctly without cMapUrl.
According to the explanation of the getDocument() arguments, in browsers PDF.js draws non-embedded fonts with system fonts (the default for useSystemFonts). The test environment had a Japanese font installed, so this may also be why characters were drawn when cMapUrl was specified. I did not test an environment without a Japanese font.
PDF.js also has a standardFontDataUrl option for PDFs that do not embed the standard fonts. It does not apply to the test PDFs in this article, so I did not test it.
Use a key to recreate the component when switching PDFs
PdfPager does not reset pageNum to 1 when url changes. The parent passes the URL as a key, so when the PDF changes, the whole component is recreated.
<PdfPager key={url} url={url} width={360} />
The React official documentation also recommends using key when you want to reset all state to its initial values when a prop changes.
When it is recreated, the cleanup of the previous PdfPager calls task.destroy(). I counted the Web Worker creations and terminations. In the production build, opening the 5-page PDF gave "created 1, terminated 0", and after switching to another PDF it gave "created 2, terminated 1". With StrictMode enabled in the development server, the Effect is cleaned up once and then runs again, so the counts were "created 2, terminated 1" and "created 4, terminated 3". In both cases only one worker was running at a time, and no errors appeared.
When I passed a URL that does not exist, the getDocument()
promise was rejected, and the following message was displayed:
PDF を開けませんでした(Unexpected server response (404) while retrieving PDF "http://localhost:4173/missing.pdf".)
PdfPager shows err.message as is, but that is English text meant for investigating the cause. On a screen for end users, it is better to replace it with a message such as "The PDF could not be opened. Please try again later."





