--- url: https://paperpic.dev/guide/accessibility.md description: >- How PaperPic works with the keyboard, screen readers and touch screens, which preferences it follows, and what your app needs to provide. --- # Accessibility People read and fix documents with a mouse, a finger, the keyboard or a screen reader. PaperPic aims at WCAG 2.2 AA, and most of the work is built in. This page lists what it does and what your app needs to add. ## What your app needs to do * **A description.** Pass [`alt`](../reference/options#alt), such as "Receipt from 5 November". Screen readers read it as the name of the image. * **Texts in the user's language.** Screen readers announce the buttons and the changes, so translate them with [`labels`](./labels). * **Your own controls, if any.** With `toolbar: false`, the buttons you build replace the built-in ones, and they need their own names and keyboard support. * **A visible focus.** Keep your CSS from hiding the focus outline of the viewer. ## Keyboard {#keyboard} With the focus inside the viewer: | Key | Action | | -------------------------- | ---------------------------------------------------------------------------- | | `+` and `-` | Zoom in and out | | Arrow keys | Pan | | `0` | Fit the whole image | | `Ctrl+Z` | Undo | | `Ctrl+Shift+Z` or `Ctrl+Y` | Redo | | `Enter` | Confirm the open tool, or else apply the changes | | `Esc` | Let go of a selected corner, close the open tool, or else cancel the changes | On macOS, `Cmd` works like `Ctrl`. With the focus on a button, `Enter` presses that button instead. Before cancelling changes, `Esc` asks for confirmation. With `toolbar: false`, `Esc` still closes a tool, but it does not cancel the edit: your interface decides. * **Toolbar and edit bar.** Tab reaches each bar, and inside it the arrow keys move between the buttons, with `Home` and `End` for the first and the last. * **Corner handles.** With Crop or Straighten open, Tab moves between the handles, and the arrow keys move the focused one 1 screen pixel, or 10 with Shift. Screen readers hear these keys, and that Enter finishes, in the description of each handle. * **Rulers.** The rulers of Adjust and Clean up are native ranges: the arrow keys, `Page Up`, `Page Down`, `Home` and `End` move them. `Enter` keeps the value, as Done does, and `Esc` closes the tool without it. ## Screen readers * The image has the role of an image, named by `alt`. Without `alt`, screen readers skip it. * The toolbar and the edit bar have their own names, such as "Image controls" and "Editing controls". * An announcement reports what the user cannot see by the focus alone: the loading of the image, the zoom level, the start of the edit mode, a document that Straighten finds, a selected corner and the position of a moved corner, the value of a ruler, the result of Apply, and any failure. * The finishes of Clean up are buttons that say whether they are pressed. A tool in use, which a dot marks on screen, is described as "In use". In black and white, Adjust is described with the reason it is disabled. ## Touch screens * With `any-pointer: coarse`, buttons and corner handles measure at least 44 pixels. Any touch screen matches it, also on a laptop with a trackpad. * While a finger drags a corner, a magnifier shows the area under it. * A corner also moves without dragging: press its handle, and then tap where it goes. This works with a mouse too. * While the image is fitted, one finger scrolls the page, so the viewer does not trap people inside it. Once zoomed, it pans the image. ## Preferences * **Reduced motion.** With `prefers-reduced-motion: reduce`, the buttons change state without transitions, and the corners go at once to the document that Straighten finds, without sliding. * **Forced colors.** In Windows high contrast and other forced color modes, pressed buttons and the main actions keep a visible outline. * **Dark mode.** The colors follow the `color-scheme` of your page, which can follow the system. See [Styling](./styling#dark-mode). --- --- url: https://paperpic.dev/guide/tools/adjust.md description: >- How the Adjust tool of PaperPic changes the brightness and the contrast of a document image with a live ruler, and how to set them from code. --- # Adjust Photos taken in poor light come out dark or gray. Adjust changes the brightness and the contrast and keeps the colors, for documents that should not become black and white, such as colored forms or photos. ## Use it 1. Press Edit, then Adjust. Its panel takes the place of the tools: a ruler, and Brightness and Contrast to choose which tone it changes. 2. Drag the ruler. The preview changes while you drag. Choose Contrast to change the other tone with the same ruler. 3. Press Done to keep both tones as one edit, which Undo removes. Cancel this tool leaves the image as it was. The middle of the ruler leaves the image as it is, and the needle catches there, so it is easy to go back to no change. Screen readers announce the value from -100 to 100, such as "Brightness +30". A dot on Adjust marks values that are not 0. Adjust runs after the other edits, so Crop and Straighten show the image with it. ## Adjust or Clean up? | Adjust | [Clean up](./clean-up) | | ------------------------------------ | ------------------------------------------------ | | Keeps the colors and the grays | Turns the document gray, or into black and white | | For colored forms, stamps and photos | For text on paper | | Keeps the format of the source | Gives PNG | In black and white, Adjust is disabled. Black and white compares each pixel with its surroundings, so brightness and contrast would barely change its result. Screen readers hear why it is disabled. With gray, Adjust works, and gray comes after it. ## From code [`setAdjustments()`](../../reference/methods#setadjustments) takes values from -1 to 1, where 0 is no change, and [`getState()`](../../reference/methods#getstate) returns them in `adjustments`: ```ts pic.edit() pic.setAdjustments({ brightness: 0.2, contrast: 0.3 }) ``` While Adjust is open, `setAdjustments()` changes what its panel shows, and [`confirmTool()`](../../reference/methods#confirmtool) keeps it as one edit. In the [`tools`](../../reference/options#tools) option, Adjust is `'adjust'`. --- --- url: https://paperpic.dev/guide/ai-agents.md description: >- How to give Claude Code, Cursor, Copilot and other coding agents the PaperPic docs, with the agent skill, the docs in node_modules, llms.txt or Context7. --- # AI coding agents When a coding agent has to guess how PaperPic works, it writes code that looks right but fails: a container with no height, a missing stylesheet, or the original image uploaded instead of the edited one. Give it the docs so that it doesn't have to guess. Start with the skill, and add one of the other options when the agent needs the full docs. They are all in English, the language agents read best. ## The agent skill {#skill} The skill tells the agent how to set up PaperPic, how to handle the common tasks and which behavior to plan for. The agent only loads it when a task involves PaperPic. Install it in your project: ```sh npx skills add paperpic/paperpic ``` It works with Claude Code, Cursor, GitHub Copilot and any other agent that supports skills. ## The docs in node_modules {#node-modules} Each package ships these pages as Markdown in `dist/docs`, matching the version you installed: ```txt node_modules/@paperpic/core/dist/docs/ ├── examples/ ├── guide/ └── reference/ ``` Agents that search `node_modules` find them there, even offline. To send yours there, add a line that names your package to the instructions it reads, such as `AGENTS.md` or `CLAUDE.md`: ```md The PaperPic docs are in node_modules/@paperpic/vue/dist/docs. ``` ## llms.txt {#llms-txt} The site also publishes its pages in two files made for language models: * [`llms.txt`](https://paperpic.dev/llms.txt) lists every page with its description and a link to its Markdown version. * [`llms-full.txt`](https://paperpic.dev/llms-full.txt) holds every page in a single file. You can read any page as Markdown too: add `.md` to its URL, such as `https://paperpic.dev/guide/getting-started.md`. ## Context7 {#context7} [Context7](https://context7.com/paperpic/paperpic) serves these docs to agents through its MCP server, along with rules for setting up PaperPic. Once your agent uses Context7, ask it to read the docs of `/paperpic/paperpic`. --- --- url: https://paperpic.dev/examples/attach-and-scan.md description: >- Complete example: the user photographs a document, straightens and cleans it up in PaperPic, and your app uploads the result. JavaScript, Vue and React. --- # Attach and scan Most apps that take documents ask the user for a photo of one, such as a receipt for an expense or a signed form. This example lets the user take the photo or pick a file, edit it in PaperPic, and send the result to your server. `upload` is the function from [Upload to a server](./upload), which sends the image and fails when the server does not accept it. :::tabs key:framework \== JavaScript ```html

``` ```ts import { PaperPic } from '@paperpic/core' import '@paperpic/core/style.css' const input = document.querySelector('#photo')! const status = document.querySelector('#status')! const pic = new PaperPic(document.querySelector('#viewer')!, { alt: 'The document you attached', maxOutputSize: 3000, }) input.addEventListener('change', () => { const file = input.files?.[0] input.value = '' if (file) { status.textContent = '' pic.setOptions({ src: file }) } }) // The edit starts as soon as the photo is on display pic.on('load', () => pic.edit()) pic.on('error', ({ phase }) => { if (phase === 'load') { status.textContent = 'This file is not an image the browser can open' } }) pic.on('apply', async ({ blob, type }) => { status.textContent = 'Sending…' try { await upload(blob, type) status.textContent = 'Sent' } catch { status.textContent = 'The document could not be sent' } }) ``` \== Vue ```vue ``` \== React ```tsx import type { ExportedImage, PaperPicEvents, PaperPicInstance } from '@paperpic/react' import { PaperPic } from '@paperpic/react' import { useRef, useState } from 'react' import '@paperpic/react/style.css' export function AttachDocument() { const picRef = useRef(null) const [photo, setPhoto] = useState() const [status, setStatus] = useState('') function choose(input: HTMLInputElement) { const file = input.files?.[0] input.value = '' if (file) { setStatus('') setPhoto(file) } } function failed({ phase }: PaperPicEvents['error']) { if (phase === 'load') { setStatus('This file is not an image the browser can open') } } async function send({ blob, type }: ExportedImage) { setStatus('Sending…') try { await upload(blob, type) setStatus('Sent') } catch { setStatus('The document could not be sent') } } return ( <> {photo && (
picRef.current?.edit()} onError={failed} onApply={send} />
)}

{status}

) } ``` ::: ## Notes * `capture="environment"` opens the back camera on phones, and computers ignore it. Without it, phones offer the camera and the photo library, which suits documents the user already has. * Emptying the input after each choice lets the user pick the same photo again, such as to start over after Apply. * The viewer opens in the edit mode once the photo loads, so the user goes straight to Straighten or Clean up. Leave out the `load` listener to show the photo first. * `phase: 'load'` tells a file the browser cannot open, such as a HEIC photo outside Safari, from a failed edit. [Loading images](../guide/loading#formats) lists the formats. * The photo stays in the browser until Apply calls `upload`. PaperPic sends nothing on its own. * [`maxOutputSize`](../reference/options#maxoutputsize) keeps the upload small. Phone photos have 12 megapixels or more, and documents stay readable at 3000 pixels on the longest side. --- --- url: https://paperpic.dev/guide/tools/clean-up.md description: >- How the Clean up tool of PaperPic turns a document photo gray, or crisp black and white without shadows, and what sensitivity and softness do. Live demo. --- # Clean up Clean up chooses the finish of the image: the original tones, gray, or black and white. Its id in the API is `finish`. Text on paper reads best in black and white, but a photo has shadows, uneven light and gray paper. Black and white compares each pixel with its surroundings to decide whether it is ink or paper, so shadows and uneven light disappear and the text stays sharp. Gray keeps every tone and only removes the color, for documents with photos or stamps that black and white would lose. Straighten the receipt first, then clean it up. ## Use it 1. Press Edit, then Clean up. Its panel takes the place of the tools, with three finishes: Original, Gray and Black and white. It opens in black and white, so the preview turns black and white and the Sensitivity ruler works. 2. Drag the ruler. Higher sensitivity darkens more pixels, which recovers faint or worn text. Lower sensitivity gives a cleaner page, without the print that shows through from the back. 3. Choose Gray instead for a gray image, or Original for the tones of the photo. The ruler only works in black and white. 4. Press Done to keep it as one edit, or Cancel this tool to leave the image as it was. Once Clean up is an edit, it opens again with its finish. To turn it off, choose Original: the edits that came after it stay. Undo, instead, would also remove those edits. Clean up always runs after the other edits. Crop shows the image with its finish, as it will be. Straighten shows it without black and white, because the edges of the paper are hard to find on a cleaned up page, and keeps gray. [Adjust](./adjust) works with gray, which comes after it, and is disabled in black and white, which has tones of its own. ## Softness [`softness`](../../reference/options#softness) sets how much gray black and white keeps at the edges of the letters, from 0 to 1, with 0.25 by default. A little gray smooths the edges and makes small text easier to read. Use `0` for strict black and white, which gives smaller files but breaks thin strokes. ## Format of the result An image in black and white is PNG, because JPEG would add artifacts around its sharp edges. A gray image keeps the format of the source. The [`output`](../../reference/options#output) option can choose another format. ## From code [`setFinish()`](../../reference/methods#setfinish) chooses the finish, `'original'`, `'gray'` or `'mono'` for black and white, and sets the sensitivity of black and white, from 0 to 1, with 0.5 by default. [`getState()`](../../reference/methods#getstate) returns both in `finish`: ```ts pic.edit() pic.setFinish({ mode: 'mono', sensitivity: 0.6 }) ``` While Clean up is open, `setFinish()` changes what its panel shows, and [`confirmTool()`](../../reference/methods#confirmtool) keeps it as one edit. --- --- url: https://paperpic.dev/guide/tools/crop.md description: >- How the Crop tool of PaperPic keeps the part of a photo that holds the document, with corner handles, a magnifier on touch screens and the keyboard. --- # Crop A photo of a document often shows the table, a hand or other papers around it. Crop keeps the rectangle that holds the document and drops the rest. ## Use it 1. Press Edit, then Crop. A rectangle appears inside the image, with a handle at each corner. 2. Drag the corners until the rectangle frames the document. The panel of Crop has zoom buttons, so you can zoom in to place them precisely. 3. Press Done, or `Enter`, to add the crop to the edits. Cancel this tool, or `Esc`, closes Crop without changing anything. While Crop is open, the image looks as the result will, with Adjust and Clean up included. The crop is an edit like any other: Undo removes it, and Apply makes it permanent. ## Corner handles * The handles stay inside the image, and the rectangle never turns inside out. * With a finger or a pen, a magnifier shows the area under it while it drags a corner, so it does not hide where the corner lands. * Without dragging, press a handle and then tap where its corner goes. The handle stays highlighted until then, the zoom buttons zoom toward its corner, and `Esc` lets go of it. * With the keyboard, Tab moves between the handles, and the arrow keys move the focused handle 1 screen pixel, or 10 with Shift. `+` and `-` zoom toward the focused handle. Screen readers announce each move. ## Crop or Straighten? Crop keeps a rectangle as it is. In a photo taken at an angle, the document looks like a trapezoid, and no rectangle fits it. Use [Straighten](./straighten) for those: it moves each corner on its own and flattens the page. ## From code Crop is in the edit bar by default, with the id `'crop'` in [`tools`](../../reference/options#tools). With `toolbar: false`, open it with [`openTool()`](../../reference/methods#opentool), and close it with [`confirmTool()`](../../reference/methods#confirmtool) or [`cancelTool()`](../../reference/methods#canceltool): ```ts pic.edit() pic.openTool('crop') // Later, from a button of your own pic.confirmTool() ``` --- --- url: https://paperpic.dev/reference/css-tokens.md description: >- The CSS custom properties that theme PaperPic, with light and dark values, plus its stylesheet, cascade layer, public classes and control names. --- # CSS tokens The tokens are CSS custom properties that change the look of the component without overriding its rules. Set them on `:root`, on an ancestor of the viewer or on `.paperpic`: ```css :root { --paperpic-color-accent: #c2410c; --paperpic-radius: 0; } ``` | Token | Light | Dark | Description | | -------------------------------- | ------------------ | ------------------ | --------------------------------------------------------------------------------------------------- | | `--paperpic-color-accent` | `#0a84ff` | `#5cb5ff` | Accent of the interface | | `--paperpic-color-dim` | `rgb(0 0 0 / 50%)` | `rgb(0 0 0 / 50%)` | Darkens the image around a selection | | `--paperpic-color-line` | `#fff` | `#fff` | Lines over the image: the outline of a selection, the corner handles and the cross of the magnifier | | `--paperpic-color-line-shadow` | `rgb(0 0 0 / 60%)` | `rgb(0 0 0 / 60%)` | The shadow under each line, so it shows on any image | | `--paperpic-color-surface` | `#fff` | `#151e2e` | Background of the interface | | `--paperpic-color-text` | `#1a263c` | `#f2f5f9` | Text of the interface | | `--paperpic-radius` | `6px` | `6px` | Corner radius of the interface | | `--paperpic-transition-duration` | `0.2s` | `0.2s` | Duration of the interface transitions | ## Dark mode The color tokens take their light or dark value with `light-dark()`, from the `color-scheme` of the page. Without `color-scheme` they are light. With `color-scheme: dark` they are dark, and with `color-scheme: light dark` they are dark when the system prefers a dark color scheme. [Styling](../guide/styling#dark-mode) shows how to set it. To choose both values of a token, use `light-dark()` too: ```css :root { --paperpic-color-accent: light-dark(#c2410c, #fb923c); } ``` The colors that paint over the image, `--paperpic-color-dim`, `--paperpic-color-line` and `--paperpic-color-line-shadow`, have one value for both, because they sit on the photo and not on the interface. A line and its shadow go in pairs: with a dark line, choose a light shadow. ## Stylesheet Each package ships one stylesheet. Import it once in your app: :::tabs key:framework \== JavaScript ```ts import '@paperpic/core/style.css' ``` \== Vue ```ts import '@paperpic/vue/style.css' ``` \== React ```ts import '@paperpic/react/style.css' ``` ::: Its rules live in the `paperpic` cascade layer, so any CSS of yours outside a layer overrides them, whatever its specificity. This includes global resets, such as a rule on `button`. With Tailwind CSS, name the order of the layers, as [Styling](../guide/styling#tailwind) shows. ## Classes {#classes} These classes are public: their names, and the elements they mark, stay stable between releases. The other classes of the component hold its layout together and can change in any release. | Class | Element | | ------------------------- | ---------------------------------------------------------------------------------------------------------------- | | `paperpic` | The root of the viewer | | `paperpic-button` | Every button of the toolbar and the edit bar | | `paperpic-button-danger` | Discard, in the question before discarding the changes | | `paperpic-button-primary` | Apply, and Done in every tool | | `paperpic-button-text` | The buttons of the question before discarding the changes | | `paperpic-edit-bar` | The edit bar, a card at the bottom while editing | | `paperpic-editing` | The root, while editing | | `paperpic-handle` | A corner handle of Crop and Straighten | | `paperpic-host` | The element that the Vue and React components render around the viewer | | `paperpic-icon` | The icon of a button | | `paperpic-status` | The message that shows, and that screen readers hear, while the image loads or the changes apply, and on failure | | `paperpic-status-visible` | The message, while it shows in the middle of the viewer | | `paperpic-toolbar` | The toolbar at the right, hidden while editing | | `paperpic-viewport` | The area that shows the image and takes the keyboard focus | Buttons show their state with ARIA attributes, which you can select too: | Attribute | State | | ------------------------ | ------------------------------------------------------------------------------------------------ | | `[aria-disabled='true']` | The button cannot act now. It keeps the keyboard focus, so it is not `disabled` | | `[aria-pressed='true']` | The fit in effect, Fit to width or Fit to height, or the choice of Adjust that the ruler changes | The hover and these states paint with `box-shadow`, which global resets of buttons leave alone. To restyle them, override `box-shadow` too. ## States {#states} The root, `.paperpic`, carries the state of the viewer in data attributes, so CSS can follow it: | Attribute | Values | | ---------------------- | ---------------------------------------------------------------------------- | | `data-paperpic-status` | `empty`, `loading`, `ready` or `error`, as `status` in the [state](./state) | | `data-paperpic-mode` | `view` or `edit` | | `data-paperpic-tool` | The id of the open tool, such as `crop`. It is missing while no tool is open | ```css .paperpic[data-paperpic-status='error'] .paperpic-status-visible { color: #b91c1c; } ``` ## Controls {#controls} Every button, ruler and corner handle carries `data-paperpic-control`, with the key of its [label](./labels). Select it to style one control: ```css .paperpic-button[data-paperpic-control='edit'] { color: var(--paperpic-color-accent); } ``` | Place | Values | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Toolbar | `edit`, `zoomIn`, `zoomOut`, `fitWidth`, `fitHeight`, `rotateLeft`, `rotateRight`, `download` | | Edit bar | `cancel`, `crop`, `perspective`, `rotateLeft`, `flip`, `adjust`, `finish`, `redact`, `undo`, `redo`, `apply` | | Adjust and Clean up | `brightness` and `contrast`, the choices and their rulers, `finishOriginal`, `finishGray` and `finishMono`, the finishes, and `finishSensitivity`, its ruler | | Every tool | `cancelTool`, `confirm` | | Crop, Straighten and Redact | `zoomIn`, `zoomOut`, `cornerTopLeft`, `cornerTopRight`, `cornerBottomRight`, `cornerBottomLeft` | | Straighten | `paperAuto`, `paperA4`, `paperLetter`, `paperCard` | | Redact | `redactArea`, `redactTurn`, `redactBlack`, `redactWhite` | | Question before discarding | `keepEditing`, `discard` | `rotateLeft` names two buttons that never show at the same time: the one of a read-only viewer, which turns the display, and the one of the edit bar, which turns the image. So do `zoomIn` and `zoomOut`, in the toolbar and in a panel. `brightness` and `contrast` name a choice and its ruler, which show together: add `button` or `input` to the selector to tell them apart. --- --- url: https://paperpic.dev/examples/custom-toolbar.md description: >- A complete example that hides the built-in toolbar of PaperPic and drives the viewer from buttons of your own, kept in step with the state of the viewer. --- # Custom toolbar When the controls of the viewer must match the rest of your interface, hide the built-in ones with `toolbar: false` and call the [methods](../reference/methods) from buttons of your own. This example offers zoom, Straighten, Undo and Apply, and enables each button only when it can act. The [`change`](../reference/events#change) event carries the [state](../reference/state) after each action, including those your buttons start. `load` and `error` report the moments when the image arrives or Apply fails. :::tabs key:framework \== JavaScript ```html

``` ```ts import type { PaperPicState } from '@paperpic/core' import { PaperPic } from '@paperpic/core' import '@paperpic/core/style.css' const pic = new PaperPic(document.querySelector('#viewer')!, { src: '/receipt.jpg', alt: 'A receipt', toolbar: false, }) const actions: Record void> = { zoomIn: () => pic.zoomIn(), zoomOut: () => pic.zoomOut(), edit: () => pic.edit(), straighten: () => pic.openTool('perspective'), confirmTool: () => pic.confirmTool(), cancelTool: () => pic.cancelTool(), undo: () => pic.undo(), cancel: () => pic.cancel(), apply: () => pic.apply(), } const buttons = document.querySelectorAll('[data-action]') for (const button of buttons) { button.addEventListener('click', () => actions[button.dataset.action!]!()) } function update({ status, mode, activeTool, hint, canUndo, canApply, canConfirm, busy }: PaperPicState) { const editing = mode === 'edit' const visible: Record = { zoomIn: true, zoomOut: true, edit: !editing, straighten: editing && !activeTool, confirmTool: Boolean(activeTool), cancelTool: Boolean(activeTool), undo: editing && !activeTool, cancel: editing && !activeTool, apply: editing && !activeTool, } for (const button of buttons) { const action = button.dataset.action! button.hidden = !visible[action] } document.querySelector('[data-action="edit"]')!.disabled = status !== 'ready' document.querySelector('[data-action="undo"]')!.disabled = !canUndo || busy document.querySelector('[data-action="confirmTool"]')!.disabled = !canConfirm document.querySelector('[data-action="apply"]')!.disabled = !canApply || busy document.querySelector('#hint')!.textContent = hint ?? '' } pic.on('change', update) pic.on('load', () => update(pic.getState())) pic.on('error', () => update(pic.getState())) update(pic.getState()) ``` \== Vue ```vue ``` \== React ```tsx import type { PaperPicInstance, PaperPicState } from '@paperpic/react' import { PaperPic } from '@paperpic/react' import { useRef, useState } from 'react' import '@paperpic/react/style.css' export function Receipt() { const picRef = useRef(null) const [state, setState] = useState() function refresh() { setState(picRef.current?.getState()) } const viewer = () => picRef.current! return ( <> {state && (
{state.mode === 'view' && ( )} {state.hint &&

{state.hint}

} {state.mode === 'edit' && state.activeTool && ( <> )} {state.mode === 'edit' && !state.activeTool && ( <> )}
)}
) } ``` ::: ## A slider of your own {#slider} A slider of your own for Clean up opens the tool first. Each move then calls `setFinish()`, which changes what Clean up shows, and `confirmTool()` keeps the last value as one edit. Here Done also applies the result, and Cancel leaves the edit mode, so these controls are the whole interface. :::tabs key:framework \== JavaScript ```html
``` ```ts import { PaperPic } from '@paperpic/core' import '@paperpic/core/style.css' const pic = new PaperPic(document.querySelector('#viewer')!, { src: '/receipt.jpg', alt: 'A receipt', toolbar: false, }) const slider = document.querySelector('#sensitivity')! document.querySelector('#clean-up')!.addEventListener('click', () => { pic.edit() pic.openTool('finish') }) slider.addEventListener('input', () => pic.setFinish({ sensitivity: slider.valueAsNumber })) document.querySelector('#done')!.addEventListener('click', () => { pic.confirmTool() pic.apply() }) document.querySelector('#cancel')!.addEventListener('click', () => { pic.cancelTool() pic.cancel() }) pic.on('change', ({ activeTool, finish }) => { const open = activeTool === 'finish' document.querySelector('#ruler')!.hidden = !open document.querySelector('#clean-up')!.hidden = open slider.value = String(finish.sensitivity) }) ``` \== Vue ```vue ``` \== React ```tsx import type { PaperPicInstance, PaperPicState } from '@paperpic/react' import { PaperPic } from '@paperpic/react' import { useRef, useState } from 'react' import '@paperpic/react/style.css' export function CleanUpRuler() { const picRef = useRef(null) const [state, setState] = useState() const viewer = () => picRef.current! function open() { viewer().edit() viewer().openTool('finish') } function done() { viewer().confirmTool() viewer().apply() } function cancel() { viewer().cancelTool() viewer().cancel() } return ( <> {state?.activeTool === 'finish' ? (
) : ( )}
setState(viewer().getState())} onError={() => setState(viewer().getState())} />
) } ``` ::: ## Notes * With `toolbar: false`, the built-in edit bar is hidden too, so Crop and Straighten show their handles but no Done button. Your interface confirms them with [`confirmTool()`](../reference/methods#confirmtool), as `Enter` does. To close them without their changes, call [`cancelTool()`](../reference/methods#canceltool), as `Esc` does. * While Crop or Straighten is open, `hint` in the state says what to do, such as "Drag the corners", as the built-in edit bar does. Show it, because with `toolbar: false` nothing else does. A new hint, such as after pressing a corner or once Straighten finds the document, comes with `change`. * `canConfirm` in the state says whether `confirmTool()` can keep what the tool shows. Straighten waits until it finds the document or the user moves a corner, so disable your Done button until then. * Sliders of your own can call [`setFinish()`](../reference/methods#setfinish) and [`setAdjustments()`](../reference/methods#setadjustments) directly, which adds one edit for each call. To leave one edit for a whole drag, open the tool with [`openTool()`](../reference/methods#opentool) first: the same methods then change what it shows, and `confirmTool()` keeps it. * [`cancel()`](../reference/methods#cancel) does not ask before discarding the edits. Ask the user first if there are some, such as when `canApply` is true. * The keyboard shortcuts keep working with the focus on the viewer. See [Accessibility](../guide/accessibility). --- --- url: https://paperpic.dev/examples/dialog.md description: >- Complete example that opens PaperPic in a dialog to edit a photo, and closes it when the user applies or cancels. JavaScript, Vue and React. --- # Edit in a dialog Many apps edit a document in a dialog over the page, such as from a list of attachments. This example opens the viewer in a ``, starts the edit mode, and closes the dialog when the user applies the changes or cancels them. `upload` is the function from [Upload to a server](./upload). :::tabs key:framework \== JavaScript ```html
``` ```ts import { PaperPic } from '@paperpic/core' import '@paperpic/core/style.css' const dialog = document.querySelector('#editor')! const pic = new PaperPic(document.querySelector('#viewer')!, { src: '/receipt.jpg', alt: 'A receipt', }) let editing = false document.querySelector('#open')!.addEventListener('click', () => { dialog.showModal() pic.edit() }) // A photo still loading starts the edit once it is on display pic.on('load', () => { if (dialog.open) { pic.edit() } }) // Apply or Cancel ends the edit, and the dialog closes with it pic.on('change', ({ mode }) => { if (editing && mode === 'view') { dialog.close() } editing = mode === 'edit' }) // While editing, Esc goes to the viewer, which asks before discarding the changes dialog.addEventListener('cancel', (event) => { if (editing) { event.preventDefault() } }) pic.on('apply', ({ blob, type }) => upload(blob, type)) ``` \== Vue ```vue ``` \== React ```tsx import type { PaperPicInstance, PaperPicState } from '@paperpic/react' import type { SyntheticEvent } from 'react' import { PaperPic } from '@paperpic/react' import { useRef } from 'react' import '@paperpic/react/style.css' export function PhotoEditor() { const dialogRef = useRef(null) const picRef = useRef(null) const editing = useRef(false) function open() { dialogRef.current?.showModal() picRef.current?.edit() } // A photo still loading starts the edit once it is on display function loaded() { if (dialogRef.current?.open) { picRef.current?.edit() } } // Apply or Cancel ends the edit, and the dialog closes with it function changed({ mode }: PaperPicState) { if (editing.current && mode === 'view') { dialogRef.current?.close() } editing.current = mode === 'edit' } // While editing, Esc goes to the viewer, which asks before discarding the changes function keepEditing(event: SyntheticEvent) { if (editing.current) { event.preventDefault() } } return ( <>
upload(blob, type)} />
) } ``` ::: ## Notes * The viewer can live in the dialog while it is closed. It has no size then, and it fits the image as soon as the dialog opens. * Opening the dialog starts the edit mode. If the photo is still loading, the `load` event starts it instead. * Apply and Cancel end the edit, and the [`change`](../reference/events#change) that follows closes the dialog. If Apply fails, the edit stays open, and so does the dialog. * Each opening edits the image on display, which after an Apply is the result. To start from the original every time, call [`reload()`](../reference/methods#reload) before `edit()`. --- --- url: https://paperpic.dev/guide/editing.md description: >- How the edit mode of PaperPic works, from the Edit button to Apply, with the tools, Undo and Redo, the preview and the events your code receives. --- # Editing A photo of a document usually needs a few fixes before it is worth keeping. The edit mode groups them: the user makes the changes, checks them, and applies them all at once. The [playground](../playground) has the whole edit mode to try. ## The edit flow 1. The user presses Edit, the pencil in the toolbar. The toolbar hides, so nothing covers the image, and the edit bar appears at the bottom of the viewer. 2. Rotate left and Flip add an edit at once. The other tools open a panel in the edit bar, and Done adds what the user chose there as one edit. Undo and Redo move through the edits. 3. Apply computes the result and goes back to viewing. Cancel discards the edits, and asks first when there are some. Nothing changes the image until Apply. Before that, the edits are a list that the viewer previews. In a narrow viewer, the edit bar has two rows: the tools, or the panel of the open tool, above, and below, Cancel at the left and Apply, or Done, at the right. From 38rem wide, everything fits on one row. Either way, the bar keeps its height when a tool opens, so the image keeps its place. A dot marks Adjust and Clean up while their setting is in effect. ## Tools | Tool | What it does | Id | | -------------------------------------- | ---------------------------------------------------------------------- | ------------- | | [Crop](./tools/crop) | Keeps the part of the image inside four corners | `crop` | | [Straighten](./tools/straighten) | Turns a photo taken at an angle into a flat page | `perspective` | | [Rotate left](./tools/rotate-and-flip) | Turns the image a quarter turn to the left | `rotate` | | [Flip](./tools/rotate-and-flip) | Mirrors the image left to right | `flip` | | [Adjust](./tools/adjust) | Changes the brightness and the contrast | `adjust` | | [Clean up](./tools/clean-up) | Turns the document gray, or into crisp black and white without shadows | `finish` | | [Redact](./tools/redact) | Covers an area with solid black or white | `redact` | The [`tools`](../reference/options#tools) option chooses which ones the edit bar offers: :::tabs key:framework \== JavaScript ```ts const pic = new PaperPic(container, { src: '/receipt.jpg', tools: ['crop', 'perspective', 'rotate'], }) ``` \== Vue ```vue ``` \== React ```tsx import type { ToolId } from '@paperpic/react' import { PaperPic } from '@paperpic/react' const tools: ToolId[] = ['crop', 'perspective', 'rotate'] export function Receipt() { return } ``` ::: Crop, Straighten, Redact, Adjust and Clean up open a panel in place of the tools. While one of them is open, the other tools, Undo, Redo and Apply wait. Done, or `Enter`, adds what the tool chose to the edits, and Cancel this tool, or `Esc`, discards it. Inside a panel, the image looks as the result will, Clean up included. Straighten is the exception: it shows the photo without black and white, so the edges of the paper stay visible. ## Preview and Apply While editing, the viewer previews the edits on a copy of the image of about 2 megapixels, so it stays fast with large photos. Zoomed in, the preview looks softer than the result. Apply computes every edit at full resolution, or at [`maxOutputSize`](../reference/options#maxoutputsize), in a Web Worker. Apply cannot be interrupted. It blocks the controls and shows a message while it runs. Then the result replaces the image on display, the history empties, and the viewer goes back to the view mode. If Apply fails, the edit stays open, so the user can try again. ## What your code receives | Event | When | | -------- | ---------------------------------------------------------------------- | | `apply` | When the result is ready, with `{ blob, width, height, type }` | | `change` | Each time the user or a method changes the [state](../reference/state) | | `error` | When the image cannot be loaded, or an edit cannot be shown or applied | :::tabs key:framework \== JavaScript ```ts pic.on('apply', ({ blob }) => upload(blob)) pic.on('error', ({ error }) => console.error(error)) ``` \== Vue ```vue ``` \== React ```tsx upload(blob)} onError={({ error }) => console.error(error)} /> ``` ::: ## What discards the edits * Cancel, after the user confirms, or [`cancel()`](../reference/methods#cancel), which does not ask. * A new `src`, or [`reload()`](../reference/methods#reload), while editing. * A change of `editable` while editing. After Apply, passing the same `src` again does nothing, so the result stays on display. [`reload()`](../reference/methods#reload) brings back the original. ## Keyboard With the focus on the viewer, keys undo, redo, confirm and cancel. [Accessibility](./accessibility#keyboard) lists every key. --- --- url: https://paperpic.dev/reference/events.md description: >- The events of PaperPic (load, error, change, apply and download), what each one carries, and how to listen to them in JavaScript, Vue and React. --- # Events Events tell your code what happens in the viewer. Listen to them with [`on()`](./methods#on). In Vue they are component events, such as `@apply`, and in React they are props, such as `onApply`. A listener that throws does not stop the viewer: the page gets the error as any uncaught one, and the other listeners still run. :::tabs key:framework \== JavaScript ```ts pic.on('apply', ({ blob }) => upload(blob)) ``` \== Vue ```vue ``` \== React ```tsx upload(blob)} /> ``` ::: ## `load` * **Payload:** [`Size`](./types#size) The image is loaded and on display. `width` and `height` are its size in pixels. It fires each time a `src` loads, also with [`reload()`](./methods#reload), but not after Apply, whose result comes with [`apply`](#apply). ## `error` * **Payload:** `{ error: Error, phase: 'load' | 'preview' | 'apply' }` Something failed, and `phase` says what: * `'load'`: the image could not be loaded. * `'preview'`: an edit could not be shown, as when the image is too large for the browser. The edit stays open. * `'apply'`: the changes could not be applied. The edit stays open. ## `change` * **Payload:** [`PaperPicState`](./state) The state changed, through the user or through a method, such as by zooming, opening a tool or undoing, or because Straighten [found the document](../guide/tools/straighten#finding-the-document). It carries the whole state, the same that [`getState()`](./methods#getstate) would return at that moment. Apply emits it twice: when it starts, with `busy: true`, and when it ends well, after [`apply`](#apply). These change the state without emitting `change`: * Loading an image, which [`load`](#load) or [`error`](#error) reports. * An Apply that fails, which [`error`](#error) reports. `busy` is `false` again. * `setOptions()` and the props of the components, so two-way bindings do not loop. * A resize of the viewer, which changes `zoom` while a fit is in effect. A pan emits nothing, because the state does not hold the position of the image. [State](./state#in-step) shows how to keep controls of your own in step. ## `apply` * **Payload:** [`ExportedImage`](./types#exportedimage) Apply finished, from the button, `Enter` or [`apply()`](./methods#apply), and the result is already on display. `blob` holds the image in the format `type`, which [`output`](./options#output) chooses. ## `download` * **Payload:** [`PaperPicDownload`](./types#paperpicdownload) The image is about to be saved, from the download button or from [`download()`](./methods#download). `source` is the image on display: the result of the last Apply, or else the `src`. `filename` is the name of the file. Call `preventDefault()` to stop the browser from saving the file, such as to save it another way: ```ts pic.on('download', ({ source, filename, preventDefault }) => { preventDefault() saveToCloud(source, filename) }) ``` --- --- url: https://paperpic.dev/examples/fixed-proportions.md description: >- Complete example where the user picks the type of document, such as a Legal sheet or a passport page, and Straighten gives it its exact proportions. --- # Fixed proportions Straighten estimates the proportions of a document from the photo, and the estimate cannot be exact. When your app knows what the user photographs, such as a Legal form or a passport page, [`aspectRatio`](../reference/options#aspectratio) gives the result its real shape. This example lets the user pick the type of document before straightening it. :::tabs key:framework \== JavaScript ```html
``` ```ts import { PaperPic } from '@paperpic/core' import '@paperpic/core/style.css' const proportions: Record = { legal: 8.5 / 14, passport: 125 / 88, envelope: 220 / 110, other: undefined, } const pic = new PaperPic(document.querySelector('#viewer')!, { src: '/scans/form.jpg', alt: 'Signed form', tools: ['perspective', 'rotate', 'finish'], aspectRatio: proportions.legal, }) document.querySelector('#type')!.addEventListener('change', (event) => { const type = (event.target as HTMLSelectElement).value pic.setOptions({ aspectRatio: proportions[type] }) }) ``` \== Vue ```vue ``` \== React ```tsx import type { ToolId } from '@paperpic/react' import { PaperPic } from '@paperpic/react' import { useState } from 'react' import '@paperpic/react/style.css' const types = [ { name: 'Legal sheet', aspectRatio: 8.5 / 14 }, { name: 'Passport page', aspectRatio: 125 / 88 }, { name: 'DL envelope', aspectRatio: 220 / 110 }, { name: 'Other', aspectRatio: undefined }, ] const tools: ToolId[] = ['perspective', 'rotate', 'finish'] export function Form() { const [index, setIndex] = useState(0) return ( <>
) } ``` ::: ## Notes * Straighten stores the proportions when the user presses Done, so choose the type before straightening. Changing it later affects only the next straightening. * For a document in landscape, swap the numbers, such as `14 / 8.5`. * The proportions apply to the page as it shows on screen. If the photo is sideways, turn it with Rotate left before you use Straighten, or a sheet in portrait comes out squashed. * Leave `aspectRatio` out for documents without a fixed size, such as receipts, and Straighten estimates them. * The panel of Straighten already offers A4, Letter and Card as [paper sizes](../guide/tools/straighten#paper-size), so this example adds other documents. A size the user chooses there wins over `aspectRatio` for that straightening. * [Straighten](../guide/tools/straighten) explains the estimate and how to handle corners that fall outside the photo. --- --- url: https://paperpic.dev/guide/getting-started.md description: >- Install PaperPic for plain JavaScript, Vue or React, show your first document image and get the edited image back. --- # Getting started This page takes you from installing PaperPic to showing an image and getting the edited result back. Choose your framework in any example, and the others on the site follow. To try PaperPic before you install it, open a starter in StackBlitz: [JavaScript](https://stackblitz.com/github/paperpic/paperpic/tree/development/starters/javascript?file=src/main.ts), [Vue](https://stackblitz.com/github/paperpic/paperpic/tree/development/starters/vue?file=src/App.vue), [React](https://stackblitz.com/github/paperpic/paperpic/tree/development/starters/react?file=src/App.tsx) or [Nuxt](https://stackblitz.com/github/paperpic/paperpic/tree/development/starters/nuxt?file=app/app.vue). Each one shows a sample receipt to edit. ## Installation ::::tabs key:framework \== JavaScript ::: code-group ```sh [npm] npm install @paperpic/core ``` ```sh [pnpm] pnpm add @paperpic/core ``` ```sh [yarn] yarn add @paperpic/core ``` ```sh [bun] bun add @paperpic/core ``` ::: \== Vue ::: code-group ```sh [npm] npm install @paperpic/vue ``` ```sh [pnpm] pnpm add @paperpic/vue ``` ```sh [yarn] yarn add @paperpic/vue ``` ```sh [bun] bun add @paperpic/vue ``` ::: `@paperpic/vue` requires Vue 3.5 or newer. In a Nuxt 4 app, install [`@paperpic/nuxt`](../reference/nuxt) instead and add it to the `modules` of `nuxt.config.ts`. It sets up the component and its stylesheet for you, so you can leave out the lines of the Vue examples that import them. \== React ::: code-group ```sh [npm] npm install @paperpic/react ``` ```sh [pnpm] pnpm add @paperpic/react ``` ```sh [yarn] yarn add @paperpic/react ``` ```sh [bun] bun add @paperpic/react ``` ::: `@paperpic/react` requires React 19 or newer. :::: ### Without a bundler {#cdn} The core also loads from a CDN that serves the files of the package as they are, such as jsDelivr. Import `dist/index.js` from a module script, and link `dist/style.css`: ```html
``` Browsers only start a worker from the origin of the page, so with the package on a CDN the editing runs on the main thread: it works, but large photos freeze the page for a moment on Apply. Serve the files from your own origin, or use a bundler, to keep the worker. The Vue and React components need a bundler. ## Show an image The viewer fills its container, so give the container a height. Import the stylesheet once in your app. :::tabs key:framework \== JavaScript ```html
``` ```ts import { PaperPic } from '@paperpic/core' import '@paperpic/core/style.css' const pic = new PaperPic(document.querySelector('#viewer')!, { src: '/receipt.jpg', alt: 'A receipt', }) ``` \== Vue ```vue ``` \== React ```tsx import { PaperPic } from '@paperpic/react' import '@paperpic/react/style.css' export function Receipt() { return (
) } ``` ::: `src` takes a URL from the same origin as your page, a `File` that the user picks, such as from an ``, or a `Blob`. `alt` describes the image for screen readers. [Loading images](./loading) covers images from other origins, formats and load errors. ## Get the edited image The pencil in the toolbar starts the edit mode. When the user applies the changes, the result replaces the image on display, and the `apply` event hands it to your code: :::tabs key:framework \== JavaScript ```ts pic.on('apply', ({ blob }) => upload(blob)) ``` \== Vue ```vue ``` \== React ```tsx upload(blob)} /> ``` ::: Here `upload` stands for your own code, such as: ```ts async function upload(blob: Blob) { const body = new FormData() body.append('image', blob) await fetch('/api/documents', { method: 'POST', body }) } ``` The `blob` keeps the format of the source when it is JPEG, PNG or WebP, and is PNG when the user cleaned up the document into black and white. [Format and quality](./saving#format) explains how PaperPic tells the format, and the [`output`](../reference/options#output) option changes it. ## Remove the viewer {#destroy} The Vue and React components create the viewer when they mount and destroy it when they unmount. With the core, call [`destroy()`](../reference/methods#destroy) when you take the viewer out of the page, such as when the route changes: ```ts pic.destroy() ``` It removes the viewer from its container, stops its listeners and its worker, and frees the memory of the image. To show it again, create a new one. ## Only show the image To show a document that people should not change, turn editing off with `editable: false`. The [Viewer](./viewer) page shows it at work. ## Requirements PaperPic works in the browsers of [Baseline Widely Available](https://web.dev/baseline). [Performance and support](./performance) covers the worker, Content Security Policy, server-side rendering and large photos. ## Next steps * [Loading images](./loading): where the image comes from, and which formats open. * [Viewer](./viewer): zoom, fit and read-only use. * [Editing](./editing): the edit mode, the tools, Undo and Apply. * [Options](../reference/options): everything you can configure. * [Troubleshooting](./troubleshooting): when the viewer does not look or work as it should. --- --- url: https://paperpic.dev/reference/labels.md description: >- Every text of the PaperPic interface, with its key and its English default, to translate the component or change its wording. --- # Labels Labels are the texts that the component shows, and the ones it announces to screen readers. They are in English by default. Pass the ones you want to change to the [`labels`](./options#labels) option, and the others keep their English text. ```ts const pic = new PaperPic(container, { src: '/receipt.jpg', labels: { apply: 'Aplicar', cancel: 'Cancelar', zoomLevel: percent => `Zoom ${percent} %`, }, }) ``` Five labels are functions, because their text includes a value. A function is new each time it is created, and the viewer takes a new one as a change, so create the labels that hold functions once, and not on every render. | Key | English | Use | | ------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | `adjust` | Adjust | The button that opens the ruler of brightness and contrast | | `adjustmentLevel` | Brightness +30 | Function of the name and the value from -100 to 100, announced after moving the ruler of Adjust | | `adjustUnavailable` | Not available in black and white | The description of Adjust in black and white, which keeps it disabled | | `applied` | Changes applied | Announced when the changes are applied | | `apply` | Apply | The button that applies the changes | | `applyError` | The changes could not be applied | Shown when Apply fails | | `brightness` | Brightness | The choice of brightness in Adjust, and the name of its ruler | | `cancel` | Cancel | The button that leaves the edit mode | | `cancelTool` | Cancel this tool | The button that closes a tool and discards its changes | | `confirm` | Done | The button that closes a tool and keeps its changes | | `contrast` | Contrast | The choice of contrast in Adjust, and the name of its ruler | | `cornerBottomLeft` | Bottom left corner | The name of a corner handle | | `cornerBottomRight` | Bottom right corner | The name of a corner handle | | `cornerKeys` | Arrow keys move it, 10 times further with Shift. Enter finishes. | The description of a corner handle: what the keys do, and that Enter finishes | | `cornerMoved` | Top left corner: 120, 80 | Function of the corner and its position in pixels of the image, announced after moving a corner | | `cornerSelected` | Top left corner: tap where it goes | Function of the corner, shown and announced after pressing a corner handle, until a tap on the image moves it | | `cornerTopLeft` | Top left corner | The name of a corner handle | | `cornerTopRight` | Top right corner | The name of a corner handle | | `crop` | Crop | The Crop button | | `cropHint` | Drag the corners | What to do in Crop | | `discard` | Discard | The button that confirms losing the changes | | `discardQuestion` | Discard your changes? | The question before losing the changes | | `download` | Download | The download button | | `edit` | Edit | The button that starts editing | | `editBar` | Editing controls | The name of the edit bar, for screen readers | | `editing` | Editing | Announced when the edit mode starts | | `finish` | Clean up | The Clean up button, and the name of its choice of finish | | `finishGray` | Gray | Chooses gray in Clean up | | `finishLevel` | Sensitivity 50% | Function of the percent, announced after moving the ruler of Clean up | | `finishMono` | Black and white | Chooses black and white in Clean up | | `finishOriginal` | Original | Chooses the original tones in Clean up, which turns it off | | `finishSensitivity` | Sensitivity | The name of the ruler of Clean up | | `fitHeight` | Fit to height | The button that fits the height of the image | | `fitWidth` | Fit to width | The button that fits the width of the image | | `flip` | Flip | The Flip button | | `inUse` | In use | The description of Adjust or Clean up while its setting is in effect, which a dot shows | | `keepEditing` | Keep editing | The button that goes back to editing instead of losing the changes | | `loadError` | The image could not be loaded | Shown when the image fails to load | | `loading` | Loading image | Shown while the image loads | | `paper` | Paper size | The name of the choice of paper size, in Straighten | | `paperA4` | A4 | Chooses A4 in Straighten | | `paperAuto` | Auto | Chooses the automatic proportions in Straighten | | `paperCard` | Card | Chooses the size of an ID or a bank card in Straighten | | `paperLetter` | Letter | Chooses US Letter in Straighten | | `perspective` | Straighten | The Straighten button | | `perspectiveFound` | Document found. Check its corners | Shown and announced when Straighten finds the document | | `perspectiveHint` | Drag each corner to a corner of the document | What to do in Straighten | | `previewError` | The changes could not be shown | Shown when an edit cannot be shown | | `processing` | Applying changes | Shown while Apply runs | | `redact` | Redact | The Redact button, and the name of its choice of color | | `redactAngle` | Angle 12° | Function of the angle in degrees, announced after turning the area of Redact | | `redactArea` | Area | The area of Redact, which moves it as a whole | | `redactBlack` | Black | Chooses black in Redact | | `redactHint` | Draw an area over what to hide | What to do in Redact | | `redactTurn` | Turn | The handle that turns the area of Redact | | `redactTurnKeys` | Arrow keys turn it 1 degree, or 10 with Shift. Enter finishes. | The description of the handle that turns the area: what the keys do, and that Enter finishes | | `redactWhite` | White | Chooses white in Redact | | `redo` | Redo | The Redo button | | `rotateLeft` | Rotate left | The rotate button of the edit bar, and one of the two of a read-only viewer | | `rotateRight` | Rotate right | The other rotate button of a read-only viewer | | `toolbar` | Image controls | The name of the toolbar, for screen readers | | `undo` | Undo | The Undo button | | `viewer` | Image viewer | The name of the area that shows the image, for screen readers | | `zoomIn` | Zoom in | The zoom in button, in the toolbar and in the panels of Crop and Straighten | | `zoomLevel` | Zoom 150% | Function of the percent, announced after zooming from the toolbar or the keyboard | | `zoomOut` | Zoom out | The zoom out button, in the toolbar and in the panels of Crop and Straighten | --- --- url: https://paperpic.dev/guide/loading.md description: >- How to give PaperPic an image from a URL, a picked file or a Blob, which formats it opens, and how your code learns that it loaded or failed. --- # Loading images PaperPic shows the image that you pass in `src`. This page covers where that image can come from, which formats open, and how your code learns that the image is ready or that it failed. ## Where the image comes from `src` takes one of three things: * **A URL from the same origin as your page**, such as `/documents/42.jpg`. * **A `File`** that the user picks with ``. [Attach and scan](../examples/attach-and-scan) shows the whole flow, from the camera to the upload. * **A `Blob`** that your code holds, such as the body of a response. For a `File` or a `Blob`, PaperPic creates the `blob:` URL it needs, and frees it when the image changes or the viewer is destroyed. ## Images from another origin, or behind a login {#fetch} PaperPic reads the pixels of the image to edit it. Browsers only allow that for an image from another origin when it arrives with CORS, which PaperPic does not request. Such an image shows, but editing it fails: an [`error`](../reference/events#error) says so as soon as an edit needs its pixels, or on Apply. Fetch the image yourself, and pass the `Blob` as `src`. This also covers images behind a login, because your request carries the cookies of the user: ```ts async function fetchImage(url: string): Promise { const response = await fetch(url, { credentials: 'include' }) if (!response.ok) { throw new Error(`The image could not be fetched: status ${response.status}`) } return response.blob() } ``` The other server must allow your origin with CORS, as for any `fetch` from the page. ## Formats {#formats} PaperPic opens every format that the browser shows in an ``: * **JPEG, PNG, WebP and AVIF** open in every [supported browser](./performance#browser-support). * **SVG** opens when the file has `width` and `height` attributes. Without them, it has no size, and the load fails. * **HEIC**, the format of iPhone photos, only opens in Safari. When an iPhone user picks a photo with ``, iOS usually hands the page a JPEG copy. A HEIC file that reaches another browser in another way fails to load. Phones often save a photo sideways, with an EXIF tag that says how to turn it. PaperPic shows the photo the way the tag says, as an `` does, and the result of Apply comes out upright. ## Know when it loads or fails The [`load`](../reference/events#load) event reports that the image is on display, with its size. If the image cannot load, because it is missing, it is not an image or the browser cannot decode it, the viewer shows a message, and the [`error`](../reference/events#error) event carries `phase: 'load'`: :::tabs key:framework \== JavaScript ```ts import { PaperPic } from '@paperpic/core' const pic = new PaperPic(container, { src: '/documents/42.jpg', alt: 'Invoice 42' }) pic.on('load', ({ width, height }) => { console.log(`The image is ${width}×${height} pixels`) }) pic.on('error', ({ error, phase }) => { if (phase === 'load') { console.error(error.message) } }) ``` \== Vue ```vue ``` \== React ```tsx import type { PaperPicEvents } from '@paperpic/react' import { PaperPic } from '@paperpic/react' function loaded({ width, height }: PaperPicEvents['load']) { console.log(`The image is ${width}×${height} pixels`) } function failed({ error, phase }: PaperPicEvents['error']) { if (phase === 'load') { console.error(error.message) } } export function Invoice() { return (
) } ``` ::: `load` fires each time a `src` loads, also with [`reload()`](../reference/methods#reload), but not after Apply: the result arrives with the [`apply`](../reference/events#apply) event. The `status` of [`getState()`](../reference/state) gives the same answer at any time: `'empty'`, `'loading'`, `'ready'` or `'error'`. ## Change or reload the image * **A new `src`** loads the new image. While the user is editing, it discards the edits. * **The same `src`** does nothing, so the result of Apply stays on display. * **[`reload()`](../reference/methods#reload)** loads the current `src` again, which brings back the original after an Apply. While the user is editing, it discards the edits too. --- --- url: https://paperpic.dev/reference/methods.md description: >- Every method of the PaperPic class, to control the viewer from your own code, such as zoom, fit, rotate, edit, apply, download and reload. --- # Methods The methods control the viewer from your own code, such as from buttons of your own with [`toolbar: false`](./options#toolbar). With the core, call them on the `PaperPic` you create. In Vue, the component exposes the viewer as `instance`, and in React, `ref` receives it. Both are `null` until the component mounts: :::tabs key:framework \== JavaScript ```ts import { PaperPic } from '@paperpic/core' const pic = new PaperPic(container, { src: '/receipt.jpg' }) pic.zoomIn() ``` \== Vue ```vue ``` \== React ```tsx import type { PaperPicInstance } from '@paperpic/react' import { PaperPic } from '@paperpic/react' import { useRef } from 'react' export function Receipt() { const picRef = useRef(null) return ( <>
) } ``` ::: In Vue and React, the component creates and destroys the viewer, and takes the options as props and the events as events of its own. So do not call [`new PaperPic()`](#new-paperpic), [`destroy()`](#destroy), [`setOptions()`](#setoptions) or [`on()`](#on) there. ## Create and destroy ### `new PaperPic()` ```ts class PaperPic { constructor(container: HTMLElement, options?: PaperPicOptions) } ``` Creates the viewer inside `container`, which it fills. Give the container a height, or the viewer stays at its minimum height. [Options](./options) lists what `options` takes. It throws a `TypeError` if `container` is not an element. Create the viewer once the element exists, such as on mount. It throws a `RangeError` if an option is out of its range. Only with the core: the Vue and React components create the viewer when they mount. ### `destroy()` ```ts function destroy(): void ``` Removes the viewer and releases everything it holds, such as its worker and the memory of its images. Calling it twice is safe. Only with the core: the Vue and React components call it when they unmount. Called on their viewer, it would leave the component empty. ## Options and state ### `setOptions()` ```ts function setOptions(options: PaperPicOptions): void ``` Changes the options you pass and keeps the others. `undefined` brings an option back to its default. It never emits `change`, so two-way bindings do not loop. It throws a `RangeError` if an option is out of its range, and then no option changes. In Vue and React, change the props instead. The next change of any prop sends every option again, which would undo a change made with `setOptions()`. ### `getState()` ```ts function getState(): PaperPicState ``` Returns the current state of the viewer, such as the zoom, the mode and whether there are changes to apply. To hear of each change instead of asking, listen to [`change`](./events#change). [State](./state) describes every field, and how the two fit together. ### `on()` ```ts function on(name: Name, listener: (payload: PaperPicEvents[Name]) => void): () => void ``` Listens to an event, and returns a function that stops listening. [Events](./events) describes each event. ```ts const off = pic.on('apply', ({ blob }) => upload(blob)) off() ``` In Vue and React, listen to the events of the component instead, such as `@apply` or `onApply`. ## View ### `zoomIn()` ```ts function zoomIn(): void ``` Zooms in one step, around the center of the viewer. ### `zoomOut()` ```ts function zoomOut(): void ``` Zooms out one step, around the center of the viewer. ### `zoomTo()` ```ts function zoomTo(zoom: number, point?: ViewPoint): void ``` Sets the zoom, where `1` shows one pixel of the image per screen pixel. [`point`](./types#viewpoint) stays in place: it is in CSS pixels from the top left corner of the viewer, and its center by default. The zoom goes from the fit of the whole image, or `1` if that is smaller, up to `8`. A value out of range is clamped. It throws a `RangeError` if `zoom` is `NaN` or a coordinate of `point` is not a finite number, and then the zoom does not change. ### `fit()` ```ts function fit(fit: Fit): void ``` Fits the whole image, its width or its height to the viewer. `fit` is a [`Fit`](./types#fit): `'image'`, `'width'` or `'height'`. ## Editing ### `edit()` ```ts function edit(): void ``` Starts editing. It does nothing if the image is not ready or [`editable`](./options#editable) is `false`. ### `rotate()` ```ts function rotate(direction?: 1 | -1): void ``` Turns the image a quarter turn: clockwise with `1`, the default, and counterclockwise with `-1`. While editing, it adds an edit that [`apply()`](#apply) makes permanent, and it does nothing while a tool is open or Apply runs. In a read-only viewer, it only changes the display. Otherwise, it does nothing. ### `flip()` ```ts function flip(): void ``` Mirrors the image left to right as it is on display, so after a quarter turn it still mirrors left to right. To mirror it top to bottom, flip it and rotate it twice. It is an edit, and it does nothing outside the edit mode or while a tool is open. ### `openTool()` ```ts function openTool(id: ToolId): void ``` Opens a tool with a panel: Crop (`'crop'`), Straighten (`'perspective'`), Adjust (`'adjust'`) or Clean up (`'finish'`), which chooses black and white as it opens when the finish is the original. The tool stays open until [`confirmTool()`](#confirmtool) or [`cancelTool()`](#canceltool). Meanwhile, no other edit can start, and Undo, Redo and Apply do nothing. It does nothing outside the edit mode, while another tool is open, for Adjust in black and white, and for Crop and Straighten while a preview is on its way. Straighten looks for the document as it opens, and places its corners on it [if it finds one](../guide/tools/straighten#finding-the-document). Redact (`'redact'`) opens with corners too, as Crop does. ### `confirmTool()` ```ts function confirmTool(): void ``` Closes the open tool and adds what it chose to the edits, as `Enter` does: the selection of Crop or Straighten, or the settings of Adjust or Clean up, as one edit. In Straighten it does nothing until the viewer finds the document or a corner moves, and the `canConfirm` of the [state](./state) says when it can. ### `cancelTool()` ```ts function cancelTool(): void ``` Closes the open tool and discards its changes, as `Esc` does. ### `setFinish()` ```ts function setFinish(setting: { mode?: FinishMode, sensitivity?: number }): void ``` Chooses the finish of [Clean up](../guide/tools/clean-up): `'original'`, `'gray'` or `'mono'` for black and white. It also changes the sensitivity of black and white, from 0 to 1. The finish always runs after the other edits. While Clean up is open, it changes what Clean up shows, and [`confirmTool()`](#confirmtool) keeps it as one edit. It does nothing outside the edit mode or while another tool is open. It throws a `RangeError` if `mode` is not a [`FinishMode`](./types#finishmode), or if `sensitivity` is not between 0 and 1. ### `setAdjustments()` ```ts function setAdjustments(setting: { brightness?: number, contrast?: number }): void ``` Changes the brightness or the contrast, each from -1 to 1, where 0 leaves the image as it is. They run after the other edits, and before gray. While Adjust is open, it changes what Adjust shows, and [`confirmTool()`](#confirmtool) keeps it as one edit. It does nothing outside the edit mode, while another tool is open or in black and white: black and white compares each pixel with its surroundings, so brightness and contrast would barely change its result. It throws a `RangeError` if a value is not between -1 and 1. ### `setPaper()` ```ts function setPaper(setting: { size?: PaperSize }): void ``` Chooses the paper that gives its proportions to the result of [Straighten](../guide/tools/straighten#paper-size): `'a4'`, `'letter'`, `'card'` for an ID or a bank card, or `'auto'`, the default, which takes [`aspectRatio`](./options#aspectratio) or else an estimate. The paper stands or lies as the corners do. It does nothing while Straighten is not open, and each Straighten starts in `'auto'`. It throws a `RangeError` if `size` is not a [`PaperSize`](./types#papersize). ### `setRedaction()` ```ts function setRedaction(setting: { color?: RedactColor }): void ``` Chooses the color that [Redact](../guide/tools/redact) covers with: `'black'`, the default, or `'white'`. While Redact is open, it changes the area on display, and [`confirmTool()`](#confirmtool) keeps it. Otherwise it is the color of the next area. It works in any mode. It throws a `RangeError` if `color` is not a [`RedactColor`](./types#redactcolor). ### `undo()` ```ts function undo(): void ``` Undoes the last edit. It does nothing outside the edit mode, while a tool is open or while Apply runs. ### `redo()` ```ts function redo(): void ``` Brings back the last edit undone. It does nothing outside the edit mode, while a tool is open or while Apply runs. ### `apply()` ```ts function apply(): Promise ``` Applies the edits at full resolution, or at [`maxOutputSize`](./options#maxoutputsize). The result becomes the image on display, the history empties, the viewer goes back to the view mode, and the [`apply`](./events#apply) event carries the result. Apply cannot be interrupted, and it blocks the controls while it runs. It does nothing outside the edit mode, while a tool is open, or when there is nothing to apply. If it fails, the [`error`](./events#error) event reports it and the edit stays open. The promise resolves when Apply ends, also when it fails, so listen to `error` instead of catching it. ### `cancel()` ```ts function cancel(): void ``` Discards the edits and goes back to the view mode. It does not ask first: the built-in Cancel button and `Esc` do. It does nothing while Apply runs. ## Image ### `download()` ```ts function download(): void ``` Saves the image on display as a file: the result of the last Apply, or else the source. It works without the [`download`](./options#download) option, which only shows a button. The [`download`](./events#download) event comes first and can stop it. It does nothing while editing, because the edits are not applied yet. Before the first Apply, a `src` from another origin opens in the browser instead: see [Saving the result](../guide/saving#download). ### `reload()` ```ts function reload(): void ``` Loads the current [`src`](./options#src) again, which brings back the original after an Apply. While editing, it discards the edits. Without a `src`, it does nothing. --- --- url: https://paperpic.dev/reference/nuxt.md description: >- How the PaperPic module for Nuxt 4 sets up the Vue component and its stylesheet, so your templates use the viewer without importing anything. --- # Nuxt `@paperpic/nuxt` is the module for Nuxt 4. It registers the `PaperPic` component of [`@paperpic/vue`](./vue) and adds its stylesheet to your app, so your templates can use the viewer without importing anything. ## Installation ::: code-group ```sh [npm] npm install @paperpic/nuxt ``` ```sh [pnpm] pnpm add @paperpic/nuxt ``` ```sh [yarn] yarn add @paperpic/nuxt ``` ```sh [bun] bun add @paperpic/nuxt ``` ::: Then add the module to `nuxt.config.ts`: ```ts export default defineNuxtConfig({ modules: ['@paperpic/nuxt'], }) ``` `@paperpic/vue` comes with the module, so you do not need to install it yourself. ## Usage ```vue ``` The component fills its parent element, so give the parent a height. It is the same component that `@paperpic/vue` exports, so the [Vue](./vue) page describes its props, events and methods. The Vue examples in these docs work in Nuxt too. Leave out the lines that import the component and `style.css` from `@paperpic/vue`, and import the types from `@paperpic/nuxt` instead. Tests change a little too, as the [Testing](../guide/testing#nuxt) page shows. ## Lazy loading {#lazy} Nuxt also registers the component as ``, which downloads the code of the viewer only when it first renders, for example when the user opens a dialog. A page that does not show the viewer right away then loads less code. The stylesheet is part of the app, so it is already there when the viewer appears. ## Types {#types} `@paperpic/nuxt` exports every type of `@paperpic/vue`, so import your types from it, such as `import type { PaperPicInstance } from '@paperpic/nuxt'`. The [Types](./types) page shows what each one holds. ## Server-side rendering The component renders an empty element on the server and creates the viewer in the browser when it mounts, so you do not need to wrap it in ``. ## Options The module has no options of its own yet. You set up each viewer with the props of the component, as in Vue. --- --- url: https://paperpic.dev/reference/options.md description: >- Every option of PaperPic, with its type, its default and what it changes, for the constructor, setOptions() and the props of the Vue and React components. --- # Options Options set what the viewer shows and what the user can do with it. Pass them when you create the viewer, or change them later with [`setOptions()`](./methods#setoptions). The Vue and React components take them as props with the same names. ```ts const pic = new PaperPic(container, { src: '/receipt.jpg', alt: 'A receipt' }) pic.setOptions({ editable: false }) ``` `setOptions()` changes only the options you pass, and `undefined` brings an option back to its default. It never emits `change`. An option out of its range throws a `RangeError` that names it, such as a `softness` of 2. ## Image ### `src` * **Type:** [`PaperPicSource`](./types#paperpicsource) * **Default:** none The image to show: a URL, or a `File` or a `Blob`. An image from another origin shows, but cannot be edited: [Loading images](../guide/loading#fetch) explains why, and what to do. Passing the same value again does not reload the image, so the result of an edit stays on display. Call [`reload()`](./methods#reload) to bring back the original. A new value while editing discards the edits. ### `alt` * **Type:** `string` * **Default:** `''` Describes the image for screen readers. Without it, screen readers skip the image, as they skip an `` with an empty `alt`. ## Interface ### `editable` * **Type:** `boolean` * **Default:** `true` Whether the user can edit the image. With `false`, it is a read-only viewer, and its toolbar adds buttons to rotate the image. That rotation only changes the display. Changing this option while editing discards the edits. ### `toolbar` * **Type:** `boolean` * **Default:** `true` Whether to show the built-in toolbar and edit bar. Without them, build your own controls with the [methods](./methods). ### `tools` * **Type:** [`readonly ToolId[]`](./types#toolid) * **Default:** every tool The tools the edit bar offers. They keep the order of this table, whatever the order of the array. It only chooses the buttons: the [methods](./methods) work with every tool. | Id | Button | | --------------- | ----------------------------------- | | `'crop'` | Crop | | `'perspective'` | Straighten | | `'rotate'` | Rotate left | | `'flip'` | Flip | | `'adjust'` | Adjust, for brightness and contrast | | `'finish'` | Clean up | | `'redact'` | Redact | ### `wheelZoom` * **Type:** `boolean` * **Default:** `true` Whether the wheel zooms the image. Turn it off when the viewer sits in a long page, so the wheel scrolls the page. A pinch on a trackpad stops zooming the image too, because the browser reports it as the wheel. ### `download` * **Type:** `boolean` * **Default:** `false` Whether the toolbar has a button that saves the image on display: the result of the last Apply, or else the source. The button is hidden while editing. The [`download`](./events#download) event lets you save the file another way. Before the first Apply, a `src` from another origin opens in the browser instead of saving: [Saving the result](../guide/saving#download) explains what to do. ### `labels` * **Type:** [`Partial`](./types#paperpiclabels) * **Default:** the English texts Replaces any of the texts that the component shows or announces. [Labels](./labels) lists every key. ### `icons` * **Type:** [`Partial`](./types#paperpicicons) * **Default:** the built-in icons Replaces any of the icons with your own markup of one element, such as an ``. The markup goes into the page as HTML, so pass only markup you trust. An empty string leaves the buttons of that icon without one. [Styling](../guide/styling#icons) shows an example. Each key names an icon, and some icons appear on two buttons: | Key | Button | | ---------------- | -------------------------------------------------- | | `adjust` | Adjust | | `apply` | Apply, and Done in every tool | | `brightness` | Brightness, in the panel of Adjust | | `cancel` | Cancel, and Cancel this tool | | `contrast` | Contrast, in the panel of Adjust | | `crop` | Crop | | `download` | Download | | `edit` | Edit | | `finish` | Clean up | | `fitHeight` | Fit to height | | `fitWidth` | Fit to width | | `flip` | Flip | | `perspective` | Straighten | | `redact` | Redact | | `redo` | Redo | | `rotateDocument` | Rotate left, in the edit bar | | `rotateLeft` | Rotate left, in the toolbar of a read-only viewer | | `rotateRight` | Rotate right, in the toolbar of a read-only viewer | | `undo` | Undo | | `zoomIn` | Zoom in | | `zoomOut` | Zoom out | ## Result ### `output` * **Type:** [`PaperPicOutput`](./types#paperpicoutput) * **Default:** the format of the source, or PNG The format of the edited image. `type` is `'image/jpeg'`, `'image/png'` or `'image/webp'`, and `quality` goes from 0 to 1 for JPEG and WebP, with `0.92` by default. Without a `type`, an image in black and white is PNG, because JPEG would damage its sharp edges. Any other image keeps the format of the source when it is JPEG, PNG or WebP, which PaperPic reads from the extension of the URL or the type of the `File` or `Blob`. Otherwise, the result is PNG, as it is when the browser cannot encode the format. ### `maxOutputSize` * **Type:** `number` * **Default:** the full resolution The longest side of the edited image, in pixels. A larger result is scaled down. ### `filename` * **Type:** `string` * **Default:** the name of the source The name of the saved file. Give it without an extension: PaperPic adds the one of the format, so a `receipt.jpg` in black and white saves as `receipt.png`. When the source has no name, such as a `Blob`, the file is called `image`. Before the first Apply, a URL without an extension saves without one, because its format is unknown. ## Tools ### `aspectRatio` * **Type:** `number` * **Default:** estimated The real proportions of the document, as width divided by height, such as `210 / 297` for an A4 sheet. Straighten gives its result these proportions. Without them, it estimates them from the photo. Crop does not use them: its rectangle stays free. The user can choose a [paper size](../guide/tools/straighten#paper-size) on the panel of Straighten instead, which wins over this option for that straightening. ### `softness` * **Type:** `number`, from 0 to 1 * **Default:** `0.25` How much gray black and white keeps at the edges of the letters, which makes them easier to read. Use `0` for strict black and white, which gives smaller files but breaks thin strokes. --- --- url: https://paperpic.dev/guide/performance.md description: >- Where PaperPic does its work, what bundlers, CSP and server-side rendering need, how it handles large phone photos, and which browsers it supports. --- # Performance and support Phone photos have 12 megapixels or more, and editing them takes real work. This page explains where that work runs, what your build and your server need, and which browsers PaperPic supports. ## A Web Worker does the work Black and white and Straighten take about a second and a half on a 12-megapixel photo on a recent phone, as the [measured times](#measurements) show. On the main thread, the page would freeze for that long. PaperPic runs them in a Web Worker instead, so the page keeps responding while Apply runs. Straighten also looks for the document there. The worker ships inside the package and starts with the standard `new Worker(new URL(…, import.meta.url))`, which bundlers such as Vite and webpack 5 pick up on their own, with no configuration. If the worker cannot start, the editing runs on the main thread: it still works, but the page can freeze for a moment with large images. ## Content Security Policy With a Content Security Policy, allow: * `worker-src 'self'`, for the worker. * `img-src blob:`, because the viewer shows attached files and the results of Apply through `blob:` URLs. * `paperpic` in `trusted-types`, if your policy restricts Trusted Types policies, because the icons of the buttons go through that policy. * A `default` Trusted Types policy whose `createScriptURL` accepts the URL of the worker, if your policy requires Trusted Types. Bundlers only pick up a worker created from a plain URL, which Trusted Types block, so without that policy the editing runs on the main thread. ## Large photos * **While editing**, the preview works on a copy of about 2 megapixels, so rulers and tools stay fluid with any photo. * **On Apply**, every edit runs at full resolution. Large photos take a few seconds, so the viewer shows a message and blocks the controls meanwhile. * **To save time and memory**, set [`maxOutputSize`](../reference/options#maxoutputsize). A limit such as 2000 or 3000 pixels keeps documents readable, and makes Apply faster and the files smaller. ## Measured times {#measurements} Each step of Apply, in the worker, on a Pixel 10 Pro with Chrome 156: | Step | 2 MP | 12 MP | 37.5 MP | | --------------------------- | ------ | ------ | ------- | | Black and white | 256 ms | 1.5 s | 4.8 s | | Straighten | 251 ms | 1.6 s | 5.0 s | | Export to PNG | 92 ms | 378 ms | 979 ms | | Export to JPEG, quality 0.9 | 33 ms | 142 ms | 525 ms | * A move of the ruler of Clean up takes about 40 ms on the same phone, because it works on the preview of about 2 MP. * A desktop computer with 8 cores does each step about six times faster. * At 37.5 MP, black and white needs about 340 MB of memory at its peak. * Mid-range Android phones and iPhones are not measured yet. ## Server-side rendering PaperPic needs a browser. The Vue and React components render an empty element on the server, such as in Nuxt or Next.js, and create the viewer in the browser. With the core, create the viewer in the browser yourself, such as when your component mounts. ## Browser support PaperPic supports the browsers of [Baseline Widely Available](https://web.dev/baseline): the features that have worked in all the major browsers for at least 30 months. The packages are built for that target, which means Chrome and Edge 124, Firefox 125 and Safari 17.5 or newer, so you do not need to transpile them. --- --- url: https://paperpic.dev/examples/ocr.md description: >- Complete example: straighten a receipt and turn it black and white in PaperPic before your server reads it with OCR or an AI model. --- # Prepare documents for OCR and AI Apps that read receipts and invoices usually send the photo to OCR, such as Tesseract or a cloud service, or to an AI model that reads images. Both do worse with real photos: taken at an angle, with shadows, and with half the table around the paper. OCR skips words, and the model spends its effort on the background. In this example, the user straightens and crops the page first, and the image leaves in black and white. PaperPic doesn't read the text. Your server does, with whatever service you pick, and the photo stays in the browser until your code sends the result. This function sends the image to your server, which reads it and replies with the fields it found: ```ts interface Receipt { date: string merchant: string total: string } async function readReceipt(blob: Blob, type: string): Promise { const body = new FormData() body.append('image', blob, `receipt.${type.split('/')[1]}`) const response = await fetch('/api/receipts/read', { method: 'POST', body }) if (!response.ok) { throw new Error(`Reading failed with status ${response.status}`) } return response.json() } ``` The edit starts in black and white as soon as the photo is on screen, so the user only has to straighten the page and apply the changes: :::tabs key:framework \== JavaScript ```html

``` ```ts import { PaperPic } from '@paperpic/core' import '@paperpic/core/style.css' const input = document.querySelector('#photo')! const status = document.querySelector('#status')! const pic = new PaperPic(document.querySelector('#viewer')!, { alt: 'The receipt you attached', tools: [ 'perspective', 'crop', 'rotate', 'finish', 'redact', ], maxOutputSize: 2000, }) input.addEventListener('change', () => { const file = input.files?.[0] input.value = '' if (file) { status.textContent = '' pic.setOptions({ src: file }) } }) // Black and white is one edit, so the user can still undo it or choose Gray in Clean up pic.on('load', () => { pic.edit() pic.setFinish({ mode: 'mono' }) }) pic.on('apply', async ({ blob, type }) => { status.textContent = 'Reading…' try { const { merchant, total } = await readReceipt(blob, type) status.textContent = `${merchant}: ${total}` } catch { status.textContent = 'The receipt could not be read' } }) ``` \== Vue ```vue ``` \== React ```tsx import type { ExportedImage, PaperPicInstance, ToolId } from '@paperpic/react' import { PaperPic } from '@paperpic/react' import { useRef, useState } from 'react' import '@paperpic/react/style.css' const tools: ToolId[] = [ 'perspective', 'crop', 'rotate', 'finish', 'redact', ] export function ReadReceipt() { const picRef = useRef(null) const [photo, setPhoto] = useState() const [status, setStatus] = useState('') function choose(input: HTMLInputElement) { const file = input.files?.[0] input.value = '' if (file) { setStatus('') setPhoto(file) } } // Black and white is one edit, so the user can still undo it or choose Gray in Clean up function start() { picRef.current?.edit() picRef.current?.setFinish({ mode: 'mono' }) } async function read({ blob, type }: ExportedImage) { setStatus('Reading…') try { const { merchant, total } = await readReceipt(blob, type) setStatus(`${merchant}: ${total}`) } catch { setStatus('The receipt could not be read') } } return ( <> {photo && (
)}

