# Document sources

Open PDFs from a URL, a File the user picked, or bytes you already have, without uploading anything.

`source` accepts everything a web app usually has at hand when it wants to show a PDF:

- a URL string or `URL` object, fetched by the viewer;
- a `File` or `Blob`, for example from a file input or drag and drop;
- an `ArrayBuffer` or `Uint8Array` you fetched, generated or decrypted yourself.

## Basics

Pass a URL and the viewer fetches, parses and renders the document.

**Demo: A URL source**

```tsx
import { PdfViewer } from '@kingtech/react-pdf-viewer';

export default function Demo() {
  return <PdfViewer source="/samples/letter-3pages.pdf" />;
}
```

`null`, `undefined` and an empty string show the empty state. Changing `source` aborts the previous request and destroys the previous document, so switching documents quickly never shows a stale page.

### Local files

A `File` is read in the browser and never leaves the user's device.

**Demo: A File from an input**

```tsx
import { PdfViewer } from '@kingtech/react-pdf-viewer';
import { useState } from 'react';

export default function Demo() {
  // Keep binary sources in state: they compare by identity.
  const [file, setFile] = useState<File | null>(null);

  return (
    <>
      <p className="demo-controls">
        <label>
          Choose a PDF{' '}
          <input
            type="file"
            accept="application/pdf"
            onChange={(event) => setFile(event.target.files?.[0] ?? null)}
          />
        </label>
      </p>
      <PdfViewer source={file} />
    </>
  );
}
```

### Bytes

`ArrayBuffer` and `Uint8Array` sources are copied before PDF.js takes ownership of them, so the buffer you pass stays usable afterwards.

**Demo: An ArrayBuffer source**

```tsx
import { PdfViewer } from '@kingtech/react-pdf-viewer';
import { useEffect, useState } from 'react';

export default function Demo() {
  const [bytes, setBytes] = useState<ArrayBuffer | null>(null);

  useEffect(() => {
    // Bytes you already have: fetched by your own code, generated or decrypted.
    fetch('/samples/mixed-sizes.pdf')
      .then((response) => response.arrayBuffer())
      .then(setBytes);
  }, []);

  // The viewer copies the bytes, so `bytes` stays usable afterwards.
  return <PdfViewer source={bytes} fileName="mixed-sizes.pdf" />;
}
```

> **Warning: Keep binary sources stable**
>
> Strings compare by value, but every other source compares by identity. Creating a `Blob` or
>   `Uint8Array` during render gives the viewer a new source on every render and reloads the document
>   each time. Keep binary sources in state or memoise them.

## Download file name

The download button uses `fileName` when you pass one; otherwise a `File`'s own name, then the last `.pdf` segment of the URL, then `document.pdf`. See [Download](https://react-pdf-viewer-chi.vercel.app/react-pdf-viewer/download/).

## Customization

`renderEmpty` replaces the view shown while there is no document, for example with a call to action.

**Demo: A custom empty state**

```tsx
import { PdfViewer } from '@kingtech/react-pdf-viewer';

export default function Demo() {
  return (
    <PdfViewer
      source={null}
      renderEmpty={() => (
        <div role="status" style={{ padding: 32, textAlign: 'center' }}>
          <strong>No report selected</strong>
          <p>Pick a report from the list to preview it here.</p>
        </div>
      )}
    />
  );
}
```

