Endpoint reference
POST /api/find-text
Search a born-digital PDF for a word, phrase or pattern and get every hit back with its page and its box in PDF points.
Born-digital means the PDF was made by software (an invoice system, a bank, a word processor), so the text is stored in it. This endpoint searches that text layer. It does not do OCR: a scanned page has no text to search, so it is searched as empty and listed in pagesWithoutText. It is the search companion to /api/extract-text, and a hit's position feeds /api/edit directly (recipe below).
Request
Method: POST. URL: https://pdfops.dev/api/find-text. Body: multipart/form-data.
| Field | Type | Required | Description |
|---|---|---|---|
pdf | File (PDF binary) | Yes | Exactly one PDF, up to 4 MB and 2,000 pages. The whole request must stay under 4.5 MB, Vercel's platform request limit. |
query | String | Yes | The text to find, or a pattern when regex=true. At most 200 characters. In a literal query, runs of spaces, tabs and non-breaking spaces count as one space, as they do in the line text. |
regex | String | No | true or false (default). Treat query as a regular expression. |
case_sensitive | String | No | true or false (default). Matching is case-insensitive by default. |
whole_word | String | No | true or false (default). Only report a match with no letter, digit, underscore or combining mark directly before or after it, so cat is not found inside category. |
pages | String | No | Pages to search, 1-based: 1-3,5,8-. Default: every page. At most 200 pages are searched per call. |
max_hits | Integer | No | 1 to 1,000, default 100. The scan stops once more hits than this exist. |
password | String | No | Opens a PDF that needs a user password. Not needed for owner-locked files with an empty user password. |
The optional X-API-Key header works as on /api/merge: no header is anonymous, 100 requests per IP per month; a valid key uses your tier's quota; an invalid or revoked key returns 401 invalid_api_key. A successful (2xx) call counts 1 request, however many pages it searches. Check consumption with GET /api/usage.
Response
On success: 200 OK, Content-Type: application/json. Searching INV-\d{4} (regex=true) in a three-page invoice file with max_hits=2, trimmed to the first hit:
{
"count": 2,
"truncated": true,
"hits": [
{
"page": 1,
"text": "INV-1001",
"line": "INVOICE INV-1001",
"x": 164.37, "y": 728, "width": 113.6, "height": 26
},
...
],
"pagesWithoutText": [],
"pagesScanned": 1,
"nextPage": 2
}
| Key | Description |
|---|---|
count | Number of hits returned. |
truncated | true when the scan stopped before searching every selected page: more hits than max_hits, the hit output cap, the matching work budget, more than 200 pages selected, or the pages read reaching the output cap /api/extract-text has for the same file. While nextPage is not null, continue from it. If it is null and pagesSkipped is present, hits on that page beyond max_hits were dropped and cannot be fetched; raise max_hits or narrow the query. |
hits[].page | 1-based page number. |
hits[].text | The matched text as it appears on the page (original case). |
hits[].line | The line the match is on, the same lines /api/extract-text reports. Cut to 200 characters either side of the match when longer. |
hits[].line_truncated | Present, as true, only when line was cut. |
hits[].x, y, width, height | The hit's box in PDF points; see Coordinates. |
pagesWithoutText | Fully searched pages with no text layer, usually scans. |
pagesScanned | How many of the selected pages, in order, were searched in full. Always present. |
nextPage | The first page number not fully searched, or null when the scan finished. See Resuming. |
pagesSkipped | Only when present: pages given up on, as [{ "page": 7, "reason": "max_hits" }]. Reasons: max_hits, output_cap, work_budget, page_output_cap. See Limits. |
linesSkipped | Only when greater than 0: lines over 10,000 characters, which are not searched. |
A PDF with no text layer returns count: 0 and the page numbers in pagesWithoutText. On any failure: 4xx or 500, Content-Type: application/json, body is { "error": "<code>", "details": "<explanation>" }.
Coordinates
The box is in the same frame as lines on /api/extract-text and as /api/edit: PDF points, 72 to the inch, measured from the bottom-left corner of the page as a viewer shows it, after any rotation or crop box. x and width are the matched text itself, not the whole line. y is the text baseline and height is the font size, so the box spans y to y + height upward. Hits on rotated (non-horizontal) text are not found; a page whose /Rotate makes the text read upright counts as horizontal and works.
Recipe: stamp at a hit
Find the text, then send an /api/edit item at the hit. This writes <- check just after the amount USD 450.50:
# 1. find it, keep the first hit
HIT=$(curl -s -X POST https://pdfops.dev/api/find-text \
-F "pdf=@invoices.pdf" -F "query=USD 450.50" -F "pages=1" | jq '.hits[0]')
# {"page":1,"text":"USD 450.50","x":480,"y":570,"width":54.47,"height":10, ...}
# 2. stamp 8 points to the right of it, on the same baseline, at the same size
ITEMS=$(echo "$HIT" | jq -c '[{type:"text", page:.page, x:(.x + .width + 8), y:.y, size:.height, text:"<- check"}]')
curl -X POST https://pdfops.dev/api/edit \
-F "pdf=@invoices.pdf" -F "items=$ITEMS" -o checked.pdf
To put text above the hit instead, use y + height (plus a little air); to put it before, use x minus the stamp's width. /api/edit text items are WinAnsi only and have no rectangle item, so this marks a hit with text or an image rather than a highlight.
Regular expressions
With regex=true, query is a pattern in a subset of JavaScript syntax, matched case-insensitively unless case_sensitive=true. Your pattern is not run on a backtracking regex engine, so no pattern can make the search slow by backtracking; the matching work per request is capped (see Limits), and a pattern that is too large is rejected.
Supported:
- Literal characters, and these escapes:
\. \\ \/ \^ \$ \* \+ \? \( \) \[ \] \{ \} \|,\n \r \t \v \f \0,\xHH,\uHHHH,\u{H...},\cX. .(any character except a line break), classes[...]and[^...]with ranges, and\d \w \s \D \W \S(inside classes too).- Word boundaries
\band\B; line anchors^and$(matching is per line). - Groups
( )and(?: )(neither captures anything), and alternation|. - Quantifiers
?*+{m}{m,}{m,n}and their lazy forms (*?,{m,n}?, and so on). Repeat counts are capped at 1,000, and nesting of repeats that can match nothing at 4 levels.
Matching follows JavaScript's u-flag rules: the leftmost match wins, then the usual priority order. Matches of zero length are never reported.
Rejected with 400 invalid_regex and a message naming the construct: backreferences (\1, \k<name>), lookahead ((?=, (?!), lookbehind ((?<=, (?<!), named groups, Unicode property escapes (\p{...}), and inline flags such as (?i) (use case_sensitive instead). Anything JavaScript's own u mode refuses is also rejected: a lone {, } or ], a quantifier on an anchor or \b, an unterminated group or class, a bad escape, a range out of order. A pattern over 200 characters returns query_too_long; one that compiles to more than 5,000 instructions is rejected as invalid_regex.
Resuming with nextPage
A page is searched whole or not at all. When the scan stops early, truncated is true, pagesScanned says how many selected pages were searched in full, and nextPage is the first page that was not. Repeat the request with pages=<nextPage>- (intersect that with your own page filter if you have one) and you continue with no page gaps and no repeated hits. Repeat until nextPage is null.
One case cannot be resumed: if a single page holds more hits than max_hits, the response has truncated: true but nextPage is null (when that page is the last one searched) and the page is listed in pagesSkipped with reason max_hits. Do not send pages=null-. Raise max_hits or narrow the query instead (see the example below).
Limits
- Hits:
max_hitsup to 1,000 (default 100). The hits in one response are also capped at about 1 million characters of JSON. - Pages: 200 pages searched per call, and no more pages than
/api/extract-textwould return for the same file (its 4 million character output cap). Continue withnextPage. - Matching work budget: each request gets a fixed amount of matching work, 50 million steps, shared by all its pages. When it is spent the scan stops and returns
truncated: true. Spending all of it took about a second on the slowest pattern shape on our test machine (0.65 to 1.2 s over 7 runs); we have not measured it on the deployed runtime. On our sample documents a whole search, parsing included, took 150 to 390 ms. - Long lines: a line over 10,000 characters is not searched. The count is reported in
linesSkipped. - Query: 200 characters.
- First page trips a limit: a page that stops the scan is normally dropped from the response and retried first next time. If it is the first page of the request, retrying would stop at the same place, so its hits so far are kept, it is listed in
pagesSkippedwith the reason, andnextPagemoves past it.
Known limits
- Hits beyond
max_hitson a single page cannot be retrieved by any request: there is no offset inside a page. The page is listed inpagesSkipped. - A match never spans lines. A phrase that wraps onto the next line, or crosses a wide gap between columns or table cells, is not found, because a "line" is one baseline segment split at wide gaps, as in
/api/extract-text. - Horizontal text only; rotated text is ignored.
- Inside a run of mixed left-to-right and right-to-left text, the box of a hit can be mirrored (it lands on the wrong side of the run). Phrases in right-to-left scripts are matched in visual order, not reading order.
- Inside a longer run of text, a hit's box is estimated from character-width weights, so it can be off by several points. Measured on our fixtures (Helvetica, 10 and 26 pt): the left edge was off by 0 to 4.5 pt (4.5 pt is about one character at 10 pt) and the width by up to 5.9 pt. A hit that covers a whole run, and a box edge at the start or end of a run, are exact.
- Text comes from the PDF's own font mappings, so a PDF made without them gives garbled text and nothing matches what you see.
Error codes
| Error code | Status | Trigger |
|---|---|---|
invalid_multipart | 400 | Request body could not be parsed as multipart/form-data. |
missing_pdf | 400 | The request does not have exactly one pdf file field. |
missing_query | 400 | query is absent or empty. |
query_too_long | 400 | query is over 200 characters. |
invalid_regex | 400 | With regex=true: the pattern is invalid or uses an unsupported construct. details names it. |
invalid_parameter | 400 | regex, case_sensitive or whole_word is not true or false, or max_hits is not an integer from 1 to 1,000. |
pdf_too_large | 400 | The pdf file is over 4 MB. |
invalid_pdf | 400 | The PDF could not be parsed (corrupt, or not a PDF). |
encrypted_pdf | 400 | The PDF needs a password we were not given. Send it as the password form field. |
decompressed_too_large | 400 | Streams inside the PDF decompress to over 32 MB. |
too_many_pages | 400 | The PDF has over 2,000 pages. |
invalid_pages | 400 | pages is not a valid page spec or names a page past the end. |
request_too_large | 413 | The whole request body is over 4.5 MB (Vercel's platform request limit). Rejected before anything is parsed. |
invalid_api_key | 401 | An X-API-Key header was sent but the key is unknown or revoked. Get a fresh key at /pricing. |
rate_limited | 429 | The anonymous per-IP limit (100/month) or your key's monthly quota is used up. Retry-After gives seconds until next calendar month. |
Examples
The outputs below are real, from a three-page invoice file (invoices.pdf), trimmed to the useful keys. Literal search, case-insensitive:
curl -X POST https://pdfops.dev/api/find-text \
-F "pdf=@invoices.pdf" -F "query=payment" \
-H "X-API-Key: pdfops_live_..." # optional, raises your quota to your tier
{"count":6,"truncated":false,"hits":[
{"page":1,"text":"Payment","x":54,"y":700,"width":37.98,"height":10,"line":"Payment due: 2026-12-01"},
{"page":1,"text":"payment","x":223.36,"y":680,"width":36.35,"height":10,"line":"Please reference INV-1001 with your payment. Invoice total below."},
...],"pagesWithoutText":[],"pagesScanned":3,"nextPage":null}
Whole words only, on page 1. invoice matches INVOICE and Invoice as words:
curl -X POST https://pdfops.dev/api/find-text \
-F "pdf=@invoices.pdf" -F "query=invoice" -F "whole_word=true" -F "pages=1"
{"count":2,"truncated":false,"hits":[
{"page":1,"text":"INVOICE","x":54,"y":728,"width":103.08,"height":26,"line":"INVOICE INV-1001"},
{"page":1,"text":"Invoice","x":265.32,"y":680,"width":30.64,"height":10,"line":"Please reference INV-1001 with your payment. Invoice total below."}
],"pagesWithoutText":[],"pagesScanned":1,"nextPage":null}
Every invoice number on pages 1 and 2, by pattern (use single quotes so the shell leaves the backslash alone):
curl -X POST https://pdfops.dev/api/find-text \
-F "pdf=@invoices.pdf" -F 'query=INV-\d{4}' -F "regex=true" -F "pages=1-2" \
| jq -c '.hits[] | [.page, .text, .y]'
[1,"INV-1001",728]
[1,"INV-1001",680]
[2,"INV-1002",728]
[2,"INV-1002",680]
A page range, from page 2 to the end:
curl -X POST https://pdfops.dev/api/find-text \
-F "pdf=@invoices.pdf" -F "query=Edge deployment" -F "pages=2-" \
| jq -c '{count, pagesScanned, nextPage, pages: [.hits[].page]}'
{"count":2,"pagesScanned":2,"nextPage":null,"pages":[2,3]}
Resuming. With max_hits=2 the first call stops after page 1 and says where to continue:
curl -X POST https://pdfops.dev/api/find-text \
-F "pdf=@invoices.pdf" -F 'query=INV-\d{4}' -F "regex=true" -F "max_hits=2" \
| jq -c '{count, truncated, pagesScanned, nextPage}'
{"count":2,"truncated":true,"pagesScanned":1,"nextPage":2}
Repeat with pages=2- (the nextPage value followed by a dash):
curl -X POST https://pdfops.dev/api/find-text \
-F "pdf=@invoices.pdf" -F 'query=INV-\d{4}' -F "regex=true" -F "max_hits=2" -F "pages=2-" \
| jq -c '{count, truncated, pagesScanned, nextPage, hits: [.hits[] | [.page, .text]]}'
{"count":2,"truncated":true,"pagesScanned":1,"nextPage":3,"hits":[[2,"INV-1002"],[2,"INV-1002"]]}
Truncated with no nextPage: one page with more hits than max_hits (here max_hits=1, two matches on page 1). The extra hit is not retrievable by resuming:
curl -X POST https://pdfops.dev/api/find-text \
-F "pdf=@invoices.pdf" -F 'query=INV-\d{4}' -F "regex=true" -F "pages=1" -F "max_hits=1"
{"count":1,"truncated":true,"hits":[
{"page":1,"text":"INV-1001","x":164.37,"y":728,"width":113.6,"height":26,"line":"INVOICE INV-1001"}
],"pagesWithoutText":[],"pagesScanned":0,"nextPage":null,"pagesSkipped":[{"page":1,"reason":"max_hits"}]}
An unsupported pattern, (a)\1 with regex=true:
{"error":"invalid_regex","details":"\"query\" is not a supported regular expression: backreferences are not supported"}
Keyless calls work: 100 requests per IP per month with no key.
Using this for real? A free API key raises the keyless 100 calls per IP to 250 requests a month, with no card.
Code examples
Have an API key? Add an X-API-Key header to any request. It is optional, and it raises your quota from 100/IP/month to your tier's.
JavaScript (Node.js 22+) — built-in fetch + FormData
import { readFile } from 'node:fs/promises';
const pdf = new Blob([await readFile('invoices.pdf')], { type: 'application/pdf' });
const headers = {};
if (process.env.PDFOPS_API_KEY) headers['X-API-Key'] = process.env.PDFOPS_API_KEY; // optional
const hits = [];
let pages = null; // null = all pages
do {
const fd = new FormData();
fd.append('pdf', pdf, 'invoices.pdf');
fd.append('query', 'INV-\\d{4}');
fd.append('regex', 'true');
if (pages) fd.append('pages', pages);
const res = await fetch('https://pdfops.dev/api/find-text', {
method: 'POST',
headers,
body: fd,
});
if (!res.ok) {
const err = await res.json();
throw new Error(`PDFops find failed: ${err.error}: ${err.details}`);
}
const body = await res.json();
hits.push(...body.hits);
pages = body.nextPage ? `${body.nextPage}-` : null;
} while (pages);
console.log(hits.map((h) => `${h.page}: ${h.text}`));
Python — requests
import os, requests
hits, pages = [], None # None = all pages
while True:
data = {"query": r"INV-\d{4}", "regex": "true"}
if pages:
data["pages"] = pages
with open("invoices.pdf", "rb") as pdf:
res = requests.post(
"https://pdfops.dev/api/find-text",
headers={"X-API-Key": os.environ.get("PDFOPS_API_KEY", "")}, # optional
files={"pdf": pdf},
data=data,
)
res.raise_for_status()
body = res.json()
hits += body["hits"]
if body["nextPage"] is None:
break
pages = f"{body['nextPage']}-"
for h in hits:
print(h["page"], h["text"], h["x"], h["y"])
From an AI agent (MCP)
The hosted MCP server at https://pdfops.dev/api/mcp exposes this as the pdf_find_text tool. It takes the PDF as an https:// URL or a data:application/pdf;base64,… URI and the same search options in snake_case, and returns next_page for resuming. See PDFops for AI agents.
Behavioral notes
- Read-only. The PDF is not changed and nothing is stored.
- No OCR. Scanned pages have no text layer; they are reported in
pagesWithoutText. - One line at a time. Matches never span lines; see Limits.
- Limits: 4 MB per PDF, 200 pages, 200 query characters and 1,000 hits per call, 4.5 MB per request (Vercel's platform limit).
FAQ
How do I search a PDF for text with an API?
POST the PDF as the pdf field of a multipart request to https://pdfops.dev/api/find-text, with the text in query. The response lists every hit with its page number, the matched text, the line it is on, and a box in PDF points. Add regex=true to treat query as a pattern, whole_word=true to skip matches inside longer words, and pages to limit the search.
Can I search a PDF with a regular expression?
Yes, with regex=true. It accepts a documented subset of JavaScript regular expression syntax: literals, character classes, dot, anchors, word boundaries, groups, alternation and the usual quantifiers, including lazy ones. Backreferences, lookahead, lookbehind, named groups, Unicode property escapes and inline flags are rejected with 400 invalid_regex. Matching is case-insensitive unless you send case_sensitive=true.
How do I mark or stamp where the text was found?
Each hit has x, y, width and height in the same frame as /api/edit: points from the bottom-left of the page as displayed, with y on the text baseline. Send an /api/edit text item at x plus width, and the same y, to write beside the hit.
Does it find text in scanned PDFs?
No. A scanned page is a picture of text with no text layer, and this endpoint does not run OCR. Such pages are searched as empty and listed in pagesWithoutText, so you can route them elsewhere.
What if there are more hits than fit in one response?
The response carries truncated: true and nextPage, the first page not fully searched. While nextPage is not null, repeat the request with pages set to that page followed by a dash, such as 4-, and you continue with no gaps and no repeated hits. If truncated is true but nextPage is null, a single page holds more hits than max_hits (it is listed in pagesSkipped): the extra hits on that page cannot be retrieved, so raise max_hits or narrow the query.
Related: Extract text and tables · Add text and images at a position · List form fields.
Get a free API key. Keyless calls get 100 requests per IP per month; a free key raises that to 250, with no card. Enter your email and the key arrives in your inbox.