Extraction and OCR¶
The extraction side of the PDF Toolkit is designed for text mining, document intelligence, and form processing workflows.
Extraction endpoints¶
| Method | Endpoint | Purpose |
|---|---|---|
GET |
/v1/pdf/text |
Extract text page by page |
POST |
/v1/pdf/metadata |
Read or update metadata |
GET |
/v1/pdf/table-extract |
Extract tabular data |
POST |
/v1/pdf/form-fields |
Read or fill AcroForm fields |
GET |
/v1/pdf/info |
Get page count and structure |
GET |
/v1/pdf/ocr |
OCR scanned or image-based PDFs |
Only metadata and form-fields take a JSON body
text, table-extract, info, and ocr are GET endpoints with query parameters. Posting a JSON body to them returns 405 Method Not Allowed. Use metadata and form-fields when you need to send a JSON payload (an update or fill object).
REST API Examples¶
Extract text¶
curl -G "https://pdf.toolkitapi.io/v1/pdf/text" \
-H "X-API-Key: YOUR_KEY" \
--data-urlencode "url=https://toolkitapi.io/report.pdf" \
--data-urlencode "pages=1-3"
import requests
resp = requests.get(
"https://pdf.toolkitapi.io/v1/pdf/text",
params={"url": "https://toolkitapi.io/report.pdf", "pages": "1-3"},
headers={"X-API-Key": "YOUR_KEY"},
timeout=120,
)
resp.raise_for_status()
data = resp.json()
for page in data["pages"]:
print(f"Page {page['page']}: {page['text'][:100]}...")
print(f"{data['total_word_count']} words across {data['extracted_pages']} pages")
const url = new URL("https://pdf.toolkitapi.io/v1/pdf/text");
url.search = new URLSearchParams({ url: "https://toolkitapi.io/report.pdf", pages: "1-3" });
const resp = await fetch(url, { headers: { "X-API-Key": "YOUR_KEY" } });
if (!resp.ok) throw new Error(`text extract failed: ${resp.status}`);
const data = await resp.json();
data.pages.forEach((p) => console.log(`Page ${p.page}: ${p.text.substring(0, 100)}...`));
Response
{
"pages": [{ "page": 1, "text": "Quarterly report..." }],
"total_pages": 10,
"extracted_pages": 3,
"total_word_count": 1420,
"total_char_count": 8931
}
Get PDF metadata¶
metadata is POST because it can also write metadata back.
curl -X POST "https://pdf.toolkitapi.io/v1/pdf/metadata" \
-H "X-API-Key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://toolkitapi.io/report.pdf"}'
import requests
resp = requests.post(
"https://pdf.toolkitapi.io/v1/pdf/metadata",
headers={"X-API-Key": "YOUR_KEY"},
json={"url": "https://toolkitapi.io/report.pdf"},
timeout=60,
)
resp.raise_for_status()
data = resp.json()
print(data["metadata"])
print(f"{data['page_count']} pages, PDF {data['pdf_version']}")
const resp = await fetch("https://pdf.toolkitapi.io/v1/pdf/metadata", {
method: "POST",
headers: { "X-API-Key": "YOUR_KEY", "Content-Type": "application/json" },
body: JSON.stringify({ url: "https://toolkitapi.io/report.pdf" }),
});
const data = await resp.json();
console.log(data.metadata);
Response
{
"metadata": { "/Title": "Quarterly Report", "/Author": "Finance" },
"page_count": 10,
"pdf_version": "1.7",
"pdf": null,
"file_size": 244900
}
Writing metadata returns a new PDF
Pass an update object to rewrite metadata. The pdf field then contains a base64-encoded PDF with the changes applied; when only reading, pdf is null.
curl -X POST "https://pdf.toolkitapi.io/v1/pdf/metadata" \
-H "X-API-Key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://toolkitapi.io/report.pdf",
"update": {"title": "Q2 Investor Update", "author": "Toolkit API"}
}'
Extract tables¶
curl -G "https://pdf.toolkitapi.io/v1/pdf/table-extract" \
-H "X-API-Key: YOUR_KEY" \
--data-urlencode "url=https://toolkitapi.io/financials.pdf" \
--data-urlencode "pages=1-5"
import requests
resp = requests.get(
"https://pdf.toolkitapi.io/v1/pdf/table-extract",
params={"url": "https://toolkitapi.io/financials.pdf", "pages": "1-5"},
headers={"X-API-Key": "YOUR_KEY"},
timeout=180,
)
resp.raise_for_status()
data = resp.json()
for i, table in enumerate(data["tables"], start=1):
print(f"Table {i}: {len(table.get('rows', []))} rows")
print(f"{data['total_tables']} tables found across {data['pages_scanned']} pages")
const url = new URL("https://pdf.toolkitapi.io/v1/pdf/table-extract");
url.search = new URLSearchParams({ url: "https://toolkitapi.io/financials.pdf", pages: "1-5" });
const resp = await fetch(url, { headers: { "X-API-Key": "YOUR_KEY" } });
const data = await resp.json();
console.log(`${data.total_tables} tables across ${data.pages_scanned} pages`);
Response
{
"tables": [{ "page": 1, "rows": [["Region", "Revenue"], ["EMEA", "1,240"]] }],
"total_tables": 3,
"pages_scanned": 5
}
Structural info¶
curl -G "https://pdf.toolkitapi.io/v1/pdf/info" \
-H "X-API-Key: YOUR_KEY" \
--data-urlencode "url=https://toolkitapi.io/report.pdf"
import requests
resp = requests.get(
"https://pdf.toolkitapi.io/v1/pdf/info",
params={"url": "https://toolkitapi.io/report.pdf"},
headers={"X-API-Key": "YOUR_KEY"},
timeout=60,
)
resp.raise_for_status()
data = resp.json()
print(f"{data['page_count']} pages, encrypted={data['is_encrypted']}, PDF {data['pdf_version']}")
const url = new URL("https://pdf.toolkitapi.io/v1/pdf/info");
url.search = new URLSearchParams({ url: "https://toolkitapi.io/report.pdf" });
const resp = await fetch(url, { headers: { "X-API-Key": "YOUR_KEY" } });
const data = await resp.json();
console.log(`${data.page_count} pages, encrypted=${data.is_encrypted}`);
Response
{
"page_count": 10,
"file_size": 244900,
"pdf_version": "1.7",
"is_encrypted": false,
"title": "Quarterly Report",
"author": "Finance",
"creator": "LibreOffice",
"producer": "Skia/PDF",
"pages": [{ "page": 1, "width": 595.0, "height": 842.0 }]
}
Read or fill form fields¶
form-fields is POST because it can also fill AcroForm fields.
# Read
curl -X POST "https://pdf.toolkitapi.io/v1/pdf/form-fields" \
-H "X-API-Key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://toolkitapi.io/form.pdf"}'
# Fill
curl -X POST "https://pdf.toolkitapi.io/v1/pdf/form-fields" \
-H "X-API-Key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://toolkitapi.io/form.pdf", "fill": {"first_name": "Chris", "email": "[email protected]"}}'
import base64
import requests
resp = requests.post(
"https://pdf.toolkitapi.io/v1/pdf/form-fields",
headers={"X-API-Key": "YOUR_KEY"},
json={
"url": "https://toolkitapi.io/form.pdf",
"fill": {"first_name": "Chris", "email": "[email protected]"},
},
timeout=60,
)
resp.raise_for_status()
data = resp.json()
if data.get("pdf"):
with open("filled.pdf", "wb") as f:
f.write(base64.b64decode(data["pdf"]))
print(f"{data['total_fields']} fields")
const resp = await fetch("https://pdf.toolkitapi.io/v1/pdf/form-fields", {
method: "POST",
headers: { "X-API-Key": "YOUR_KEY", "Content-Type": "application/json" },
body: JSON.stringify({
url: "https://toolkitapi.io/form.pdf",
fill: { first_name: "Chris", email: "[email protected]" },
}),
});
const data = await resp.json();
console.log(`${data.total_fields} fields`);
Response
{
"fields": [{ "name": "first_name", "type": "/Tx", "value": "" }],
"total_fields": 2,
"pdf": "JVBERi0xLjQK...",
"file_size": 51200
}
OCR a scanned PDF¶
OCR is a GET endpoint with query parameters.
curl -G "https://pdf.toolkitapi.io/v1/pdf/ocr" \
-H "X-API-Key: YOUR_KEY" \
--data-urlencode "url=https://toolkitapi.io/scanned-doc.pdf" \
--data-urlencode "pages=1-2" \
--data-urlencode "language=eng" \
--data-urlencode "dpi=300" \
--data-urlencode "engine=auto"
import requests
resp = requests.get(
"https://pdf.toolkitapi.io/v1/pdf/ocr",
params={
"url": "https://toolkitapi.io/scanned-doc.pdf",
"pages": "1-2",
"language": "eng",
"dpi": 300,
"engine": "auto", # 'gpu', 'cpu', or 'auto'
},
headers={"X-API-Key": "YOUR_KEY"},
timeout=300,
)
resp.raise_for_status()
data = resp.json()
print(f"{data['total_word_count']} words ({data['language']})")
print(data["pages"][0]["text"][:500])
const url = new URL("https://pdf.toolkitapi.io/v1/pdf/ocr");
url.search = new URLSearchParams({
url: "https://toolkitapi.io/scanned-doc.pdf",
pages: "1-2",
language: "eng",
dpi: "300",
engine: "auto",
});
const resp = await fetch(url, { headers: { "X-API-Key": "YOUR_KEY" } });
if (!resp.ok) throw new Error(`OCR failed: ${resp.status}`);
const data = await resp.json();
console.log(`Extracted ${data.total_word_count} words`);
console.log(data.pages[0].text.slice(0, 500));
Response
{
"pages": [{ "page": 1, "text": "Invoice #4471...", "word_count": 182 }],
"total_pages": 10,
"extracted_pages": 2,
"total_word_count": 402,
"language": "eng"
}
Python SDK Examples¶
Extract text¶
from toolkitapi import PDF
with PDF(api_key="tk_...") as pdf:
result = pdf.extract_text(
url="https://toolkitapi.io/report.pdf",
pages="1-3",
)
print(result["total_word_count"])
print(result["pages"][0]["text"][:500])
Read metadata¶
from toolkitapi import PDF
with PDF(api_key="tk_...") as pdf:
result = pdf.metadata(url="https://toolkitapi.io/report.pdf")
print(result["metadata"])
Update metadata¶
from toolkitapi import PDF
with PDF(api_key="tk_...") as pdf:
result = pdf.metadata(
url="https://toolkitapi.io/report.pdf",
update={
"title": "Q2 Investor Update",
"author": "Toolkit API",
},
)
print(result["page_count"])
Extract tables¶
from toolkitapi import PDF
with PDF(api_key="tk_...") as pdf:
result = pdf.table_extract(
url="https://toolkitapi.io/financials.pdf",
pages="2-4",
)
print(result["total_tables"])
Read or fill form fields¶
from toolkitapi import PDF
with PDF(api_key="tk_...") as pdf:
fields = pdf.form_fields(url="https://toolkitapi.io/form.pdf")
print(fields["fields"])
filled = pdf.form_fields(
url="https://toolkitapi.io/form.pdf",
fill={"first_name": "Chris", "email": "[email protected]"},
)
print(filled["total_fields"])
Structural info¶
from toolkitapi import PDF
with PDF(api_key="tk_...") as pdf:
info = pdf.info(url="https://toolkitapi.io/report.pdf")
print(info["page_count"])
print(info["is_encrypted"])
OCR a scanned PDF¶
from toolkitapi import PDF
with PDF(api_key="tk_...") as pdf:
result = pdf.ocr(
url="https://toolkitapi.io/scanned.pdf",
pages="1-2",
language="eng",
dpi=300,
)
print(result["total_word_count"])
Parameter reference¶
Query params (GET routes)¶
| Parameter | Endpoint(s) | Type | Default | Description |
|---|---|---|---|---|
url |
all | string | — | Required. Public URL of the PDF (max 2048 chars) |
pages |
text, table-extract, ocr | string | null |
Page spec like 1-3,5. Omit for all pages |
language |
ocr | string | eng |
Tesseract language code (eng, fra, deu, …) |
dpi |
ocr | integer | 300 |
72–600. Render resolution before OCR |
engine |
ocr | string | auto |
gpu, cpu, or auto (try GPU, fall back to CPU) |
JSON body (POST routes)¶
| Parameter | Endpoint | Type | Description |
|---|---|---|---|
url |
metadata, form-fields | string | Required. Public URL of the PDF |
update |
metadata | object | String key/value pairs to write into the PDF metadata |
fill |
form-fields | object | Field name → value pairs to fill in the AcroForm |
Error cases¶
| Status | When it happens | Fix |
|---|---|---|
400 |
Could not parse the PDF — file is corrupt or not a PDF |
Verify the URL returns a real PDF |
400 |
Encrypted PDF without a password | Decrypt with /v1/pdf/protect first (action: "decrypt") |
400 |
Unknown form field name in fill |
Read fields first and match names exactly |
401 |
Missing or invalid X-API-Key |
Send the header |
405 |
You POSTed JSON to text/table-extract/info/ocr |
Those are GET — use query params |
422 |
dpi outside 72–600 |
Clamp to the documented range |
422 |
language not installed on the OCR worker |
Stick to common Tesseract codes, or check the supported list |
504 |
OCR or table extraction timed out | Narrow the pages range, or raise engine: "cpu" for predictability |
When to use OCR¶
Use OCR when the document is image-based or when normal text extraction returns little or no content.
- Try
/v1/pdf/textfirst. It's far faster and cheaper — many "scanned-looking" PDFs still carry a text layer. - Check the signal: if
total_word_countis near zero for a page range you know has content, that page is image-only. Re-run with/v1/pdf/ocr. dpiis the main quality lever.300is a good default; drop to200for speed on clean scans, raise to400+ for small or low-contrast type.- Limit
pageson first pass. OCR is the slowest route in the toolkit; scope to a couple of pages to validate quality before processing the whole file. - Prefer
engine: "auto"in production so you get GPU acceleration when available and still succeed on CPU-only workers.
Tips¶
- Only
metadataandform-fieldsaccept JSON bodies. Everything else on this page isGET— a JSONPOSTgets a405. metadataandform-fieldsreturn a base64pdffield only when you modify the document (update/fill). Pure reads returnpdf: null, so always null-check before decoding.infois the cheap pre-flight call. It gives youpage_count,is_encrypted, andpdf_versionwithout parsing content — use it to pick the right downstream route.pagesuses the same spec everywhere:"all"/omitted for everything, or1-3,5,8-10style ranges.table-extractis heuristic. It works well on ruled tables; for borderless layouts, checktables[].rowsand fall back to OCR plus manual parsing if structure is missing.- All requests take a public URL — the service fetches the document server-side, so local files must be uploaded somewhere reachable first.