---
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<Receipt> {
  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
<label>
  Photo of the receipt
  <input id="photo" type="file" accept="image/*" capture="environment" />
</label>
<div id="viewer" style="height: 480px"></div>
<p id="status" role="status"></p>
```

```ts
import { PaperPic } from '@paperpic/core'
import '@paperpic/core/style.css'

const input = document.querySelector<HTMLInputElement>('#photo')!
const status = document.querySelector('#status')!

const pic = new PaperPic(document.querySelector<HTMLElement>('#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
<script setup lang="ts">
import type { ExportedImage, ToolId } from '@paperpic/vue'
import { PaperPic } from '@paperpic/vue'
import { shallowRef, useTemplateRef } from 'vue'
import '@paperpic/vue/style.css'

const tools: ToolId[] = [
  'perspective',
  'crop',
  'rotate',
  'finish',
  'redact',
]

const pic = useTemplateRef('pic')
const photo = shallowRef<File>()
const status = shallowRef('')

function choose(event: Event) {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  input.value = ''
  if (file) {
    status.value = ''
    photo.value = file
  }
}

// Black and white is one edit, so the user can still undo it or choose Gray in Clean up
function start() {
  pic.value?.instance?.edit()
  pic.value?.instance?.setFinish({ mode: 'mono' })
}

async function read({ blob, type }: ExportedImage) {
  status.value = 'Reading…'
  try {
    const { merchant, total } = await readReceipt(blob, type)
    status.value = `${merchant}: ${total}`
  }
  catch {
    status.value = 'The receipt could not be read'
  }
}
</script>

<template>
  <label>
    Photo of the receipt
    <input type="file" accept="image/*" capture="environment" @change="choose">
  </label>
  <div v-if="photo" style="height: 480px">
    <PaperPic
      ref="pic"
      :src="photo"
      alt="The receipt you attached"
      :tools="tools"
      :max-output-size="2000"
      @load="start"
      @apply="read"
    />
  </div>
  <p role="status">
    {{ status }}
  </p>
</template>
```

\== 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<PaperPicInstance>(null)
  const [photo, setPhoto] = useState<File>()
  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 (
    <>
      <label>
        Photo of the receipt
        <input type="file" accept="image/*" capture="environment" onChange={event => choose(event.target)} />
      </label>
      {photo && (
        <div style={{ height: 480 }}>
          <PaperPic
            ref={picRef}
            src={photo}
            alt="The receipt you attached"
            tools={tools}
            maxOutputSize={2000}
            onLoad={start}
            onApply={read}
          />
        </div>
      )}
      <p role="status">{status}</p>
    </>
  )
}
```

:::

## 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.