{status}

) } ``` ::: ## Notes * Straighten helps OCR more than anything else: it flattens the page so the lines of text run level, and crops away the table. It finds the paper by itself when it opens, so the user only checks the corners. `tools` leaves out Flip and Adjust, which a receipt rarely needs. * Black and white removes shadows and uneven light, which OCR engines such as Tesseract read as noise, and makes a small PNG. AI models read color, though: for documents with photos, stamps or a highlighted total, leave out `setFinish()` or let the user choose Gray. * AI models shrink large images before they read them, and many charge by size. 2000 pixels on the longest side keeps small print legible and the upload light. Check the limits of your model or OCR service. * If the image goes to an outside service, the user can first cover an account number, a signature or a face with [Redact](../guide/tools/redact). Apply writes those areas into the pixels, so the service never receives what was under them. Always send the result, never the source. * With an AI model, your server can ask for exactly the fields it needs, such as the merchant, the date and the total, as JSON, so its reply already has the shape that `readReceipt` returns. --- --- url: https://paperpic.dev/reference/react.md description: >- How the PaperPic component for React maps the options, events and methods of the core to props, callback props and a ref. --- # React `@paperpic/react` wraps the viewer in a component for React 19 or newer. The options are props, the events are callback props, and the methods are on the viewer that `ref` receives. ```tsx import type { ExportedImage } from '@paperpic/react' import { PaperPic } from '@paperpic/react' import '@paperpic/react/style.css' function upload({ blob }: ExportedImage) { // Send the edited image to your server } export function Receipt() { return (
) } ``` The component fills its parent element, so give the parent a height. ## Props Every [option](./options) is a prop with the same name, such as `editable={false}` or `aspectRatio={210 / 297}`. Two more props style the element that holds the viewer: | Prop | Type | Description | | ----------- | --------------- | --------------------------------- | | `className` | `string` | Classes on top of `paperpic-host` | | `style` | `CSSProperties` | Inline styles | An object or array with the same contents as before, such as `tools={['crop', 'rotate']}`, changes nothing, so inline values are fine. A function is new on every render, so define the functions of `labels`, such as `zoomLevel`, outside the component, or build those labels with `useMemo`. ## Events | Prop | Payload | | ------------ | ---------------------------------------------- | | `onApply` | [`ExportedImage`](./types#exportedimage) | | `onChange` | [`PaperPicState`](./state) | | `onDownload` | [`PaperPicDownload`](./types#paperpicdownload) | | `onError` | `{ error, phase }` | | `onLoad` | [`Size`](./types#size) | [Events](./events) describes each one. A new function does not recreate the viewer, so inline functions are fine. A change of props never calls `onChange`. `onChange` receives the [state](./state) of the viewer, not a DOM event. [State](./state#in-step) shows how to keep it with `useState`, `onChange`, `onLoad` and `onError`. ## Methods {#methods} `ref` receives the viewer, of type [`PaperPicInstance`](./types#paperpicinstance), with the [methods](./methods), such as `zoomIn()` or `apply()`. It is `null` until the component mounts: ```tsx import type { PaperPicInstance } from '@paperpic/react' import { PaperPic } from '@paperpic/react' import { useRef } from 'react' export function Viewer({ src }: { src: string }) { const picRef = useRef(null) return ( <>
) } ``` The component creates the viewer when it mounts and destroys it when it unmounts, so do not call `destroy()`. Change the props instead of calling `setOptions()`, which the next change of a prop would undo, and use the callback props instead of `on()`. Passing the same `src` again does not reload the image, so it keeps the result of an edit. To bring back the original, call `picRef.current.reload()`. ## Types {#types} `@paperpic/react` exports every type of `@paperpic/core`, so you do not need to install it: [Types](./types) shows each one. It also exports the types of the component: [`PaperPicProps`](./types#paperpicprops), with its props, and [`PaperPicInstance`](./types#paperpicinstance), the viewer that `ref` receives. ## Server-side rendering The component is marked with `'use client'`. With server-side rendering, such as in Next.js, it renders an empty element on the server and creates the viewer in the browser. --- --- url: https://paperpic.dev/examples/read-only.md description: >- A complete example of a read-only PaperPic viewer for the attachments of a record, with a list of documents, rotation and a download button. --- # Read-only viewer Some documents should be read but not changed, such as the attachments of an order or a claim. This example shows them one at a time in a read-only viewer, with a list to switch between them and a button to download them. :::tabs key:framework \== JavaScript ```html
``` ```ts import { PaperPic } from '@paperpic/core' import '@paperpic/core/style.css' const documents = [ { src: '/orders/42/invoice.jpg', alt: 'Invoice' }, { src: '/orders/42/delivery-note.jpg', alt: 'Delivery note' }, ] const pic = new PaperPic(document.querySelector('#viewer')!, { ...documents[0], editable: false, download: true, wheelZoom: false, }) document.querySelector('#documents')!.addEventListener('change', (event) => { const index = Number((event.target as HTMLSelectElement).value) pic.setOptions(documents[index]!) }) ``` \== Vue ```vue ``` \== React ```tsx import { PaperPic } from '@paperpic/react' import { useState } from 'react' import '@paperpic/react/style.css' const documents = [ { src: '/orders/42/invoice.jpg', alt: 'Invoice' }, { src: '/orders/42/delivery-note.jpg', alt: 'Delivery note' }, ] export function Attachments() { const [index, setIndex] = useState(0) const current = documents[index]! return ( <>
) } ``` ::: ## Notes * With `editable: false`, the toolbar has no Edit button, and its rotate buttons only turn the image on display. * `download: true` adds a button that saves the document as it is, with its own file name. The [`download`](../reference/events#download) event lets you serve it from your server instead. * `wheelZoom: false` lets the wheel scroll the page, which suits a viewer inside a longer page. * A new `src` loads the next document and fits it to the viewer. --- --- url: https://paperpic.dev/guide/tools/redact.md description: >- How the Redact tool of PaperPic covers an account number, a signature or any area with solid black or white, so the result no longer holds it. --- # Redact A photo of a document can show more than it should: an account number, a signature, a face in the background. Redact covers a rectangle, level or leaning, with solid black or white, and the result no longer holds what was under it. ## Use it 1. Press Edit, then Redact. A band appears across the middle of the image, with a handle at each corner. 2. Draw the area over what to hide: drag from one corner of it to the opposite one, anywhere on the image, the band included. Then drag the area to move it, turn it by the handle above it, so it leans with a line of text, and drag its corners to resize it. The area shows its color, still see-through, so you can place it over the right words. 3. Choose Black or White in the panel. 4. Press Done, or `Enter`, to add the area to the edits. Cancel this tool, or `Esc`, closes Redact without changing anything. You can only draw until you place the area. Once you draw, move, turn or resize it, a drag on the rest of the image pans again, so nothing replaces the area by accident. Before that, pan a zoomed image with two fingers, or with the arrow keys while the focus is on the image. Without dragging, the band is the area: move it with the keyboard, or press it and then tap where it goes. Each Done adds one area, so open Redact again to cover another part. Undo removes the last area, and the color stays for the next one. The corner handles work as in [Crop](./crop): drag them, press one and then tap where it goes, or move them with the keyboard. On the handle above the area, the arrow keys turn it 1 degree, or 10 with Shift. Dragged, it snaps to level. ## What it guarantees {#guarantees} * The areas are covered after every other edit, so Adjust and Clean up never wash out their black or white. * An area follows the edits after it: a turn, a flip or a crop moves it with the image, and Straighten bends it with the page. * It covers every pixel that its edges touch, even in part, and it is opaque in a transparent PNG too. * Apply writes solid pixels into the result, so the file keeps nothing of what they cover. Until Apply, the viewer keeps the source, so Undo brings back what an area covers. Share the result of Apply, never the source. ## From code Redact is in the edit bar by default, with the id `'redact'` in [`tools`](../../reference/options#tools). With `toolbar: false`, open it with [`openTool()`](../../reference/methods#opentool), choose the color with [`setRedaction()`](../../reference/methods#setredaction), and close it with [`confirmTool()`](../../reference/methods#confirmtool) or [`cancelTool()`](../../reference/methods#canceltool): ```ts pic.edit() pic.openTool('redact') pic.setRedaction({ color: 'white' }) // Later, from a button of your own pic.confirmTool() ``` The `redaction` of the [state](../../reference/state) holds the color in use. --- --- url: https://paperpic.dev/guide/tools/rotate-and-flip.md description: >- How to rotate and flip a document image in PaperPic, in the edit mode, in a read-only viewer and from code. --- # Rotate and flip Phones often save a photo of a document sideways or upside down, and some scans come out mirrored. Rotate left and Flip fix the orientation and leave the rest of the image as it is. ## Rotate In the edit bar, Rotate left turns the image a quarter turn counterclockwise, as in photo galleries. Press it twice for a half turn, or three times for a quarter turn clockwise. A rotation is an edit: Undo removes it, and Apply makes it permanent. Four rotations bring the image back to where it was, and then there is nothing to apply. From code, [`rotate()`](../../reference/methods#rotate) turns clockwise with `1`, and counterclockwise with `-1`: ```ts pic.rotate(1) pic.rotate(-1) ``` ## Flip Flip mirrors the image left to right, as it is on display, so after a quarter turn it still mirrors left to right on the screen. To mirror an image top to bottom, flip it and rotate it twice. Flips and rotations that cancel out leave nothing to apply. From code, call [`flip()`](../../reference/methods#flip). ## In a read-only viewer With [`editable: false`](../viewer#read-only), the toolbar has Rotate left and Rotate right buttons. They only turn the image on display: nothing is saved, and the `apply` event never fires. [`rotate()`](../../reference/methods#rotate) does the same from code. A read-only viewer has no Flip. ## Ids In the [`tools`](../../reference/options#tools) option, Rotate left is `'rotate'` and Flip is `'flip'`. --- --- url: https://paperpic.dev/guide/saving.md description: >- How PaperPic hands over the edited image, how to choose its format and size, how to upload it, and how the download button and its event work. --- # Saving the result PaperPic never uploads or stores anything. When the user applies the edits, it hands the result to your code, and your app decides where it goes. This page covers what you receive and how to save it. ## The `apply` event Apply computes the result and fires [`apply`](../reference/events#apply) with: | Field | Type | Description | | ----------------- | -------- | --------------------------------- | | `blob` | `Blob` | The edited image | | `type` | `string` | Its format, such as `'image/png'` | | `width`, `height` | `number` | Its size in pixels | :::tabs key:framework \== JavaScript ```ts pic.on('apply', ({ blob, type }) => upload(blob, type)) ``` \== Vue ```vue ``` \== React ```tsx upload(blob, type)} /> ``` ::: After Apply, the result is the image on display, the history is empty, and the next edit starts from the result. [`reload()`](../reference/methods#reload) brings back the original `src`. ## Upload it Send the `blob` as a file in a form: ```ts async function upload(blob: Blob, type: string) { const body = new FormData() body.append('image', blob, `document.${type.split('/')[1]}`) const response = await fetch('/api/documents', { method: 'POST', body }) if (!response.ok) { throw new Error(`The upload failed with status ${response.status}`) } } ``` The viewer shows the result at once, whether or not it reaches your server, so tell the user when the upload fails. ## Format and quality {#format} Without options, the result keeps the format of the source when it is JPEG, PNG or WebP. PaperPic reads it from the extension of the URL, such as `.jpg`, or from the type of the `File` or `Blob`. A document in black and white is PNG, because JPEG would add artifacts around its sharp edges. Any other source gives PNG too, such as a GIF, or a URL without an extension like `/api/documents/42`, even when it serves a JPEG. [`output`](../reference/options#output) chooses the format, and its quality from 0 to 1 for JPEG and WebP, with 0.92 by default: :::tabs key:framework \== JavaScript ```ts const pic = new PaperPic(container, { src: '/receipt.jpg', output: { type: 'image/webp', quality: 0.8 }, }) ``` \== Vue ```vue ``` \== React ```tsx const output = { type: 'image/webp', quality: 0.8 } export function Receipt() { return } ``` ::: | Format | Suits | | ------------ | -------------------------------------------------------- | | `image/png` | Documents in black and white, and text, with no loss | | `image/jpeg` | Photos and colored documents, in small files | | `image/webp` | Photos and colored documents, in smaller files than JPEG | A browser that cannot encode the format you ask for gives PNG, so read `type` in the event. ## Size The result keeps the full resolution of the source, which is 12 megapixels or more for many phone photos. [`maxOutputSize`](../reference/options#maxoutputsize) limits its longest side, in pixels: :::tabs key:framework \== JavaScript ```ts const pic = new PaperPic(container, { src: '/receipt.jpg', maxOutputSize: 2000, }) ``` \== Vue ```vue ``` \== React ```tsx ``` ::: The preview while editing has at most about 2 megapixels, so `maxOutputSize` changes only the result. Safari on iOS limits a canvas to about 16 megapixels, and recent iPhones take photos of 24 megapixels or more, so Apply can fail at full resolution. If your users edit photos from an iPhone, set `maxOutputSize`. 3000 pixels keeps documents readable and stays well below the limit. [Apply fails with a large photo](./troubleshooting#too-large) shows the error. ## Metadata {#metadata} The result of Apply carries no metadata. PaperPic draws the image on a canvas, so the EXIF data of the photo, such as the GPS position, the camera and the date, is gone. The download button saves the source as it is until the first Apply, with its metadata. ## The download button {#download} [`download: true`](../reference/options#download) adds a button at the end of the toolbar that saves the image on display: the result of the last Apply, or else the source as it is. It is hidden while editing, because the edits are not applied yet. [`download()`](../reference/methods#download) does the same from code, with or without the button. The browser's context menu does not open over the viewer, so this button is the way to save the image from it. The file keeps the name of the source and takes the extension of its format, so a `receipt.jpg` in black and white saves as `receipt.png`. [`filename`](../reference/options#filename) sets another name. Without any name, such as for a `Blob`, the file is called `image`. Before the first Apply, a URL without an extension saves without one, because its format is unknown. With a `src` from another origin, browsers do not save the file before the first Apply: they open the image instead, and the user leaves your page. Pass the image as a `Blob`, as [Loading images](./loading#fetch) shows, or save it yourself in the `download` event. ### Save it another way The [`download`](../reference/events#download) event comes before the browser saves the file. Call `preventDefault()` to save it another way, such as from your server, which can name the file and check who downloads it: :::tabs key:framework \== JavaScript ```ts pic.on('download', ({ preventDefault }) => { preventDefault() window.location.assign('/api/documents/42/file') }) ``` \== Vue ```vue ``` \== React ```tsx import type { PaperPicDownload } from '@paperpic/react' import { PaperPic } from '@paperpic/react' function download({ preventDefault }: PaperPicDownload) { preventDefault() window.location.assign('/api/documents/42/file') } export function Receipt() { return } ``` ::: --- --- url: https://paperpic.dev/examples/form.md description: >- Complete example where a receipt photo goes in a form field, the user edits it in PaperPic, and the form sends the edited image. JavaScript, Vue and React. --- # Send with a form Some apps send documents with a plain form, such as an expense with its receipt, and have no code of their own to upload a file. This example keeps the photo in the file field of the form, and puts the edited image back in that field when the user applies the changes, so the form sends it as it would any file. :::tabs key:framework \== JavaScript ```html
``` ```ts import { PaperPic } from '@paperpic/core' import '@paperpic/core/style.css' const input = document.querySelector('#receipt')! const pic = new PaperPic(document.querySelector('#viewer')!, { alt: 'The receipt you attached', maxOutputSize: 3000, }) input.addEventListener('change', () => { const file = input.files?.[0] if (file) { pic.setOptions({ src: file }) } }) // The form sends the edited image in place of the photo pic.on('apply', ({ blob, type }) => { const name = input.files?.[0]?.name.replace(/\.\w+$/, '') ?? 'receipt' const files = new DataTransfer() files.items.add(new File([blob], `${name}.${type.split('/')[1]}`, { type })) input.files = files.files }) ``` \== Vue ```vue ``` \== React ```tsx import type { ExportedImage } from '@paperpic/react' import { PaperPic } from '@paperpic/react' import { useRef, useState } from 'react' import '@paperpic/react/style.css' export function ExpenseForm() { const inputRef = useRef(null) const [photo, setPhoto] = useState() // The form sends the edited image in place of the photo function applied({ blob, type }: ExportedImage) { const input = inputRef.current if (!input) { return } const name = input.files?.[0]?.name.replace(/\.\w+$/, '') ?? 'receipt' const files = new DataTransfer() files.items.add(new File([blob], `${name}.${type.split('/')[1]}`, { type })) input.files = files.files } return (
{photo && (
)}
) } ``` ::: ## Notes * Apply puts the edited image in the file field with a [`DataTransfer`](https://developer.mozilla.org/docs/Web/API/DataTransfer), so the form sends it under the same name. Before any Apply, the form sends the photo as the user picked it. * Changing the files of the field from code does not fire its `change` event, so the viewer keeps the result on display. * The file keeps the name of the photo, with the extension of the result, such as `receipt.png` after Clean up in black and white. * The buttons of the viewer never submit the form. * [`maxOutputSize`](../reference/options#maxoutputsize) keeps the form light. Phone photos have 12 megapixels or more, and documents stay readable at 3000 pixels on the longest side. --- --- url: https://paperpic.dev/reference/state.md description: >- What getState() returns and the change event carries, from the image status and mode to the zoom and the edits, and how to sync your own controls with it. --- # State The state is a snapshot of the viewer: whether there is an image, the mode, the zoom, the open tool and whether there are changes to apply. You get it in two ways, and both give the same [`PaperPicState`](./types#paperpicstate) object: * [`getState()`](./methods#getstate) returns it whenever you ask. * The [`change`](./events#change) event sends it each time the user or a method changes it. ## Keeping controls in step {#in-step} `change` does not report the image. A loaded image comes with [`load`](./events#load), and a load or an Apply that fails comes with [`error`](./events#error). To keep controls of your own in step, such as an Apply button, read the state at the start, take it from each `change`, and read it again on `load` and `error`: :::tabs key:framework \== JavaScript ```ts import type { PaperPicState } from '@paperpic/core' import { PaperPic } from '@paperpic/core' import '@paperpic/core/style.css' const applyButton = document.querySelector('#apply')! const pic = new PaperPic(container, { src: '/receipt.jpg', toolbar: false }) function update({ canApply, busy }: PaperPicState) { applyButton.disabled = !canApply || busy } update(pic.getState()) pic.on('change', update) pic.on('load', () => update(pic.getState())) pic.on('error', () => update(pic.getState())) applyButton.addEventListener('click', () => pic.apply()) ``` \== Vue ```vue ``` \== React ```tsx import type { PaperPicInstance, PaperPicState } from '@paperpic/react' import { PaperPic } from '@paperpic/react' import { useRef, useState } from 'react' import '@paperpic/react/style.css' export function Receipt() { const picRef = useRef(null) const [state, setState] = useState() function refresh() { setState(picRef.current?.getState()) } return ( <>
) } ``` ::: In Vue and React the viewer exists only once the component mounts, so the state starts as `undefined` and arrives with the first `load` or `error`. Until then, there is nothing to apply. ## Fields | Field | Type | Description | | ------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `activeTool` | [`ToolId \| null`](./types#toolid) | The open tool, such as `'crop'` or `'adjust'`, or `null` | | `adjustments` | `{ brightness, contrast }` | The brightness and the contrast, each from -1 to 1. They do not apply in black and white. While Adjust is open, they are the values on its panel | | `busy` | `boolean` | Whether Apply is running | | `canApply` | `boolean` | Whether there are changes to apply. Rotations and flips that cancel out are no change | | `canConfirm` | `boolean` | Whether [`confirmTool()`](./methods#confirmtool) can keep what the open tool shows. Straighten waits until it finds the document or a corner moves. It is `false` with no tool open | | `canRedo` | `boolean` | Whether there is an edit to bring back | | `canUndo` | `boolean` | Whether there is an edit to undo | | `finish` | `{ mode, sensitivity }` | The finish of Clean up, a [`FinishMode`](./types#finishmode), and the sensitivity of black and white, from 0 to 1. While Clean up is open, they are the values on its panel | | `fit` | [`Fit \| null`](./types#fit) | The fit in effect, or `null` once the user has zoomed by hand | | `hint` | `string \| null` | What the open tool asks of the user, as the built-in edit bar shows it, such as "Drag the corners", or `null`. With `toolbar: false`, show it in your interface | | `image` | [`Size \| null`](./types#size) | The size of the image in pixels, at full resolution and with the edits so far, but without the turn of `rotation`, or `null` without an image | | `mode` | `'view' \| 'edit'` | Whether the user is viewing or editing the image | | `paper` | `{ size }` | The paper size on the panel of Straighten, a [`PaperSize`](./types#papersize), while it is open, and `'auto'` otherwise | | `redaction` | `{ color }` | The color of Redact, a [`RedactColor`](./types#redactcolor): the one on its panel while it is open, and the one of the next area otherwise | | `rotation` | [`Rotation`](./types#rotation) | How far the image on display is turned from `image`, in degrees clockwise | | `status` | `'empty' \| 'loading' \| 'ready' \| 'error'` | `'empty'` without `src`, `'loading'` while it loads, `'ready'` once it is on display, and `'error'` if it could not be loaded | | `zoom` | `number` | Screen pixels per pixel of the image | With a `rotation` of 90 or 270, the image on screen, and the result of Apply, have the width and the height of `image` swapped. [`maxOutputSize`](./options#maxoutputsize) can make the result smaller. --- --- url: https://paperpic.dev/guide/tools/straighten.md description: >- How the Straighten tool of PaperPic turns a photo taken at an angle into a flat page, how it estimates proportions and when to set aspectRatio. Live demo. --- # Straighten A document photographed at an angle looks like a trapezoid: the far edge is shorter and the text leans. Straighten turns it back into a flat, rectangular page, as if it had been scanned. Its id in the API is `perspective`. ## Use it 1. Press Edit, then Straighten. A handle appears for each corner, on the document if the viewer [finds it](#finding-the-document). 2. Drag each handle that is off onto its corner of the document. Zoom in with the buttons of its panel to place them precisely. 3. If you know the paper, choose its [size](#paper-size): A4, Letter or Card. Auto estimates it. 4. Press Done, or `Enter`. The viewer shows the page flat, cut to the four corners. Done waits until the viewer finds the document or you move a corner. The handles work as in [Crop](./crop): a magnifier on touch screens, press and tap instead of dragging, and Tab and the arrow keys on the keyboard. Here the magnifier also shows while a mouse drags a corner, because each corner must land exactly on one of the paper. The four corners always keep a convex shape, so the page can always be flattened. Straighten shows the photo without the black and white of [Clean up](./clean-up), because the edges of the paper are hard to find on a cleaned up page. Black and white comes back after Done, and gray stays. ## Finding the document {#finding-the-document} As Straighten opens, the viewer looks for the document in the photo and places the four corners on it, so Done is ready at once. The search runs in the browser in a fraction of a second, and it changes nothing until Done. The viewer proposes only what it is sure enough of. If the paper blends into the table, or the photo has no document, the corners start inside the image and wait for the user. A corner that the user has already touched never moves on its own. ## Paper size {#paper-size} The panel of Straighten offers paper sizes, which give the result the exact proportions of that paper: | Choice | Proportions | | ------ | ----------------------------------------------------------------------------------------- | | Auto | [`aspectRatio`](../../reference/options#aspectratio), or else an [estimate](#proportions) | | A4 | 210 × 297 mm, which A3 and A5 share | | Letter | 8.5 × 11 in, US Letter | | Card | 85.6 × 53.98 mm, an ID or a bank card | A size sets only the proportions: it does not move the corners. The paper stands or lies as the corners do, so there is no orientation to choose. A size that is not the one of the document distorts it, so Straighten starts in Auto each time it opens. With the four corners on the corners of the image, Auto changes nothing, and a size gives the whole image the proportions of that paper. ## Proportions {#proportions} A photo does not tell the real shape of the page, so Straighten estimates its proportions from where the corners sit in the photo. The estimate suits photos taken from a normal distance, but it cannot be exact. The estimate uses the original photo, even after a crop or a rotation in the same edit. Once the user applies, the result counts as the new photo, so straighten before applying. When you know the document, set [`aspectRatio`](../../reference/options#aspectratio) to its width divided by its height, and the result takes those proportions: :::tabs key:framework \== JavaScript ```ts const pic = new PaperPic(container, { src: '/invoice.jpg', aspectRatio: 210 / 297, }) ``` \== Vue ```vue ``` \== React ```tsx ``` ::: | Document | `aspectRatio` | | ------------------------- | -------------- | | A4 sheet, portrait | `210 / 297` | | US Letter sheet, portrait | `8.5 / 11` | | ID card, landscape | `85.6 / 53.98` | For a sheet in landscape, swap the numbers, such as `297 / 210`. The proportions apply to the page as it shows on screen, so turn a sideways photo with [Rotate left](./rotate-and-flip) before you straighten it. ## Corners cut off by the photo Sometimes a corner of the document falls outside the photo. The handles stay inside the image, so place that handle on the border of the photo, along the edge of the document that keeps the content. The last rows lean slightly and the estimated proportions suffer, which [`aspectRatio`](../../reference/options#aspectratio) can fix. The [playground](../../playground) has a sample receipt with a cut-off corner to try it. ## From code Straighten opens with [`openTool('perspective')`](../../reference/methods#opentool) and closes with [`confirmTool()`](../../reference/methods#confirmtool) or [`cancelTool()`](../../reference/methods#canceltool): ```ts pic.edit() pic.openTool('perspective') pic.setPaper({ size: 'a4' }) // Later, from a button of your own pic.confirmTool() ``` Choose the paper size with [`setPaper()`](../../reference/methods#setpaper) while the tool is open. `confirmTool()` waits until the viewer finds the document or a corner moves, and the `canConfirm` of the [state](../../reference/state) says when it can. --- --- url: https://paperpic.dev/guide/styling.md description: >- How to fit PaperPic into the look of your app, with its stylesheet, its CSS tokens, dark mode, your own icons and a cascade layer that lets your CSS win. --- # Styling PaperPic should look like part of your app. It ships one stylesheet, takes its colors and corners from a few CSS tokens, follows the color scheme of your page, and keeps its rules in a cascade layer, so your own CSS always wins. ## Import the stylesheet Import it once in your app: :::tabs key:framework \== JavaScript ```ts import '@paperpic/core/style.css' ``` \== Vue ```ts import '@paperpic/vue/style.css' ``` \== React ```ts import '@paperpic/react/style.css' ``` ::: ## Give it a size The viewer fills its container and has no height of its own, so the container needs one. Any CSS that gives it a height works: ```css .document-viewer { height: 70dvh; } ``` The viewer follows the size of its container, not the size of the screen. It reacts when the container changes, such as when a side panel opens. ## Colors and corners Five [CSS tokens](../reference/css-tokens) set the surface, the text, the accent, the corner radius and the length of the transitions. Set them on `:root`, on an ancestor of the viewer or on `.paperpic`: ```css :root { --paperpic-color-accent: #c2410c; --paperpic-radius: 0; } ``` The tokens are inherited, so a class on the container of one viewer, or on the Vue or React component, changes that viewer only: ```css .signature-viewer { --paperpic-color-accent: #15803d; } ``` Three more tokens color what the viewer paints over the photo while Crop or Straighten is open: `--paperpic-color-dim` darkens the image around the selection, and `--paperpic-color-line` and `--paperpic-color-line-shadow` draw the lines and the corner handles. They keep one value on light and dark pages. A line and its shadow go in pairs, so give a dark line a light shadow: ```css :root { --paperpic-color-line: #111; --paperpic-color-line-shadow: rgb(255 255 255 / 70%); } ``` ## Use the colors of your design system {#design-system} If your app keeps its colors in CSS variables, point the tokens at them instead of copying their values. The viewer then follows your theme, dark mode included: ```css .paperpic { --paperpic-color-surface: var(--app-surface); --paperpic-color-text: var(--app-text); --paperpic-color-accent: var(--app-primary); --paperpic-radius: var(--app-radius); } ``` Set them on `.paperpic`, as here. A token that uses `var()` reads the variable on the element where you set it, so on `:root` it would miss a theme that you switch on one part of the page. Any design system with CSS variables works, such as the theme variables of Tailwind CSS 4: `var(--color-blue-600)` or `var(--radius-md)`. ## Dark mode {#dark-mode} The colors follow the `color-scheme` of your page, as the form controls of the browser do: * With `color-scheme: light dark`, they turn dark when the user's system prefers a dark color scheme. * With `color-scheme: dark`, they are always dark. This also works on one part of the page. * Without `color-scheme`, they stay light, so a page without a dark theme keeps a light viewer. If your site follows the system, declare it once: ```css :root { color-scheme: light dark; } ``` If your site switches themes with a class, such as on ``, set `color-scheme` with that class. The scroll bars and form controls of the browser follow it too: ```css :root.dark { color-scheme: dark; } ``` To choose your own dark colors, give a token both values with `light-dark()`: ```css :root { --paperpic-color-accent: light-dark(#c2410c, #fb923c); } ``` Tokens that point at the variables of your [design system](#design-system) follow your theme instead. ## Icons {#icons} The [`icons`](../reference/options#icons) option replaces any icon with your own markup, usually an `` from the icon set of your app: :::tabs key:framework \== JavaScript ```ts import { PaperPic } from '@paperpic/core' import '@paperpic/core/style.css' const pic = new PaperPic(document.querySelector('#viewer')!, { src: '/receipt.jpg', icons: { zoomIn: '', }, }) ``` \== Vue ```vue
``` \== React ```tsx import { PaperPic } from '@paperpic/react' import '@paperpic/react/style.css' const icons = { zoomIn: '', } export function Receipt() { return (
) } ``` ::: * Each key names an icon, and some icons appear on two buttons: `apply` is also on Done, and `cancel` also closes a tool. [Options](../reference/options#icons) lists every key. * PaperPic gives the icon the class `paperpic-icon`, which sets its size, and hides it from screen readers, because the button already has a name. * Draw the icon with `currentColor`, so it takes the color of the button in every theme. * The markup goes into the page as HTML, so pass only markup you trust. * With Vite, `import zoomIn from './zoom-in.svg?raw'` gives you the markup of an `.svg` file. To change every icon at once, such as their size or the width of their lines, style the class: ```css .paperpic-icon { inline-size: 1.125rem; block-size: 1.125rem; stroke-width: 1.5; } ``` ## Your CSS wins The rules of PaperPic live in the `paperpic` cascade layer, and any CSS outside a layer overrides them, whatever its specificity. That makes overrides easy, but a global reset outside a layer, such as a rule on `button`, also reaches the buttons of the viewer. If your reset breaks the viewer, move it into a layer that comes before `paperpic`. The first statement that names the layers fixes their order, so put it in CSS that loads before the stylesheet of PaperPic: ```css @layer reset, paperpic; @layer reset { button { all: unset; } } ``` ## Tailwind CSS {#tailwind} Tailwind CSS 4 keeps its rules in cascade layers too. Name every layer, in order, before you import Tailwind and PaperPic, so the reset of Tailwind comes before `paperpic` and its utilities come after it: :::tabs key:framework \== JavaScript ```css @layer theme, base, paperpic, components, utilities; @import 'tailwindcss'; @import '@paperpic/core/style.css'; ``` \== Vue ```css @layer theme, base, paperpic, components, utilities; @import 'tailwindcss'; @import '@paperpic/vue/style.css'; ``` \== React ```css @layer theme, base, paperpic, components, utilities; @import 'tailwindcss'; @import '@paperpic/react/style.css'; ``` ::: Import the stylesheet of PaperPic here, in your CSS, and not from JavaScript. In another order, the reset of Tailwind removes padding and borders from the viewer, or the viewer overrides utilities such as `h-96` on the component. ## Class names {#class-names} The [CSS reference](../reference/css-tokens#classes) lists the classes you can target, such as `paperpic-toolbar` and `paperpic-button`, and their names stay stable. Other classes hold the layout together and can change in any release. Prefer the tokens when they cover what you need. Every button, ruler and corner handle also carries `data-paperpic-control`, with the key of its [label](../reference/labels). Select it to style one control: ```css .paperpic-button[data-paperpic-control='edit'] { color: var(--paperpic-color-accent); } ``` The root, `.paperpic`, also carries its state in [`data-paperpic-status`, `data-paperpic-mode` and `data-paperpic-tool`](../reference/css-tokens#states), so your CSS can follow the load, the edit mode and the open tool: ```css .paperpic[data-paperpic-mode='edit'] { outline: 2px solid var(--paperpic-color-accent); } ``` ## Layout The interface adapts to its container on its own: * The toolbar sits at the right and scrolls when the viewer is too short for its buttons. It hides while editing. * The edit bar is a card at the bottom with two rows of fixed height, or one row in a viewer at least 38rem wide, so the image keeps its place when a tool opens. * On touch screens, buttons and corner handles grow to at least 44 pixels. ## Your own controls When styling is not enough, hide the built-in toolbar and edit bar with `toolbar: false`, and drive the viewer from controls of your own. [Custom toolbar](../examples/custom-toolbar) shows how. --- --- url: https://paperpic.dev/guide/testing.md description: >- How to test an app that uses PaperPic, with a stand-in in jsdom or happy-dom and the real viewer in a browser with Playwright. JavaScript, Vue and React. --- # Testing Unit tests usually run in jsdom or happy-dom, which imitate a browser inside Node. That is fine for your own code, but not for PaperPic: it decodes images, draws them on a canvas and edits them in a Web Worker, and neither of them has any of that. So split the work. In unit tests, put a stand-in where PaperPic goes and check what your code does with the result. Test the editing itself in a real browser. ## In jsdom and happy-dom {#dom} If you mount the real viewer there anyway, this is what you get: * happy-dom shows the toolbar, but the image never loads: [`getState()`](../reference/methods#getstate) returns `status: 'error'`, and [`error`](../reference/events#error) arrives with `phase: 'load'`. * jsdom fails sooner. It has no `ResizeObserver`, so mounting throws `ReferenceError: ResizeObserver is not defined`. With a stub of `ResizeObserver` you get as far as in happy-dom, and jsdom adds a `Not implemented: HTMLCanvasElement's getContext() method` warning. Either way, no user could ever get to Apply there, so the test sends `apply` itself. ## A stand-in in unit tests {#stand-in} The tests below cover the code of [Upload to a server](../examples/upload): once the user applies the changes, it uploads the image and shows Saved. They run in Vitest with jsdom or happy-dom, and replace `fetch`, so nothing goes over the network. :::tabs key:framework \== JavaScript Move the code of the example into a function that creates the viewer and returns it, such as `showInvoice(viewer, status)` in `show-invoice.ts`. `vi.mock()` swaps PaperPic for a class that only keeps the listeners, so the test can call the one for `apply`: ```ts import { expect, it, vi } from 'vitest' import { showInvoice } from './show-invoice' // The listeners that the code adds, kept so the test can call them const listeners = vi.hoisted(() => new Map unknown>()) vi.mock('@paperpic/core', () => ({ PaperPic: class { on(name: string, listener: (payload: unknown) => unknown) { listeners.set(name, listener) return () => listeners.delete(name) } destroy() {} }, })) it('saves the edited invoice', async () => { const fetch = vi.fn(async () => new Response(null, { status: 204 })) vi.stubGlobal('fetch', fetch) const status = document.createElement('p') showInvoice(document.createElement('div'), status) await listeners.get('apply')?.({ blob: new Blob(['png']), type: 'image/png', width: 1, height: 1, }) expect(fetch).toHaveBeenCalledWith('/api/documents/42', expect.objectContaining({ method: 'PUT' })) expect(status.textContent).toBe('Saved') }) ``` \== Vue With `stubs`, Vue Test Utils renders an empty component where PaperPic would be, and the test emits `apply` from it, as the viewer would: ```ts import { PaperPic } from '@paperpic/vue' import { mount } from '@vue/test-utils' import { expect, it, vi } from 'vitest' import Invoice from './Invoice.vue' it('saves the edited invoice', async () => { const fetch = vi.fn(async () => new Response(null, { status: 204 })) vi.stubGlobal('fetch', fetch) // A stub takes the place of PaperPic, which needs a real browser const wrapper = mount(Invoice, { global: { stubs: { PaperPic: true }, }, }) wrapper.findComponent(PaperPic).vm.$emit('apply', { blob: new Blob(['png']), type: 'image/png', width: 1, height: 1, }) await vi.waitFor(() => expect(wrapper.text()).toContain('Saved')) expect(fetch).toHaveBeenCalledWith('/api/documents/42', expect.objectContaining({ method: 'PUT' })) }) ``` \== React `vi.mock()` swaps PaperPic for a plain button that sends `apply` with a tiny image, and Testing Library clicks it: ```tsx import type { ExportedImage } from '@paperpic/react' import { fireEvent, render, screen } from '@testing-library/react' import { expect, it, vi } from 'vitest' import { Invoice } from './Invoice' // PaperPic needs a real browser. In its place, a button applies a small image vi.mock('@paperpic/react', () => ({ PaperPic: ({ onApply }: { onApply?: (image: ExportedImage) => void }) => ( ), })) it('saves the edited invoice', async () => { const fetch = vi.fn(async () => new Response(null, { status: 204 })) vi.stubGlobal('fetch', fetch) render() fireEvent.click(screen.getByRole('button', { name: 'Apply' })) await screen.findByText('Saved') expect(fetch).toHaveBeenCalledWith('/api/documents/42', expect.objectContaining({ method: 'PUT' })) }) ``` ::: The image needs no real pixels: a `Blob` of a few bytes is enough, because your code only looks at its type and size. [`ExportedImage`](../reference/types#exportedimage) lists everything that `apply` carries. ## In Nuxt {#nuxt} In Nuxt, unit tests run with [`@nuxt/test-utils`](https://nuxt.com/docs/getting-started/testing), in the `nuxt` environment of Vitest. That environment runs on happy-dom, or on jsdom if you choose it, so PaperPic still needs a stand-in. It works as in Vue, with two changes. `mountSuspended()` takes the place of `mount()` and mounts the component inside your Nuxt app. And since `@paperpic/nuxt` registers PaperPic for you, your component does not import it, so the test finds it by its name. This test covers the same component, saved as `Invoice.vue` and adapted to Nuxt as the [Nuxt](../reference/nuxt) page explains: ```ts import { mountSuspended } from '@nuxt/test-utils/runtime' import { expect, it, vi } from 'vitest' import Invoice from './Invoice.vue' it('saves the edited invoice', async () => { const fetch = vi.fn(async () => new Response(null, { status: 204 })) vi.stubGlobal('fetch', fetch) // A stub takes the place of PaperPic, which needs a real browser const wrapper = await mountSuspended(Invoice, { global: { stubs: { PaperPic: true }, }, }) wrapper.findComponent({ name: 'PaperPic' }).vm.$emit('apply', { blob: new Blob(['png']), type: 'image/png', width: 1, height: 1, }) await vi.waitFor(() => expect(wrapper.text()).toContain('Saved')) expect(fetch).toHaveBeenCalledWith('/api/documents/42', expect.objectContaining({ method: 'PUT' })) }) ``` ## In a real browser {#browser} In a browser, the viewer runs for real: it loads the image, edits it in the worker and applies the changes. This [Playwright](https://playwright.dev) test opens the invoice, rotates it, applies the changes and waits for the upload: ```ts import { expect, test } from '@playwright/test' test('saves the edited invoice', async ({ page }) => { // data-paperpic-control is the same in every language. The toolbar and the edit bar both have a rotateLeft, // and the toolbar is hidden while editing, so the locator keeps the visible one const control = (name: string) => page.locator(`[data-paperpic-control="${name}"]`).filter({ visible: true }) // Answers the upload, so the test needs no server await page.route('**/api/documents/42', route => route.fulfill({ status: 204 })) await page.goto('/invoices/42') // Edit is enabled once the image is on display await expect(control('edit')).toBeEnabled() await control('edit').click() await control('rotateLeft').click() const saved = page.waitForRequest(request => request.method() === 'PUT' && request.url().endsWith('/api/documents/42')) await control('apply').click() await saved await expect(page.getByText('Saved')).toBeVisible() }) ``` * Find the controls by `data-paperpic-control` rather than by their names. The names change with the language and with [`labels`](../reference/options#labels), and these values don't. [Controls](../reference/css-tokens#controls) lists them all. * A rotation is the quickest edit to test, because nothing has to wait. Straighten looks for the document first, and its Done button stays disabled until it finds one or the user moves a corner. * To start from a photo, as [Attach and scan](../examples/attach-and-scan) does, hand the file input a file with `setInputFiles()`. * To test your server too, take out `page.route()`. --- --- url: https://paperpic.dev/guide/labels.md description: >- How to translate PaperPic or change its wording with the labels option, screen reader texts included, and how to follow the language of your app. --- # Translating the interface PaperPic shows its buttons, hints and messages in English, and screen readers announce what changes, also in English. The [`labels`](../reference/options#labels) option replaces any of these texts, so the component speaks the language of your app. No translations ship with the packages. ## Replace some texts Pass only the texts you want to change. The others keep their English text: :::tabs key:framework \== JavaScript ```ts const pic = new PaperPic(container, { src: '/receipt.jpg', labels: { apply: 'Save', finish: 'Enhance' }, }) ``` \== Vue ```vue ``` \== React ```tsx import type { PaperPicLabels } from '@paperpic/react' import { PaperPic } from '@paperpic/react' const labels: Partial = { apply: 'Save', finish: 'Enhance' } export function Receipt() { return } ``` ::: [Labels](../reference/labels) lists every key with its English text and where it appears. ## Texts with a value Five labels are functions, because their text includes a value: the zoom, the sensitivity of Clean up, a corner and its position, a selected corner, and the ruler of Adjust. Screen readers announce them. Format the numbers as your language does: ```ts const signed = new Intl.NumberFormat('es', { signDisplay: 'exceptZero' }) const labels: Partial = { zoomLevel: percent => `Zoom ${percent} %`, finishLevel: percent => `Sensibilidad ${percent} %`, cornerMoved: (corner, x, y) => `${corner}: ${x}, ${y}`, cornerSelected: corner => `${corner}: toca donde va`, adjustmentLevel: (name, value) => `${name} ${signed.format(value)}`, } ``` ## Follow the language of your app When your app changes language, pass the labels of the new language, and the viewer updates its texts at once. Keep one object of labels for each language, created once, so that each render passes the same object: :::tabs key:framework \== JavaScript ```ts function setLanguage(language: string) { pic.setOptions({ labels: translations[language] }) } ``` \== Vue ```vue ``` \== React ```tsx import { PaperPic } from '@paperpic/react' export function Receipt({ language }: { language: string }) { return } ``` ::: Here `translations` stands for your own object of labels for each language. ## A starting point This site shows the component in nine languages besides English. Their labels are in [`paperpic-labels.ts`](https://github.com/paperpic/paperpic/blob/development/apps/docs/.vitepress/theme/components/paperpic-labels.ts), and you can copy them into your app. --- --- url: https://paperpic.dev/guide/troubleshooting.md description: >- Fixes for a PaperPic viewer with no height or style, Tailwind CSS conflicts, images that do not load or edit, a freeze on Apply and large photos that fail. --- # Troubleshooting Most problems with PaperPic come from its setup, and not from the image. Find what you see, and the fix below it. ## The viewer is a thin strip, or does not show {#no-height} The viewer fills its container, and a container without a height collapses to the minimum height of the viewer, 16rem. Give the container a height, such as `height: 480px`, or a place in a flex or grid layout that gives it one. [Styling](./styling) shows both. ## The buttons have no style, and the console warns {#no-stylesheet} The console says `PaperPic: the stylesheet is missing, so the viewer has no layout.` Import the stylesheet once in your app: `@paperpic/core/style.css`, or the `style.css` of `@paperpic/vue` or `@paperpic/react`. With `@paperpic/nuxt`, the module adds the stylesheet for you, so check that `@paperpic/nuxt` is in the `modules` of `nuxt.config.ts`. ## Tailwind CSS removes the borders and the padding of the viewer {#tailwind} The reset of Tailwind CSS 4 wins over the stylesheet of PaperPic when the cascade layers come in the wrong order. Name the layers before you import both, as [Styling](./styling#tailwind) shows. ## The image shows, but editing it fails {#other-origin} The [`error`](../reference/events#error) says that the image comes from another origin. Browsers do not let PaperPic read the pixels of such an image. Fetch it yourself and pass the `Blob`, as [Loading images](./loading#fetch) shows. ## The image does not load {#load-error} The viewer shows that the image could not be loaded, and `error` carries `phase: 'load'`. Check that the URL exists, and that the browser opens the format: HEIC only opens in Safari, and an SVG needs `width` and `height` attributes. [Loading images](./loading#formats) lists the formats. ## The page freezes while Apply runs {#worker} The worker did not start, so the editing runs on the main thread. It still works, but large photos freeze the page for a moment. The usual causes are: * A Content Security Policy without `worker-src 'self'`, or one that requires Trusted Types without a `default` policy. [Performance and support](./performance) lists what to allow. * The package loaded from a CDN, from another origin than the page. Browsers only start a worker from the origin of the page. The network panel of the browser shows whether the page requested the worker file, whose name starts with `worker`. ## Apply fails with a large photo {#too-large} The `error` says `The browser could not read an image of …`, or `could not save an image of …`. Browsers limit the size of a canvas, and Safari on iOS the most. Set [`maxOutputSize`](../reference/options#maxoutputsize), such as to 3000 pixels, which keeps documents readable. ## The wheel zooms the image instead of scrolling the page {#wheel} Set [`wheelZoom: false`](../reference/options#wheelzoom). The buttons, the keyboard and a pinch still zoom. --- --- url: https://paperpic.dev/reference/types.md description: >- Every TypeScript type that PaperPic exports, with its definition, the page that explains it and how to import it from the package you installed. --- # Types The reference and the examples name types such as `ExportedImage` or `ToolId`. This page shows what each one holds, so you can type your own code. Each type links to the page that explains it. Import the types from the package you installed. `@paperpic/vue` and `@paperpic/react` export every type of `@paperpic/core`, so you do not need to install it: :::tabs key:framework \== JavaScript ```ts import type { ExportedImage, PaperPicState, ToolId } from '@paperpic/core' ``` \== Vue ```ts import type { ExportedImage, PaperPicState, ToolId } from '@paperpic/vue' ``` \== React ```ts import type { ExportedImage, PaperPicState, ToolId } from '@paperpic/react' ``` ::: In a Nuxt app, import them from `@paperpic/nuxt`, which exports every type of `@paperpic/vue`. ## Options ### `PaperPicOptions` ```ts interface PaperPicOptions { alt?: string aspectRatio?: number download?: boolean editable?: boolean filename?: string icons?: Partial labels?: Partial maxOutputSize?: number output?: PaperPicOutput softness?: number src?: PaperPicSource toolbar?: boolean tools?: readonly ToolId[] wheelZoom?: boolean } ``` What the constructor and [`setOptions()`](./methods#setoptions) take. In Vue and React, these are the props of the component. [Options](./options) explains each one. ### `PaperPicSource` ```ts type PaperPicSource = string | Blob ``` The image in [`src`](./options#src): a URL, or a `File` or a `Blob`. The `source` of [`PaperPicDownload`](#paperpicdownload) has the same type. ### `PaperPicOutput` ```ts interface PaperPicOutput { quality?: number type?: string } ``` The format of the edited image, in [`output`](./options#output). ### `ToolId` ```ts type ToolId = 'adjust' | 'crop' | 'finish' | 'flip' | 'perspective' | 'redact' | 'rotate' ``` A tool of the edit bar, in [`tools`](./options#tools), [`openTool()`](./methods#opentool) and the `activeTool` of the [state](./state). [`tools`](./options#tools) gives the button of each one. ### `PaperPicLabels` ```ts interface PaperPicLabels { adjust: string adjustmentLevel: (name: string, value: number) => string adjustUnavailable: string applied: string apply: string applyError: string brightness: string cancel: string cancelTool: string confirm: string contrast: string cornerBottomLeft: string cornerBottomRight: string cornerKeys: string cornerMoved: (corner: string, x: number, y: number) => string cornerSelected: (corner: string) => string cornerTopLeft: string cornerTopRight: string crop: string cropHint: string discard: string discardQuestion: string download: string edit: string editBar: string editing: string finish: string finishGray: string finishLevel: (percent: number) => string finishMono: string finishOriginal: string finishSensitivity: string fitHeight: string fitWidth: string flip: string inUse: string keepEditing: string loadError: string loading: string paper: string paperA4: string paperAuto: string paperCard: string paperLetter: string perspective: string perspectiveFound: string perspectiveHint: string previewError: string processing: string redact: string redactAngle: (degrees: number) => string redactArea: string redactBlack: string redactHint: string redactTurn: string redactTurnKeys: string redactWhite: string redo: string rotateLeft: string rotateRight: string toolbar: string undo: string viewer: string zoomIn: string zoomLevel: (percent: number) => string zoomOut: string } ``` Every text of the interface, in [`labels`](./options#labels). The texts that include a value, such as the zoom level, are functions. [Labels](./labels) gives the English text of each one. ### `PaperPicIcons` ```ts interface PaperPicIcons { adjust: string apply: string brightness: string cancel: string contrast: string crop: string download: string edit: string finish: string fitHeight: string fitWidth: string flip: string perspective: string redact: string redo: string rotateDocument: string rotateLeft: string rotateRight: string undo: string zoomIn: string zoomOut: string } ``` Every icon of the interface, as the markup of one element, in [`icons`](./options#icons), which gives the buttons of each one. ## State ### `PaperPicState` ```ts interface PaperPicState { activeTool: ToolId | null adjustments: { brightness: number, contrast: number } busy: boolean canApply: boolean canConfirm: boolean canRedo: boolean canUndo: boolean finish: { mode: FinishMode, sensitivity: number } fit: Fit | null hint: string | null image: Size | null mode: 'view' | 'edit' paper: { size: PaperSize } redaction: { color: RedactColor } rotation: Rotation status: 'empty' | 'loading' | 'ready' | 'error' zoom: number } ``` What [`getState()`](./methods#getstate) returns and the [`change`](./events#change) event carries. [State](./state) explains each field. ### `FinishMode` ```ts type FinishMode = 'original' | 'gray' | 'mono' ``` The finish of [Clean up](../guide/tools/clean-up): the original tones, gray, or black and white with `'mono'`. [`setFinish()`](./methods#setfinish) takes it, and the `finish` of the [state](./state) holds it. ### `PaperSize` ```ts type PaperSize = 'auto' | 'a4' | 'letter' | 'card' ``` The paper that gives its proportions to the result of [Straighten](../guide/tools/straighten#paper-size). [`setPaper()`](./methods#setpaper) takes it, and the `paper` of the [state](./state) holds it. ### `RedactColor` ```ts type RedactColor = 'black' | 'white' ``` The color that [Redact](../guide/tools/redact) covers with. [`setRedaction()`](./methods#setredaction) takes it, and the `redaction` of the [state](./state) holds it. ### `Fit` ```ts type Fit = 'image' | 'width' | 'height' ``` How the image fits the viewer: whole, by its width or by its height. [`fit()`](./methods#fit) takes it, and the `fit` of the [state](./state) holds it. ### `Rotation` ```ts type Rotation = 0 | 90 | 180 | 270 ``` How far the image on display is turned, in degrees clockwise, in the `rotation` of the [state](./state). ### `Size` ```ts interface Size { height: number width: number } ``` A width and a height in pixels, such as the `image` of the [state](./state) or what the [`load`](./events#load) event carries. ## Events ### `PaperPicEvents` ```ts interface PaperPicEvents { apply: ExportedImage change: PaperPicState download: PaperPicDownload error: { error: Error, phase: 'load' | 'preview' | 'apply' } load: Size } ``` Each event with what it carries, for [`on()`](./methods#on). [Events](./events) explains each one. ### `ExportedImage` ```ts interface ExportedImage { blob: Blob height: number type: string width: number } ``` The edited image, which the [`apply`](./events#apply) event carries. `type` is the format of `blob`, which [`output`](./options#output) chooses. ### `PaperPicDownload` ```ts interface PaperPicDownload { filename: string preventDefault: () => void source: PaperPicSource } ``` What the [`download`](./events#download) event carries. Call `preventDefault()` to save the file another way. ## Methods ### `ViewPoint` ```ts interface ViewPoint { x: number y: number } ``` A point in CSS pixels from the top left corner of the viewer, for [`zoomTo()`](./methods#zoomto). ## Vue and React `@paperpic/vue` and `@paperpic/react` also export the types of their component, and `@paperpic/nuxt` exports the same ones as `@paperpic/vue`. [Vue](./vue) and [React](./react) show how to use it. ### `PaperPicInstance` ```ts type PaperPicInstance = PaperPic ``` The viewer that the component gives you: `instance` in Vue, and what `ref` receives in React. It is the class `PaperPic` of `@paperpic/core`, with every [method](./methods). ### `PaperPicProps` ```ts interface PaperPicProps extends PaperPicOptions { className?: string onApply?: (result: PaperPicEvents['apply']) => void onChange?: (state: PaperPicEvents['change']) => void onDownload?: (download: PaperPicEvents['download']) => void onError?: (failure: PaperPicEvents['error']) => void onLoad?: (size: PaperPicEvents['load']) => void ref?: Ref style?: CSSProperties } ``` The props of the component in React: the options, plus the classes and styles of its element, a callback for each event, and `ref`. In Vue, the props have the same fields as [`PaperPicOptions`](#paperpicoptions), and the events are component events. --- --- url: https://paperpic.dev/examples/upload.md description: >- A complete example that sends the image edited in PaperPic to your server and tells the user whether it was saved, in plain JavaScript, Vue and React. --- # Upload to a server The viewer shows the result of Apply at once, but saving it is up to your app. This example sends the edited image to your server and tells the user how it went. This function sends the image as a file in a form, and fails when the server does not accept it: ```ts async function upload(blob: Blob, type: string) { const body = new FormData() body.append('file', blob, `document.${type.split('/')[1]}`) const response = await fetch('/api/documents/42', { method: 'PUT', body }) if (!response.ok) { throw new Error(`The upload failed with status ${response.status}`) } } ``` The viewer calls it on Apply, and a status line reports the result: :::tabs key:framework \== JavaScript ```html

``` ```ts import { PaperPic } from '@paperpic/core' import '@paperpic/core/style.css' const status = document.querySelector('#status')! const pic = new PaperPic(document.querySelector('#viewer')!, { src: '/documents/42.jpg', alt: 'Invoice 42', maxOutputSize: 3000, }) pic.on('apply', async ({ blob, type }) => { status.textContent = 'Saving…' try { await upload(blob, type) status.textContent = 'Saved' } catch { status.textContent = 'The document could not be saved' } }) ``` \== Vue ```vue ``` \== React ```tsx import type { ExportedImage } from '@paperpic/react' import { PaperPic } from '@paperpic/react' import { useState } from 'react' import '@paperpic/react/style.css' export function Invoice() { const [status, setStatus] = useState('') async function save({ blob, type }: ExportedImage) { setStatus('Saving…') try { await upload(blob, type) setStatus('Saved') } catch { setStatus('The document could not be saved') } } return ( <>

{status}

) } ``` ::: ## Notes * `role="status"` makes screen readers announce the result of the upload. * [`maxOutputSize`](../reference/options#maxoutputsize) keeps the file small. Documents stay readable at 3000 pixels on the longest side. * After Apply, the history is empty, so the user cannot undo into the old image. To offer a retry button, keep the last `blob` and `type` and call `upload` again. * The server receives PNG for a document in black and white, and otherwise the format of the source when it is JPEG, PNG or WebP. Read [Saving the result](../guide/saving#format) to learn how PaperPic tells the format, and to choose another one. --- --- url: https://paperpic.dev/guide/viewer.md description: >- How people zoom, pan and fit a document image in PaperPic, what the toolbar offers, and how to show an image read-only, with a live demo. --- # Viewer Small print and long receipts are hard to read at a glance on a screen. The viewer fits the image when it loads and lets people zoom into any part of it. ## Zoom and pan | Action | Mouse and trackpad | Touch | Keyboard | | ------------------------------- | ----------------------------- | ---------- | ----------- | | Zoom | Wheel, or pinch on a trackpad | Pinch | `+` and `-` | | Pan | Drag | Drag | Arrow keys | | Switch between the fit and 100% | Double click | Double tap | | | Fit the whole image | | | `0` | The keys work while the focus is inside the viewer. On a button, the arrow keys move between the buttons instead, and while there is nothing to move, they scroll the page. A pinch zooms around the point between the fingers. On a touch screen, one finger scrolls the page while the image is fitted, and pans the image once it is zoomed in. The zoom goes from the fit of the whole image, or 100% for a small image, up to 800%. An image that fits stays centered, and one that overflows pans up to its edges. When the image loads, it fits the viewer whole, and it keeps its fit when the viewer changes size, until the user zooms by hand. In a long page, the wheel would zoom the image instead of scrolling the page. Set `wheelZoom: false` there: the buttons, the keyboard and a pinch on a touch screen still zoom. A pinch on a trackpad no longer zooms the image, because the browser reports it as the wheel. ## The toolbar The toolbar sits at the right of the viewer, and scrolls when the viewer is too short for its buttons. It hides while editing, so it never covers a corner of Crop or Straighten. | Button | What it does | | --------------------------- | ----------------------------------------------------------------------------------------------------- | | Edit | Starts the [edit mode](./editing). It shows once the image is ready, and never with `editable: false` | | Zoom in, Zoom out | Zoom one step of 25%, around the center | | Fit to width, Fit to height | Fit the width, which suits long documents, or the height | | Rotate left, Rotate right | Only in a read-only viewer: turn the image on display | | Download | Only with `download: true`: save the image on display | Fit to width and Fit to height stay pressed while their fit holds. No button fits the whole image again: press `0`, or zoom out all the way. With `toolbar: false`, the toolbar and the edit bar are hidden, and you can build your own controls with the [methods](../reference/methods). ## Read-only viewer {#read-only} With `editable: false`, the Edit button goes away, and the toolbar gets two buttons that rotate the image. That rotation only changes the display, and nothing is saved: Download saves the image without it. Use it for documents that people should read but not change, such as the attachments of a record. :::tabs key:framework \== JavaScript ```ts const pic = new PaperPic(container, { src: '/receipt.jpg', alt: 'A receipt', editable: false, }) ``` \== Vue ```vue ``` \== React ```tsx ``` ::: ## Control the view from code The methods [`zoomIn()`](../reference/methods#zoomin), [`zoomOut()`](../reference/methods#zoomout), [`zoomTo()`](../reference/methods#zoomto) and [`fit()`](../reference/methods#fit) do what the buttons do, and [`getState()`](../reference/methods#getstate) tells you the zoom and the fit in effect: ```ts pic.fit('width') pic.zoomTo(2) const { zoom, fit } = pic.getState() ``` --- --- url: https://paperpic.dev/reference/vue.md description: >- How the PaperPic component for Vue maps the options, events and methods of the core to props, component events and a template ref. --- # Vue `@paperpic/vue` wraps the viewer in a component for Vue 3.5 or newer. The options are props, the events are component events, and the methods are on the `instance` that the component exposes. ```vue ``` The component fills its parent element, so give the parent a height. ## Props Every [option](./options) is a prop with the same name, such as `:editable="false"` or `:aspect-ratio="210 / 297"`. A change of a prop reaches the viewer through `setOptions()`. `class` and `style` go to the element that holds the viewer, which also has the class `paperpic-host`. An object or array with the same contents as before, such as `:tools="['crop', 'rotate']"`, changes nothing, so the template can build them. A function is new on every render of the parent, so build `labels` that hold functions, such as `zoomLevel`, with `computed`. ## Events | Event | Payload | | ---------- | ---------------------------------------------- | | `apply` | [`ExportedImage`](./types#exportedimage) | | `change` | [`PaperPicState`](./state) | | `download` | [`PaperPicDownload`](./types#paperpicdownload) | | `error` | `{ error, phase }` | | `load` | [`Size`](./types#size) | [Events](./events) describes each one. A change of a prop never emits `change`. [State](./state#in-step) shows how to keep the state in a `shallowRef` with `@change`, `@load` and `@error`. ## Methods {#methods} The component exposes the viewer as `instance`, with the [methods](./methods), such as `zoomIn()` or `apply()`. It is `null` until the component mounts: ```vue ``` The component creates the viewer when it mounts and destroys it when it unmounts, so do not call `destroy()`. Change the props instead of calling `setOptions()`, which the next change of a prop would undo, and use the component events instead of `on()`. Passing the same `src` again does not reload the image, so it keeps the result of an edit. To bring back the original, call `instance.reload()`. ## Types {#types} `@paperpic/vue` exports every type of `@paperpic/core`, so you do not need to install it: [Types](./types) shows each one. It also exports the types of the component: [`PaperPicProps`](./types#paperpicprops), with its props, and [`PaperPicInstance`](./types#paperpicinstance), the viewer in `instance`. ## Server-side rendering With server-side rendering, such as in Nuxt, the component renders an empty element on the server and creates the viewer in the browser. In a Nuxt app, [`@paperpic/nuxt`](./nuxt) sets up the component and its stylesheet for you. --- --- url: https://paperpic.dev/guide/introduction.md description: >- PaperPic is an open-source document scanner and image viewer for web apps: straighten, crop and clean up photos of documents, and zoom in to read them. --- # What is PaperPic? Photos of documents arrive skewed, shadowed and full of background. PaperPic shows them in a viewer that people can zoom into, and lets them straighten and clean up each photo before your app keeps it, as a scanner app would. ## What it does * **View.** Zoom with the buttons, the wheel, a pinch, a double click or the keyboard, pan, and fit the whole image, its width or its height. A read-only viewer can also rotate the image. * **Edit.** In the edit mode, the user can crop, straighten a photo taken at an angle, rotate, flip, adjust the brightness and the contrast, and clean up the document into gray or black and white. Every edit can be undone until the user applies the changes. * **Deliver.** Apply computes the result at full resolution and hands it to your code as a `Blob`. A download button can also save it. Each step happens only when the user asks for it. Nothing changes the photo on its own. ## What it does not do * It does not upload anything. Your app decides what to do with the result. * It does not open PDF files, only images. * It does not always find the document on its own: when it is not sure, the user drags the corners. * It does not open the camera itself. On a phone, the file input offers it, as [Attach and scan](../examples/attach-and-scan) shows. ## Packages | Package | Use it with | | ----------------- | ---------------------------------- | | `@paperpic/core` | Plain JavaScript, or any framework | | `@paperpic/vue` | Vue 3.5 or newer | | `@paperpic/react` | React 19 or newer | | `@paperpic/nuxt` | Nuxt 4 | The core and the two components have the same options, events and methods, and the core has no runtime dependencies. In a Nuxt app, `@paperpic/nuxt` sets up the Vue component for you. The editing runs in a Web Worker, so the page stays responsive with large photos. ## Try it The [playground](../playground) lets you edit a sample receipt, or a photo of your own that never leaves your browser. To add PaperPic to your app, go to [Getting started](./getting-started).