The loading and error views have their own slots; see [Loading states](https://react-pdf-viewer-chi.vercel.app/react-pdf-viewer/loading-states/), [Error states](https://react-pdf-viewer-chi.vercel.app/react-pdf-viewer/error-states/) and the [customization guide](https://react-pdf-viewer-chi.vercel.app/react-pdf-viewer/customization/).

## Advanced / escape hatch

To load documents without the viewer, for example to count pages or render thumbnails in your own layout, use [`usePdfDocument`](https://react-pdf-viewer-chi.vercel.app/react-pdf-viewer/headless/) directly. It accepts the same sources and request options.

## Limitations

- **Cross-origin URLs need CORS.** The browser blocks reading a PDF from another origin unless the server sends `Access-Control-Allow-Origin`. The viewer reports a `NETWORK_ERROR`. Workaround: enable CORS on the server, or proxy the file through your own origin. See [Authenticated requests](https://react-pdf-viewer-chi.vercel.app/react-pdf-viewer/authenticated-requests/).
- **Large files are loaded in full.** URL sources are fetched completely before rendering starts (range requests are not used), so a very large PDF takes as long as its download. Workaround: split huge documents server-side, or show your own progress UI with `renderLoading`.
- **Streams are not accepted.** A `ReadableStream` is not a `PdfSource`. Workaround: read it into a `Blob` or `ArrayBuffer` first (`await new Response(stream).blob()`).

## API

- [PdfViewer](https://react-pdf-viewer-chi.vercel.app/react-pdf-viewer/api/pdf-viewer.md)
- [PdfSource](https://react-pdf-viewer-chi.vercel.app/react-pdf-viewer/api/pdf-source.md)

---

## PdfViewer reference

A PDF viewer: one page at a time with a toolbar for zoom, navigation, fullscreen, rotation, download and print.

Default props give a classic single-page layout; every additional feature (text layer, links, continuous layout, thumbnails, search, …) is opt-in.

### Used by

- [Document sources](https://react-pdf-viewer-chi.vercel.app/react-pdf-viewer/document-sources.md)

### Import

```ts
import { PdfViewer } from '@kingtech/react-pdf-viewer';
```

### Props

| Name | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| `source` | `PdfSource \| null` | — | Yes | The document: a URL string or `URL`, or `ArrayBuffer` / `Uint8Array` / `Blob` / `File`. `null`, `undefined` and `''` show the empty state. |
| `fileName` | `string` | `derived from the source` | No | Download file name. Default: a `File`’s name, the URL’s last `.pdf` segment, else `document.pdf`. |
| `page` | `number` | — | No | Controlled 1-based page. Out-of-range values are clamped and reported through `onPageChange`. |
| `defaultPage` | `number` | `1` | No | Initial page while uncontrolled, and the page every new document opens on. |
| `scale` | `number` | — | No | Controlled scale: `1` = 100%, one PDF point per CSS pixel. |
| `defaultScale` | `number` | `1` | No | Initial scale while uncontrolled; also the reset-zoom target and the scale at which fitting applies. |
| `rotation` | `Rotation` | — | No | Controlled clockwise rotation, added to each page’s intrinsic rotation. |
| `defaultRotation` | `Rotation` | `0` | No | Initial rotation while uncontrolled. |
| `fullscreen` | `boolean` | — | No | Controlled fullscreen state. Passing it selects `fullscreenMode="controlled"` unless a mode is set. |
| `defaultFullscreen` | `boolean` | `false` | No | Initial fullscreen state while uncontrolled. |
| `fullscreenMode` | `FullscreenMode` | `'controlled' when fullscreen is passed, else 'native'` | No | `controlled`: layout only, the parent presents fullscreen (e.g. in its own dialog). `native`: the browser Fullscreen API on the viewer root, falling back to `overlay`. `overlay`: a fixed full-viewport layer with a focus trap; `Esc` closes it. |
| `minScale` | `number` | `0.25` | No | Zoom floor (25%). |
| `maxScale` | `number` | `5` | No | Zoom ceiling (500%). |
| `scaleStep` | `number` | `0.05` | No | Increment of the zoom buttons and the `+` / `-` keys. |
| `zoomLevels` | `readonly number[]` | — | No | Preset ladder, e.g. `[0.5, 1, 1.5, 2, 4]`: the zoom buttons step between presets instead of by `scaleStep`. |
| `fitWidthAtDefaultScale` | `boolean` | `true` | No | At the default scale, shrink the page to the available width. |
| `fitMode` | `'page' \| 'none' \| 'width'` | `'none'` | No | At the default scale, fill the width (`width`) or fit the whole page (`page`). Zooming away shows the page at true size. |
| `password` | `string` | — | No | Password for encrypted documents. Changing it reloads the document. |
| `pdfjsOptions` | `PdfJsDocumentOptions` | — | No | Per-instance `getDocument` overrides such as `cMapUrl`, `standardFontDataUrl` or `verbosity`. Source-related options are managed by the viewer. |
| `toolbar` | `boolean \| ToolbarConfig` | `true` | No | `false` hides the toolbar; an object sets `position`, `actions` and `hiddenWhenCompact`. |
| `compactBreakpoint` | `number` | `960` | No | Viewport width (px) below which the compact layout applies: less padding, and `hiddenWhenCompact` actions hidden outside fullscreen. |
| `keyboardShortcuts` | `boolean` | `true` | No | Keyboard shortcuts while focus is inside the viewer. |
| `printMode` | `'render' \| 'open-url'` | `'render'` | No | `render` prints through a hidden iframe, with progress and Cancel; `open-url` opens the PDF in a new tab. |
| `maxCanvasPixels` | `number` | `16777216` | No | Canvas pixel budget per page (4096 × 4096). Above it, resolution degrades gracefully instead of failing. |
| `labels` | `Partial<PdfViewerLabels>` | `English (defaultLabels)` | No | Overrides for any visible string or accessible name. Keep the object stable (e.g. at module scope). |
| `locale` | `string` | `the browser locale` | No | BCP 47 locale for number formatting, e.g. `hu-HU`. |
| `layout` | `'single' \| 'continuous'` | `'single'` | No | One page at a time or vertical scrolling through all pages. Only the visible pages ±1 are rendered; the page indicator follows the scroll position. |
| `textLayer` | `boolean` | `false` | No | Selectable, copyable text that assistive technology can read. |
| `annotationLayer` | `boolean` | `false` | No | Clickable links: internal links navigate, external links open in a new tab with `rel="noopener noreferrer"`. |
| `pageInput` | `boolean` | `false` | No | Editable page number in the toolbar. |
| `zoomReset` | `boolean` | `false` | No | The zoom label becomes a button that resets zoom. |
| `wheelZoom` | `boolean` | `false` | No | `Ctrl` / `⌘` + wheel and trackpad pinch zoom, anchored at the pointer. |
| `passwordPrompt` | `boolean` | `false` | No | Ask for the password of encrypted documents instead of reporting `PASSWORD_REQUIRED`. |
| `renderPasswordPrompt` | `(context: { incorrect: boolean; submit: (password: string) => void }) => ReactNode` | — | No | Replaces the built-in password form (with `passwordPrompt`). |
| `thumbnails` | `boolean` | `false` | No | Lazily rendered page thumbnails sidebar, hidden in compact, non-fullscreen mode. |
| `search` | `boolean` | `false` | No | Find bar with highlighting (implies `textLayer`). `Ctrl` / `⌘` + `F` focuses it, `Enter` / `Shift` + `Enter` step through matches, `Esc` clears. |
| `renderLoading` | `() => ReactNode` | — | No | Replaces the loading view. |
| `renderError` | `(error: PdfViewerError, actions: { retry: () => void }) => ReactNode` | — | No | Replaces the document and page error views. |
| `renderToolbar` | `(api: PdfViewerApi) => ReactNode` | — | No | Replaces the toolbar. Render `&lt;PdfToolbar api={api} /&gt;` inside to reuse parts. |
| `renderEmpty` | `() => ReactNode` | — | No | Replaces the view shown without a source. |
| `className` | `string` | — | No | Added to the root (`.rpv-root`). `rpv-theme-dark` and `rpv-theme-auto` select the dark presets. |
| `style` | `CSSProperties` | — | No | Inline styles on the root, e.g. CSS variables. |
| `id` | `string` | — | No | Id of the root element. |
| `aria-label` | `string` | `labels.viewer` | No | Accessible name of the viewer region. |
| `requestInit` | `RequestInit` | — | No | Extra `fetch` options for URL sources: headers, `credentials`, `mode`, … |
| `fetcher` | `(url: string, init: RequestInit) => Promise<Response>` | — | No | Replaces `fetch` entirely, e.g. with an authenticated HTTP client. |
| `getHttpErrorMessage` | `(response: Response) => Promise<string>` | — | No | Builds the `HTTP_ERROR` message. Return `undefined` for the default: an RFC 7807 `detail`, then `title`, then a JSON string body, then `Failed to fetch PDF: {status} {statusText}`. |

### Events

| Name | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| `onPageChange` | `(page: number) => void` | — | No | Called whenever the page changes, controlled or not. |
| `onScaleChange` | `(scale: number) => void` | — | No | Called whenever the scale changes. |
| `onRotationChange` | `(rotation: Rotation) => void` | — | No | Called whenever the rotation changes. |
| `onFullscreenChange` | `(fullscreen: boolean) => void` | — | No | Called whenever fullscreen is entered or left. |
| `onDocumentLoad` | `(info: { numPages: number; fingerprint: string }) => void` | — | No | A document finished loading. |
| `onPageRender` | `(info: PageRenderInfo) => void` | — | No | A page render completed. |
| `onError` | `(error: PdfViewerError) => void` | — | No | Every failure except aborted loads, canceled renders and HTTP errors handled by `onHttpError`. |
| `onDownload` | `(context: { fileName: string; data: Uint8Array }) => false \| void` | — | No | Before saving; `data` holds the already-loaded bytes. Return `false` to handle the download yourself. |
| `onPrint` | `() => false \| void` | — | No | Before printing. Return `false` to handle printing yourself. |
| `onHttpError` | `(response: Response) => boolean \| void \| Promise<boolean \| void>` | — | No | Called for non-2xx responses. Return `true` when handled (e.g. after redirecting to sign-in): the viewer shows its empty state and does not call `onError`. |

### CSS classes

| Key | Class | Description |
| --- | --- | --- |
| rpv-root | `.rpv-root` | The root element. Add <code>rpv-theme-dark</code>, or <code>rpv-theme-auto</code> to follow the operating system, for the dark preset. |
| data-status | `[data-status]` | Document status. |
| data-layout | `[data-layout]` | The <code>layout</code> prop. |
| data-compact | `[data-compact]` | The viewport is narrower than <code>compactBreakpoint</code>. |
| data-fullscreen | `[data-fullscreen]` | In fullscreen, in any mode. |
| data-presentation | `[data-presentation]` | How fullscreen is presented; <code>layout</code> in controlled mode. |
| data-zoomed | `[data-zoomed]` | The scale is above <code>defaultScale</code>. |

### Source

[packages/react-pdf-viewer/src/PdfViewer.tsx](https://github.com/kiralygyula92/react-pdf-viewer/blob/main/packages/react-pdf-viewer/src/PdfViewer.tsx#L125)


---

## PdfSource reference

A PDF document source: a URL for the viewer to fetch, or a file or bytes that are already in memory.

- `string` / `URL`: fetched by the viewer (see `PdfRequestOptions`).
- `ArrayBuffer` / `Uint8Array` / `Blob` (including `File`): read directly, nothing is uploaded.

Strings compare by value; every other source compares by identity, so keep binary sources referentially stable (e.g. in state) to avoid reloading on every render.

### Used by

- [Document sources](https://react-pdf-viewer-chi.vercel.app/react-pdf-viewer/document-sources.md)

### Import

```ts
import type { PdfSource } from '@kingtech/react-pdf-viewer';
```

Signature: `type PdfSource = string | URL | ArrayBuffer | Uint8Array | Blob`

### Source

[packages/react-pdf-viewer/src/types.ts](https://github.com/kiralygyula92/react-pdf-viewer/blob/main/packages/react-pdf-viewer/src/types.ts#L15)

