AI and machine learning · Intermediate · 22 min
Send images and PDF documents to Claude from Python
By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · anthropic 2.14.0 · Pillow 13.0.0 · pypdf 7.1.1
You will send Claude a receipt photo as base64 and by URL, a multi-page PDF with page citations, and a file uploaded once through the Files API, after checking each file against the documented limits and shrinking large photos with Pillow.
On this page
Claude reads images and PDFs as well as text. You put a picture or a document into the content list of a user message as its own block, next to the text block that asks the question. The work around that block is where most bugs live: a photo that is too large, a PDF with a password, a file uploaded ten times when once would do, an answer nobody can trace back to a page.
In this tutorial you build a small toolkit for a shop's paperwork. It sends a till receipt photo to Claude in two ways, asks questions about a three-page returns policy PDF with page citations, uploads the PDF once and reuses it, and flags scanned documents that a person has to check. Every script checks its file against the limits Anthropic documents before it sends anything, so a bad file fails on your machine, not after a slow upload.
The model is claude-opus-5-5. All the code runs against the official anthropic Python SDK, version 2.14.0. The sample files are generated by a script, so you can follow along without real receipts, and swap in your own files at any point.
Step 1 · Create the project and the sample files
Make a throwaway project folder and add four pinned packages: the SDK, Pillow for images, pypdf to read PDFs, and fpdf2, which only the sample generator uses:
mkdir -p ~/vision-demo
cd ~/vision-demo
uv init --no-package
uv add anthropic==2.14.0 pillow==13.0.0 pypdf==7.1.1 fpdf2==2.9.0Load your API key into the terminal, as in the earlier tutorial. Do this in every new terminal before you run the scripts:
set -a
. ~/.config/llm-demo/env
set +aNow write make_samples.py. It draws a receipt at the size a phone camera saves (3024 by 4032 pixels), writes a three-page policy PDF that has real text in it, and saves the receipt again as a one-page PDF made only of a picture, which is what a scanner produces:
cat > make_samples.py <<'PY'
from fpdf import FPDF
from PIL import Image, ImageDraw, ImageFont
# A till receipt at phone-camera size.
receipt = Image.new("RGB", (3024, 4032), (238, 234, 226))
draw = ImageDraw.Draw(receipt)
big = ImageFont.load_default(size=150)
small = ImageFont.load_default(size=110)
lines = [
(big, "MAMA PUT KITCHEN"),
(small, "Allen Avenue, Ikeja"),
(small, "2026-11-20 13:05"),
(small, ""),
(small, "Jollof rice x2 NGN 3,000.00"),
(small, "Plantain NGN 1,000.00"),
(small, "Zobo NGN 500.00"),
(small, ""),
(big, "TOTAL NGN 4,500.00"),
]
y = 400
for font, text in lines:
draw.text((300, y), text, fill=(30, 30, 30), font=font)
y += 260
receipt.save("receipt.jpg", "JPEG", quality=95)
# A three-page policy with a text layer.
pages = [
("1. Orders", "Orders placed before 14:00 ship the same working day."),
("2. Refunds", "Refunds are accepted within 30 days of purchase. Bring the receipt, "
"or the order number for online orders. Items must be unused."),
("3. Delivery", "We deliver within Lagos, Abuja and Port Harcourt. Orders outside "
"these cities go by courier at the customer's cost."),
]
pdf = FPDF()
for heading, body in pages:
pdf.add_page()
pdf.set_font("Helvetica", size=18)
pdf.cell(0, 12, text="Kola Hardware returns policy")
pdf.ln(16)
pdf.set_font("Helvetica", size=14)
pdf.multi_cell(0, 9, text=f"{heading}\n{body}")
pdf.output("policy.pdf")
# The same receipt as a scanner would save it: a picture inside a PDF, no text.
receipt.save("scanned.pdf", "PDF", resolution=300)
print("receipt.jpg", receipt.size)
print("policy.pdf", len(pages), "pages")
print("scanned.pdf 1 page")
PY
uv run make_samples.pyThe prices are in Nigerian naira, written NGN so the font needs no special symbol. Use your own receipt and policy any time: put the files in ~/vision-demo and change the names in the scripts.
Check it worked
The script prints receipt.jpg (3024, 4032), policy.pdf 3 pages and scanned.pdf 1 page. Open receipt.jpg in an image viewer: you see the shop name, three items and a total.
Step 2 · Check each file against the limits before you send it
The API rejects files that break its limits, but only after your machine has uploaded the whole request. On a slow or prepaid mobile connection that is wasted time and data, so check first. These are the limits Anthropic's vision and PDF support pages give for the Claude API in November 2026:
- Images: JPEG, PNG, GIF or WebP. An animated GIF counts as its first frame only.
- No side longer than 8,000 pixels, and at most 10 MB per image once base64-encoded. Amazon Bedrock allows 5 MB.
- PDFs: no password or encryption, and at most 600 pages in one request (100 on models with a context window under 1 million tokens).
- The whole request, with every file in it, at most 128 MB.
Base64 turns every 3 bytes into 4 characters, so a file grows by a third when you encode it. A 9 MB photo is about 12 MB of base64 and goes over the image limit. Put the checks in a module that every later script imports, media.py:
cat > media.py <<'PY'
import base64
import math
from pathlib import Path
from PIL import Image, ImageOps
from pypdf import PdfReader
IMAGE_TYPES = {"JPEG": "image/jpeg", "PNG": "image/png", "GIF": "image/gif", "WEBP": "image/webp"}
MAX_IMAGE_SIDE = 8000 # pixels, for each side
MAX_IMAGE_B64 = 10 * 1024 * 1024 # bytes after base64 encoding
MAX_PDF_PAGES = 600 # 100 on models with a smaller context window
MAX_REQUEST = 128 * 1024 * 1024 # bytes, the whole request
def b64_size(n_bytes):
return 4 * math.ceil(n_bytes / 3)
def b64(path):
return base64.standard_b64encode(Path(path).read_bytes()).decode("ascii")
def check_image(path):
"""Return the media type of an image the API accepts, or raise ValueError."""
with Image.open(path) as img:
fmt, (w, h) = img.format, img.size
if fmt not in IMAGE_TYPES:
raise ValueError(f"{fmt} is not JPEG, PNG, GIF or WebP")
if max(w, h) > MAX_IMAGE_SIDE:
raise ValueError(f"{max(w, h)} px is over the {MAX_IMAGE_SIDE:,} px limit for a side")
encoded = b64_size(Path(path).stat().st_size)
if encoded > MAX_IMAGE_B64:
raise ValueError(f"{encoded:,} bytes of base64 is over the 10 MB limit")
return IMAGE_TYPES[fmt]
def check_pdf(path, max_pages=MAX_PDF_PAGES):
"""Return the page count of a PDF the API accepts, or raise ValueError."""
reader = PdfReader(path)
if reader.is_encrypted:
raise ValueError("the PDF is password-protected or encrypted")
pages = len(reader.pages)
if pages > max_pages:
raise ValueError(f"{pages} pages is over the {max_pages}-page limit; split it")
if b64_size(Path(path).stat().st_size) > MAX_REQUEST:
raise ValueError("the PDF is over the 128 MB request limit; use the Files API or split it")
return pages
def visual_tokens(w, h):
"""Anthropic's estimate: one visual token per 28 x 28 pixel patch."""
return math.ceil(w / 28) * math.ceil(h / 28)
def shrink_photo(src, dest, long_edge=1568):
"""Turn the photo upright, fit it inside long_edge pixels and save it as JPEG."""
with Image.open(src) as img:
img = ImageOps.exif_transpose(img).convert("RGB")
img.thumbnail((long_edge, long_edge), Image.Resampling.LANCZOS)
img.save(dest, "JPEG", quality=85, optimize=True)
return img.size
def reply_text(message):
text = "".join(block.text for block in message.content if block.type == "text")
if not text and message.stop_reason == "max_tokens":
return "(max_tokens was used up before any text; raise max_tokens)"
return text or "(no text in the reply)"
PYreply_text is there because Claude Opus 5.5 always thinks before it answers, and thinking tokens count towards max_tokens. If thinking uses up the whole allowance, the reply has no text block at all, and the function says so instead of printing nothing.
Now a small command-line checker, and an image that is too wide, to see a refusal:
cat > check_files.py <<'PY'
import sys
from media import check_image, check_pdf
for name in sys.argv[1:]:
try:
if name.lower().endswith(".pdf"):
print(f"{name}: ok, {check_pdf(name)} page(s)")
else:
print(f"{name}: ok, {check_image(name)}")
except ValueError as err:
print(f"{name}: refused, {err}")
PY
uv run python -c "from PIL import Image; Image.new('RGB', (9000, 600), 'white').save('wide.png')"
uv run check_files.py receipt.jpg policy.pdf scanned.pdf wide.pngCheck it worked
You see four lines. The first three end in ok with image/jpeg, 3 page(s) and 1 page(s). The last is wide.png: refused, 9000 px is over the 8,000 px limit for a side.
Step 3 · Shrink large photos before you send them
Claude splits an image into 28 by 28 pixel patches, and each patch costs one input token. Anthropic's vision page gives the estimate as width ÷ 28, rounded up, times height ÷ 28, rounded up. Claude 4.7 and later models, Opus 5.5 among them, take images up to 2,576 pixels on the long edge and 4,784 visual tokens, and scale anything larger down on their side. So a full-size phone photo costs up to 4,784 tokens and still has to travel over your connection at full size.
A till receipt does not need that much detail. Fitting it inside 1,568 pixels keeps the print readable, roughly halves the tokens, and cuts the upload to a fraction of the original. That matters on a prepaid data bundle, and when your app runs on a low-end Android phone. Keep the larger size for dense pages with small print, and compare the answers on a few real samples before you settle on a size.
shrink_photo in media.py also calls ImageOps.exif_transpose. Phones often save a photo sideways and store "rotate this" in the file's EXIF data. Turning the pixels upright before you resize means Claude sees the receipt the right way up. Run it:
cat > shrink.py <<'PY'
import os
from PIL import Image
from media import shrink_photo, visual_tokens
with Image.open("receipt.jpg") as img:
w, h = img.size
print(f"original: {w}x{h}, {os.path.getsize('receipt.jpg'):,} bytes")
print(" sent as it is, Claude Opus 5.5 scales it down and counts up to 4,784 visual tokens")
nw, nh = shrink_photo("receipt.jpg", "receipt-small.jpg")
print(f"resized: {nw}x{nh}, {os.path.getsize('receipt-small.jpg'):,} bytes, "
f"about {visual_tokens(nw, nh):,} visual tokens")
PY
uv run shrink.pyCheck it worked
The last line starts resized: 1176x1568 and ends about 2,352 visual tokens. The byte count of receipt-small.jpg is much smaller than the original's. Open receipt-small.jpg and zoom in: every price is still sharp enough for you to read, and that is the check that matters.
Step 4 · Send the receipt as a base64 image block
An image block has a source. With "type": "base64" you send the bytes yourself, encoded as text, with the media type. Anthropic's vision guide suggests putting images before the question, so the image block comes first in the list. Create receipt_base64.py:
cat > receipt_base64.py <<'PY'
import anthropic
from media import b64, check_image, reply_text
PROMPT = (
"This is a photo of a till receipt. List the shop name, the date, each line item "
"with its price, and the total. Copy every figure exactly as printed, in the "
"receipt's own language. If you cannot read a value, write UNREADABLE instead of guessing."
)
path = "receipt-small.jpg"
media_type = check_image(path)
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=4000,
messages=[
{
"role": "user",
"content": [
{"type": "image", "source": {"type": "base64", "media_type": media_type, "data": b64(path)}},
{"type": "text", "text": PROMPT},
],
}
],
)
print(reply_text(message))
print("tokens in/out:", message.usage.input_tokens, message.usage.output_tokens)
PY
uv run receipt_base64.pyThe prompt asks for UNREADABLE rather than a guess, and for figures copied as printed. A model that is told to fill every field fills them, sometimes with numbers it made up. "In the receipt's own language" keeps the item names in French, Swahili or Yoruba if that is how they were printed, instead of quietly translated.
Check it worked
The reply lists the shop, the date, the three items and NGN 4,500.00 as the total, and the last line shows the token counts. The input count includes the image's visual tokens, so it is more than 2,000. The wording differs from run to run. Check each figure against the photo yourself: the step on scanned documents explains why.
Step 5 · Send an image by URL instead
If the image already sits on a public web address, you can send the address instead of the bytes. Anthropic's servers download it, so nothing large leaves your machine. That suits images already in your own storage bucket or CDN. It does not suit private files, because the address has to open for anyone, and you cannot resize the image on the way. Create receipt_url.py:
cat > receipt_url.py <<'PY'
import sys
import anthropic
from media import reply_text
url = sys.argv[1]
if not url.startswith("https://"):
print("Give a public https:// address for the image.")
sys.exit(2)
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=4000,
messages=[
{
"role": "user",
"content": [
{"type": "image", "source": {"type": "url", "url": url}},
{"type": "text", "text": "List the shop name, the date and the total on this receipt. "
"Write UNREADABLE for anything you cannot read."},
],
}
],
)
print(reply_text(message))
PYBefore you run it, put the address of a receipt image of your own in the IMAGE_URL variable. Check first that the address opens in a private browser window without a login, then replace the placeholder below with it:
export IMAGE_URL="https://<your-public-image-url>"Now send it:
uv run receipt_url.py "$IMAGE_URL"Check it worked
With a real public image, the reply lists the shop, the date and the total from that image. Run the script with http:// or with a file name instead, and it stops with Give a public https:// address for the image. before it calls the API.
Step 6 · Send the PDF and ask for page citations
A PDF goes in a document block. Claude gets both the text of each page and an image of it, so tables and charts count too. Anthropic's PDF page estimates 1,500 to 3,000 text tokens per page, plus up to 1,568 tokens for each page image, so a long PDF costs real money on every request.
Citations make the answer checkable. Turn them on with "citations": {"enabled": True} on the document block, and the reply comes back split into several text blocks. The ones that rest on the document carry a citations list, and each PDF citation gives the quoted sentence and its pages. The page numbers start at 1, and end_page_number is exclusive: a quote from page 2 alone has a start of 2 and an end of 3. If a request has several documents, enable citations on all of them or on none. Create pdf_citations.py:
cat > pdf_citations.py <<'PY'
import anthropic
from media import b64, check_pdf
path = "policy.pdf"
pages = check_pdf(path)
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=4000,
messages=[
{
"role": "user",
"content": [
{
"type": "document",
"source": {"type": "base64", "media_type": "application/pdf", "data": b64(path)},
"title": "Kola Hardware returns policy",
"citations": {"enabled": True},
},
{"type": "text", "text": "How long do customers have to ask for a refund?"},
],
}
],
)
print(f"sent {path} ({pages} pages)")
for block in message.content:
if block.type != "text":
continue
print(block.text, end="")
for cite in block.citations or []:
if cite.type == "page_location":
last = cite.end_page_number - 1
where = f"p. {cite.start_page_number}" + (f"-{last}" if last > cite.start_page_number else "")
print(f' [{where}: "{cite.cited_text}"]', end="")
print()
PY
uv run pdf_citations.pyTwo limits apply. Citations and structured output (output_config.format) cannot be used in the same request: the API returns a 400 error. And Claude cannot cite a PDF that is only a scan, because there is no text for a citation to point to.
Check it worked
You see sent policy.pdf (3 pages), then the answer with a marker such as [p. 2: "Refunds are accepted within 30 days of purchase."] after the part that came from the document. Open policy.pdf at page 2: the quoted sentence is there, word for word.
Step 7 · Upload the PDF once and reuse its file ID
Every base64 request carries the whole file again. If you ask five questions about the same contract, you upload it five times. The Files API stores the file once and gives you an ID to put in later requests instead. It is out of beta, so the SDK call is client.files.upload with no beta header. Upload and delete are free; the file's content is still billed as input tokens each time a request uses it.
Uploaded files belong to the whole workspace, not to one user or conversation. Any key with access to the workspace can read them. Keep the mapping from your users to their file IDs on your own server, and never accept a file ID sent in by a user, or one user could read another's documents. Create files_reuse.py:
cat > files_reuse.py <<'PY'
from pathlib import Path
import anthropic
from media import check_pdf, reply_text
path = Path("policy.pdf")
check_pdf(path)
client = anthropic.Anthropic()
uploaded = client.files.upload(file=(path.name, path.read_bytes(), "application/pdf"))
print(f"uploaded {uploaded.filename} as {uploaded.id}, {uploaded.size_bytes:,} bytes")
questions = [
"How long do customers have to ask for a refund?",
"Which cities does delivery cover?",
]
try:
for question in questions:
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=4000,
messages=[
{
"role": "user",
"content": [
{"type": "document", "source": {"type": "file", "file_id": uploaded.id},
"title": "Kola Hardware returns policy"},
{"type": "text", "text": question},
],
}
],
)
print("Q:", question)
print("A:", reply_text(message))
finally:
client.files.delete(uploaded.id)
print("deleted", uploaded.id)
PY
uv run files_reuse.pyThe finally block deletes the file even if a question fails, so a crash does not leave the policy stored. In a real app you would keep the ID in your database while the document is in use and delete it when the user removes the document. An image works the same way: upload it with its image media type and use {"type": "image", "source": {"type": "file", "file_id": ...}}.
Check it worked
The first line shows uploaded policy.pdf as file_ followed by an ID and the file size. Then come two questions with their answers, and the last line is deleted with the same ID. The size matches ls -l policy.pdf.
Step 8 · Send scanned documents to a person for checking
A model reading a photo or a scan can misread a faded 8 as a 3, drop a decimal point, or join two lines of a receipt. Thermal till paper fades in heat and sunlight, phone photos blur, and handwritten amounts are harder still. The answer reads as confidently when it is wrong as when it is right. A scan also has no text layer, so citations cannot point you to the source.
So decide in code which documents a person must check, before anything goes into your accounts. needs_review.py looks for a text layer in each PDF:
cat > needs_review.py <<'PY'
import sys
from pypdf import PdfReader
for name in sys.argv[1:]:
reader = PdfReader(name)
chars = sum(len((page.extract_text() or "").strip()) for page in reader.pages)
if chars == 0:
print(f"{name}: no text layer, so it is a scan. No citations; "
"a person checks every figure against the original.")
else:
print(f"{name}: {chars} characters of text. Citations can point to pages; "
"a person still spot-checks the figures.")
PY
uv run needs_review.py policy.pdf scanned.pdfTreat every photo the same way as a scanned PDF. A workable rule for receipts and invoices: show the extracted values next to the image, and have a person confirm the total and the date before the entry is saved. Add cheap checks in code as well, such as the line items adding up to the total, and send any UNREADABLE field straight to the person.
Check it worked
policy.pdf reports a few hundred characters of text, and scanned.pdf reports no text layer, so it is a scan. Run the script on one of your own PDFs: one exported from a word processor has text, and one from a scanner app usually has none unless the app ran text recognition on it.
Step 9 · Clean up
The upload script already deleted its file. Delete the demo project. The key file stays, because the other tutorials in this section use it:
cd ~
rm -rf ~/vision-demoCheck it worked
ls ~/vision-demo reports that the folder does not exist.
Next steps
- Turn the receipt reply into fields your code can trust: get reliable JSON output from an LLM. Remember that structured output and citations cannot share a request.
- Test these scripts without spending money or needing a key: test Claude API code offline against a stub server.
- Show long answers about big PDFs as they are written: stream Claude responses token by token in Python.
- Go back over keys, errors and costs: call an LLM API from Python.
Related tutorials
- Test Claude API code offline against a stub serverYou will have a pytest suite that checks your Claude API code against a local stub of the Messages API, covering the request it sends, text and tool_use replies, a max_tokens stop and 429 and 529 errors, with a folder of fixtures and a rule for refreshing them.
- Process thousands of prompts at half price with the Message Batches APIYou will tag 2,000 product reviews with Claude Haiku 5.5 through the Message Batches API, match results by custom_id, retry only the requests that failed or expired, and finish with a script you can stop and resume.
- Improve LLM answers with few-shot examples and measure the differenceYou will score a small local model on 40 labelled customer messages with zero, three and eight examples in the prompt, and end with a table that shows what the examples changed.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials