, dataJson, optionsJson]}`; the result is the `.docx` as base64).
## HTML templates [#html-templates]
```kotlin
val html = """
Invoice {{number}}
{{customer.name}}, due {{due | date:"dd/MM/yyyy"}}
{{#each items}}| {{@number}} | {{description}} | {{price | currency:"EUR"}} |
{{/each}}
{{#if paid}}Paid
{{else}}Total due: {{total | currency:"EUR"}}
{{/if}}
"""
NexPdfDocument.fromHtmlTemplate(html, data.toString(), null).use { doc ->
File(filesDir, "invoice.pdf").writeBytes(doc.saveBytes())
}
```
Values are HTML-escaped; `{{{raw}}}` (three braces) inserts HTML as it is.
## PDF templates [#pdf-templates]
`fillTemplate(dataJson, optionsJson)` fills an existing PDF in place: AcroForm fields by name
(dotted names such as `customer.name` follow the data tree) and placeholders in the page's text
lines. It returns the number of fields and text lines filled, or `-1` on failure.
```kotlin
NexPdfDocument.openBytes(formTemplate).use { doc ->
val filled = doc.fillTemplate(data.toString(), """{"flatten":true}""")
check(filled >= 0) { NexPdfJni.lastError() }
File(filesDir, "filled.pdf").writeBytes(doc.saveBytes())
}
```
For a raw handle the calls are `NexPdfJni.templateDocxToPdf(template, dataJson, optionsJson)` and
`templateHtmlToPdf(html, dataJson, optionsJson)` (a new handle, `0` on failure; free it with
`NexPdfJni.free`), `templateDocxFill(template, dataJson)` and
`templateFillPdf(handle, dataJson, optionsJson)`. `null` data is `{}`.
Rows that no longer fit after filling break onto new pages. The text rows and graphics at the top
and bottom edge of the page can be marked as a header and a footer, which repeat in place on every
page instead of flowing with the content:
| Option | Default | Meaning |
|---|---|---|
| `header_height` | `0` (no header) | Points from the top edge that hold the header |
| `footer_height` | `72` | Points from the bottom edge that hold the footer |
With the default, a text row that starts in the bottom 72 pt (one inch) of the page is treated as
footer and repeated in place on every page; it does not flow with the content. Set
`"footer_height":0` to turn the footer zone off: no row is a footer, and flowing rows may then run
to the bottom edge. A small value such as `36` keeps a margin without catching rows.
Without `footer_height` the flow keeps a bottom margin of 36 to 72 pt. Rows taller than a page are
cut between lines. Graphics after the last row move with the end of the content, onto a page of
their own when they do not fit.
Text is shaped with OpenType and ordered with Unicode bidi; right-to-left text without explicit
alignment starts at the right. The `font` option picks the font for characters the page font cannot
show: `"bundled"` (the default), `"keep"`, a path such as `"/path/to/font.ttf"`, `{"path": ...}` or
`{"data": ""}`. Right-to-left text uses that font even when the page font has codes for it,
unless `font` is `"keep"`.
## Syntax [#syntax]
| Tag | Meaning |
|---|---|
| `{{customer.name}}`, `{{items.0.price}}` | A value from the data |
| `{{total \| currency:"EUR"}}` | A value through a formatter |
| `{{#each items}}…{{/each}}` | Repeats for each item; inside, `this`, `@index`, `@number`, `@first`, `@last`, `@key`, `../name` and `@root.name` |
| `{{#if paid}}…{{else}}…{{/if}}` | Condition; comparisons such as `{{#if total > 1000}}` work |
| `{{#unless paid}}…{{/unless}}` | Inverse condition |
| `{{% logo}}` | An image from the data |
| `{{! note}}` | A comment, not printed |
Formatters: `upper`, `lower`, `capitalize`, `trim`, `currency:"EUR"` (optionally with a locale,
`currency:"EUR","de"`), `number[:decimals[,"locale"]]`, `percent[:decimals]`, `round[:decimals]`,
`date:"yyyy-MM-dd"` (ISO dates or Unix seconds), `default:"text"`, `join[:", "]` and `length`.
An image value is base64 text or a `data:` URL of a PNG, JPEG or GIF, or an object
`{"data": "...", "width": 120, "height": 40}` with a size in points:
```kotlin
import android.util.Base64
val logo = assets.open("logo.png").use { it.readBytes() }
data.put("logo", JSONObject().put("data", Base64.encodeToString(logo, Base64.NO_WRAP)).put("width", 120))
```
## Options [#options]
| Option | Default | Meaning |
|---|---|---|
| `strict` | `false` | A field missing from the data fails the call, naming the field and where the tag is. Otherwise it renders empty |
| `locale` | `en` | Default locale of `currency` and `number` (`en`, `de`, `fr`, `pt-BR`, …) |
| `flatten` | `false` | PDF templates: flatten the form after filling |
| `fields` | `true` | PDF templates: fill AcroForm fields |
| `text` | `true` | PDF templates: replace placeholders in the page text |
| `header_height`, `footer_height`, `font` | | PDF templates: see [PDF templates](#pdf-templates) |
| `base_dir` | | HTML templates: the folder relative image paths are read from |
Syntax errors (an unclosed block, an unknown formatter) always fail. `fromDocxTemplate` and
`fromHtmlTemplate` then throw `IllegalArgumentException` with the engine's message; the other calls
return their failure value and `NexPdfJni.lastError()` has the message:
```kotlin
try {
NexPdfDocument.fromHtmlTemplate("{{missing}}
", "{}", """{"strict":true}""").close()
} catch (e: IllegalArgumentException) {
Log.w("NexPDF", e.message ?: "") // names the field and the tag location
}
```
# Word-level comparison (/docs/android/guides/text-comparison)
Comparison works without a key (`viewer` module).
[Compare and optimise](/docs/android/guides/compare-and-optimize) shows which pages changed and by
how many pixels. Word-level comparison tells you **what text** changed: words inserted, deleted,
replaced and moved, with their positions on both versions.
## List the changes [#list-the-changes]
`old.compareTextJson(new, optionsJson)` compares the document it is called on (the old version)
with `new` (`NexPdfJni.compareTextJson(oldHandle, newHandle, optionsJson)` for raw handles). An
empty string means the call failed; `NexPdfJni.lastError()` says why.
```kotlin
import com.nexdevit.nexpdf.NexPdfDocument
import com.nexdevit.nexpdf.NexPdfJni
import org.json.JSONObject
NexPdfDocument.openBytes(v1Bytes).use { old ->
NexPdfDocument.openBytes(v2Bytes).use { new ->
val diff = JSONObject(old.compareTextJson(new, null))
val s = diff.getJSONObject("summary")
Log.i("NexPDF", "%.1f%% similar: +%d -%d words, %d moves".format(
s.getDouble("similarity") * 100, s.getInt("words_inserted"), s.getInt("words_deleted"), s.getInt("moved")))
val changes = diff.getJSONArray("changes")
for (i in 0 until changes.length()) {
val c = changes.getJSONObject(i)
Log.i("NexPDF", "${c.getString("type")} '${c.opt("old_text")}' -> '${c.opt("new_text")}' ${c.opt("old_page")} ${c.opt("new_page")}")
}
}
}
```
Each change has `type` (`inserted`, `deleted`, `replaced` or `moved`), `old_text`, `new_text`,
`old_page`, `new_page`, and `old_rects` / `new_rects` (`{"page", "rect": [llx, lly, urx, ury]}`) to
highlight it. The `summary` counts `words_old`, `words_new`, `words_equal`, the changes by type, the
words inserted, deleted and moved, `similarity` (0 to 1) and `truncated`.
Words hyphenated across lines are rejoined before comparing, and compound hyphens are kept
(`self-driving`, `long-term`).
## Options [#options]
| Option | Default | Meaning |
|---|---|---|
| `ignore_case` | `false` | Treat upper and lower case as equal |
| `ignore_punctuation` | `false` | Ignore punctuation differences |
| `detect_moves` | `true` | Report text that moved as `moved` instead of deleted plus inserted |
| `min_move_words` | `3` | Shortest run of words reported as a move |
| `align` | `document` | `document` compares the whole text; `index` compares page 1 with page 1, and so on |
| `page_map` | | Explicit page pairs, `[[old_page, new_page], …]` |
## An annotated PDF of the changes [#an-annotated-pdf-of-the-changes]
`old.compareAnnotate(new, optionsJson)` returns a new PDF with highlight annotations: deleted words
in red on the old pages, inserted words in green on the new pages, moved text in blue. An empty
array means the call failed.
```kotlin
val pdf = NexPdfDocument.openBytes(v1Bytes).use { old ->
NexPdfDocument.openBytes(v2Bytes).use { new ->
old.compareAnnotate(new, """{"output":"side_by_side","author":"Review bot"}""")
}
}
check(pdf.isNotEmpty()) { NexPdfJni.lastError() }
File(filesDir, "changes.pdf").writeBytes(pdf)
```
It takes the options above plus `output` (`both`: old pages then new pages, the default; `old`;
`new`; or `side_by_side`: one wide page per pair with the marks drawn in), `author`, and
`deleted_color`, `inserted_color` and `moved_color` (`#RRGGBB`). Open the result with
`NexPdfDocument.openBytes(pdf)` to work with it further, or show it in the
[reader](/docs/android/reader).
# Text extraction (/docs/android/guides/text-extraction)
Text extraction, Markdown export and the offline assistant are part of the `viewer` module and work
without a key.
## Plain text of a page [#plain-text-of-a-page]
`pageText(pageIndex)` returns the text of a page in reading order, with the layout reconstructed
into lines and paragraphs:
```kotlin
import com.nexdevit.nexpdf.NexPdfDocument
val text = NexPdfDocument.openBytes(bytes).use { doc ->
(0 until doc.pageCount()).joinToString("\n\n") { doc.pageText(it) }
}
```
## The whole document as Markdown [#the-whole-document-as-markdown]
`toMarkdown()` keeps headings, lists and tables, which makes it a good input for search indexes and
language models:
```kotlin
val markdown = doc.toMarkdown()
```
## Text blocks with positions [#text-blocks-with-positions]
`NexPdfJni.pageBlocksJson(handle, pageIndex)` returns the text blocks of a page with their font size
and rectangle in PDF points:
```kotlin
val blocks = JSONArray(NexPdfJni.pageBlocksJson(doc.handle(), 0))
for (i in 0 until blocks.length()) {
val b = blocks.getJSONObject(i)
Log.i("NexPDF", "%5.1fpt %s".format(b.getDouble("size"), b.getString("text").take(60)))
}
```
Each block has `text`, `size`, `llx`, `lly`, `urx` and `ury`.
## Passages for a language model [#passages-for-a-language-model]
`NexPdfJni.askDocument(handle, question, k, maxChars)` ranks the passages of the document against a
question, offline, and returns the `k` best with a page-tagged context you can send to a language
model. `maxChars` `0` uses the default limit (200,000 characters).
```kotlin
val result = JSONObject(NexPdfJni.askDocument(doc.handle(), "When does the contract end?", 5, 0))
val passages = result.getJSONArray("passages")
for (i in 0 until passages.length()) {
val p = passages.getJSONObject(i)
Log.i("NexPDF", "${p.getInt("page")} ${p.getDouble("score")} ${p.getString("text").take(80)}")
}
val prompt = "Answer from this document:\n${result.getString("context")}\n\nQuestion: When does the contract end?"
```
## Scanned documents [#scanned-documents]
Pages that are images have no text to extract. Run [OCR](/docs/android/guides/ocr) first to add a
searchable text layer.
## Related [#related]
- [Search](/docs/android/guides/search)
- [Conversion](/docs/android/guides/conversion) for HTML, JSON, XML and CSV output
# XFA forms (/docs/android/guides/xfa-forms)
XFA forms need the `forms` module (Indie tier and above).
XFA (XML Forms Architecture) forms keep their layout and data in XML inside the PDF. Many
government and bank forms use them, and many viewers no longer open them. NexPDF reads both kinds:
- **static** XFA, where the PDF also has AcroForm fields: the XFA data and the AcroForm fields are
kept in step, so filling either side updates the other;
- **dynamic** XFA, where the pages are laid out from the XFA template: NexPDF lays the template out
into ordinary PDF pages with AcroForm fields.
The `NexPdfDocument` methods below are also `NexPdfJni` methods that take `doc.handle()` first.
They return `-1` (or an empty string) on failure, with the reason in `NexPdfJni.lastError()`.
## Inspect a form [#inspect-a-form]
```kotlin
import com.nexdevit.nexpdf.NexPdfDocument
import com.nexdevit.nexpdf.NexPdfJni
import org.json.JSONObject
NexPdfDocument.openBytes(taxForm).use { doc ->
val info = JSONObject(doc.xfaInfoJson())
Log.i("NexPDF", "${info.getBoolean("has_xfa")} ${info.getBoolean("dynamic")} " +
"${info.getInt("field_count")} ${info.getInt("acroform_field_count")}")
}
```
The result has `has_xfa`, `dynamic`, `field_count`, `acroform_field_count`, `data_value_count`
and the list of XDP `packets`.
## Export and import data [#export-and-import-data]
`xfaExportData(format)` returns the data as `xml` (the data document, `…`, the
default with `null`) or as flat `json` (`{"path": "value"}`). It returns an empty string when the
document has no XFA.
```kotlin
val values = JSONObject(doc.xfaExportData("json"))
Log.i("NexPDF", values.optString("form1.customer.name"))
val imported = doc.xfaImportData("""{"form1.customer.name":"Ana Silva","form1.item[1].qty":"3"}""", "json")
check(imported >= 0) { NexPdfJni.lastError() }
File(filesDir, "filled.pdf").writeBytes(doc.saveBytes())
```
`xfaImportData(data, format)` returns the number of values imported. XML replaces the data; JSON
(flat paths or nested objects) sets the given values and creates repeated groups as needed. Data
paths are dotted names with an index for repeated siblings (`form1.item[1].qty`).
## Convert, flatten or remove [#convert-flatten-or-remove]
| Call | Result |
|---|---|
| `xfaToAcroform()` | A plain AcroForm PDF without XFA. Dynamic forms are laid out into new pages. Returns the number of fields |
| `xfaFlatten()` | Converts and flattens: a plain PDF with the values drawn. Returns the number of flattened widgets |
| `xfaRemove()` | Removes XFA and keeps the existing AcroForm fields and pages. Returns 1, or 0 when there was no XFA |
```kotlin
NexPdfDocument.openBytes(taxForm).use { doc ->
val xml = assets.open("data.xml").bufferedReader().use { it.readText() }
doc.xfaImportData(xml, "xml")
check(doc.xfaToAcroform() >= 0) { NexPdfJni.lastError() } // now fill it like any AcroForm
File(filesDir, "tax-form-acroform.pdf").writeBytes(doc.saveBytes())
}
```
AcroForm fields made from XFA are named by their SOM path (`form1[0].item[1].qty[0]`). See
[Forms](/docs/android/guides/forms) to fill and flatten them.
## Scripts, pictures and fonts [#scripts-pictures-and-fonts]
FormCalc (built-in interpreter) and JavaScript scripts run against an XFA object model
(`xfa.resolveNode`, `this.rawValue`, `xfa.host`, `instanceManager`, script objects). The
`initialize`, `calculate` (repeated to a fixed point) and `validate` events run when data is
imported and when the form is converted or flattened; conversion also runs `ready`, `docReady`,
`prePrint`, page-area `layoutReady` and conditional breaks.
- Picture clauses are applied (display, edit and data pictures for dates, times, numbers, currency
and text, with built-in locales).
- The layout draws rich text, images (embedded, `href` and data-bound), table column widths,
right-to-left flow, leaders and trailers, overflow targets, conditional breaks and `occur` on
page areas. Data binding supports `once`, `none`, `global` and `dataRef` with full SOM.
- Text is drawn in embedded Unicode fonts (the bundled Liberation fonts, then registered fallback
fonts), with OpenType shaping and Unicode bidi. When no font has the glyphs, a warning says to
register one.
- Barcode fields are drawn as vector barcodes: QR, Data Matrix, Aztec, PDF417, Code 128 (A/B/C,
GS1-128), Code 39, Code 93, EAN-13, EAN-8, UPC-A, UPC-E, Interleaved 2 of 5, Codabar and
Telepen.
After conversion, text fields keep the value they show (display picture applied, such as
`1,234.50` or `29 Nov 2026`) as their value, and the form no longer asks viewers to redraw
appearances, so viewers that draw text fields from the value show the same text. Passwords and
values longer than the field's maximum length keep the raw value. The raw data values stay in the
XFA data only until conversion: export the data first if you need them. Static XFA keeps raw
values when filled fields are synced.
## Calls without a typed method [#calls-without-a-typed-method]
`NexPdfJni` has no typed method for `xfa_to_acroform_json` (conversion with options and a report),
`xfa_run_scripts_json` (run `initialize`, `calculate` and `validate` and store the calculated values)
or `register_fallback_font` (a TrueType, OpenType or `.ttc` font for CJK, Arabic and other scripts,
process-wide). Reach them through `NexPdfJni.invoke`, the whole C API as one JSON call. Its
document handles are its own, not the `long` handles of `NexPdfDocument`, so open the document
through `invoke` too:
```kotlin
import android.util.Base64
import org.json.JSONArray
fun call(fn: String, vararg args: Any?): Any? {
val request = JSONObject().put("fn", fn).put("args", JSONArray(args.toList()))
val response = JSONObject(NexPdfJni.invoke(request.toString()))
if (!response.getBoolean("ok")) error(response.getString("error"))
return response.opt("result")
}
fun b64(bytes: ByteArray) = Base64.encodeToString(bytes, Base64.NO_WRAP)
call("register_fallback_font", b64(assets.open("NotoSansCJK-Regular.ttc").readBytes()))
val h = call("open_bytes", b64(taxForm))
try {
val run = JSONObject(call("xfa_run_scripts_json", h) as String)
Log.i("NexPDF", "${run.get("data_changed")} ${run.get("validation_errors")}")
val r = JSONObject(call("xfa_to_acroform_json", h, """{"scripts":true,"flatten":false}""") as String)
Log.i("NexPDF", "${r.get("fields")} fields on ${r.get("pages")} pages, ${r.get("warnings")}")
val pdf = Base64.decode(call("save_bytes", h) as String, Base64.DEFAULT)
File(filesDir, "tax-form-acroform.pdf").writeBytes(pdf)
} finally {
call("close", h)
}
```
The conversion report has `flattened`, `fields`, `pages`, `warnings` and `validation_errors` (each
with `som`, `test`, `severity` and `message`). The scripts report has `data_changed`, `warnings` and
`validation_errors`. Options default to `{"scripts":true,"flatten":false}` (`null` = defaults).
## Limits [#limits]
- Other barcode types (postal codes, RSS, MaxiCode and others) stay text fields, with a warning.
- Host dialogs (`xfa.host.messageBox`) are recorded as warnings, not shown.
# NexPDF for Android (/docs/android)
NexPDF for Android (`com.nexdevit:nexpdf-android`) is an AAR with the native engine for
`arm64-v8a`, `armeabi-v7a` and `x86_64`, and three layers of API:
- **`NexPdfDocument`**: a small `Closeable` class for the common tasks: open, render, extract text,
search, convert to Markdown, JSON or Word, and save.
- **`NexPdfJni`**: static native methods for the rest of the engine. They take the document's
`long` handle from `doc.handle()`.
- **`NexPdfReaderActivity`**: the ready-made reader screen, configured with the shared UI
configuration. See [Reader](/docs/android/reader).
Licensing is `NexPdfLicense`. The classes are Java and work the same from Kotlin.
```kotlin
import com.nexdevit.nexpdf.NexPdfDocument
import com.nexdevit.nexpdf.NexPdfJni
NexPdfDocument.openBytes(bytes).use { doc ->
val png = doc.renderPagePng(0, 144.0)
val text = doc.pageText(0)
val fields = NexPdfJni.formFieldsJson(doc.handle())
}
```
## Requirements [#requirements]
| | |
|---|---|
| Android | API 24 (Android 7.0) or later |
| ABIs | `arm64-v8a`, `armeabi-v7a`, `x86_64` |
| Dependencies | None. The reader needs no AndroidX |
## How it works [#how-it-works]
- `NexPdfDocument` wraps a native handle. Close it with `close()`, `use { }` in Kotlin or
try-with-resources in Java. `handle()` throws `IllegalStateException` once it is closed.
- `NexPdfDocument.openBytes`, `openEbook`, `openImage`, `openOffice`, `fromHtml` and the template
calls throw `IllegalArgumentException` with the engine's message when the file cannot be opened.
`openBytes` converts Office files, e-books and comics, and `openBytes(bytes, password)` opens
encrypted PDFs.
- `NexPdfJni` methods do not throw. A failure returns `false`, `0`, `-1`, an empty array or an
empty string, and `NexPdfJni.lastError()` gives the reason on the same thread.
- Methods whose name ends in `Json` return JSON text; parse it with `org.json`.
- Page indices start at 0. Coordinates are PDF points with the origin at the bottom-left of the
page (`llx, lly, urx, ury`).
- Use one document from one thread at a time. Different documents can be used on different
threads. Run long calls (rendering many pages, OCR, conversion) off the main thread.
## Every C function has a Java method [#every-c-function-has-a-java-method]
Since 1.1, every function of the C API has a `NexPdfJni` method, including `askDocument`,
`toHtml` / `toXml` / `toCsv` / `toRtf`, `saveLinearized`, `setOverprint`, `pageLabelsJson` /
`setPageLabelsJson`, `subsetFonts`, `convertPdfX`, `openEbook`, `openImage`,
`registerStandardFont`, `hasBundledFonts`, `clearError` and the three external-signing calls, and
the 1.1 functions (templates, document timestamps, comment threads, structured extraction, XFA,
word-level comparison, barcodes, OCR models and PDF/A and PDF/UA validation). `NexPdfDocument`
wraps the common ones, and the sync calls are in `NexPdfSyncJni` (see
[Real-time collaboration](/docs/android/guides/collaboration)).
### The generic invoke call [#the-generic-invoke-call]
`NexPdfJni.invoke` still takes the whole C API as one JSON request, which suits bridges that only
pass strings. Function names are the C names without `nexpdf_`, byte buffers travel as base64 and
documents as handle numbers:
```kotlin title="NexPdfInvoke.kt"
import android.util.Base64
import com.nexdevit.nexpdf.NexPdfJni
import org.json.JSONArray
import org.json.JSONObject
object NexPdfInvoke {
/** Calls a C function by name, without the nexpdf_ prefix. */
fun call(fn: String, vararg args: Any?): Any? {
val request = JSONObject().put("fn", fn).put("args", JSONArray(args.map { it ?: JSONObject.NULL }))
val response = JSONObject(NexPdfJni.invoke(request.toString()))
if (!response.getBoolean("ok")) throw IllegalStateException(response.getString("error"))
return response.opt("result")
}
fun base64(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP)
/** Opens PDF bytes as an invoke document; close it with call("close", handle). */
fun open(pdf: ByteArray): Int = (call("open_bytes", base64(pdf)) as Number).toInt()
}
```
Invoke handles are separate from the `long` handles of `NexPdfJni`: open the document's bytes with
`NexPdfInvoke.open` and free the handle with `call("close", h)`. Prefer the typed methods in app
code.
## Getting started [#getting-started]
## Guides [#guides]
## Help and reference [#help-and-reference]
# Installation (/docs/android/installation)
### Download the SDK [#download-the-sdk]
From the [v1.1.0 release](https://github.com/nexdevit/nexpdf-android/releases/tag/v1.1.0),
download one of:
| File | Contents |
|---|---|
| `nexpdf-android-1.1.0-maven.zip` | A Maven repository on disk with `com.nexdevit:nexpdf-android:1.1.0` |
| `nexpdf-android-1.1.0.aar` | The AAR alone |
Unzip the Maven repository into your project, for example as `nexpdf-maven/`.
### Add the repository and the dependency [#add-the-repository-and-the-dependency]
```kotlin title="settings.gradle.kts"
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven { url = uri("nexpdf-maven") }
}
}
```
```kotlin title="app/build.gradle.kts"
dependencies {
implementation("com.nexdevit:nexpdf-android:1.1.0")
}
```
```groovy title="settings.gradle"
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven { url = uri("nexpdf-maven") }
}
}
```
```groovy title="app/build.gradle"
dependencies {
implementation "com.nexdevit:nexpdf-android:1.1.0"
}
```
To use the AAR file alone instead, copy it to `app/libs/` and add
`implementation(files("libs/nexpdf-android-1.1.0.aar"))`.
### Check the minimum SDK [#check-the-minimum-sdk]
Set `minSdk = 24` or higher. The AAR contains native libraries for `arm64-v8a`, `armeabi-v7a` and
`x86_64`; if you set `ndk.abiFilters`, keep to those.
### Check the installation [#check-the-installation]
```kotlin
import com.nexdevit.nexpdf.NexPdfJni
Log.i("NexPDF", "version " + NexPdfJni.version())
```
## What the AAR adds [#what-the-aar-adds]
- The native libraries `libnexpdf_ffi.so` (the engine) and `libnexpdf_jni.so` (the JNI bridge).
- The `NexPdfReaderActivity` declaration in the merged manifest (not exported).
- Consumer keep rules for R8 and ProGuard that keep `NexPdfJni`, `NexPdfLicense`,
`NexPdfReaderActivity` and `NexPdfUIConfig`.
## Bundle the license [#bundle-the-license]
Put `nexpdf_license.xml` in `app/src/main/assets/`, or the key in the manifest, as described in
[License](/docs/android/license).
# License (/docs/android/license)
Call `NexPdfLicense.initialize` once per process, before other NexPDF calls, typically in
`Application.onCreate()`. It accepts the license XML file's text or the bare `NEX2.` key. See
[Licensing](/docs/guides/licensing) for how keys are issued and bound.
## Activate [#activate]
```kotlin
val rc = NexPdfLicense.initialize(this)
```
The key is read from, in order:
1. the manifest meta-data `com.nexdevit.nexpdf.license_key`;
2. `assets/nexpdf_license.xml`.
```xml title="AndroidManifest.xml"
```
If neither is present, `initialize` returns `-8`.
```kotlin
val rc = NexPdfLicense.initialize(this, BuildConfig.NEXPDF_LICENSE_KEY)
```
The key is activated for the platform `android` and the app's package name (`applicationId`), read
from the `Context`, so a key issued for `com.acme.app` does nothing in another app.
It returns `NexPdfLicense.LICENSED` (`2`) for a commercial key and `NexPdfLicense.TRIAL` (`1`) for a
trial key.
## Check the status [#check-the-status]
```kotlin
val status = JSONObject(NexPdfLicense.status())
Log.i("NexPDF", "${status.optString("state")} ${status.optString("tier")} ${status.optInt("days_left")}")
```
`status()` returns the license JSON: `state` (`unlicensed`, `trial`, `licensed`), `licensee`, `id`,
`tier`, `modules`, `expires_at`, `days_left` and `watermark`. To check one module, look for it in
`modules`.
## Handle errors [#handle-errors]
A rejected key returns a negative code, and `NexPdfJni.lastError()` gives the reason:
```kotlin
when (val rc = NexPdfLicense.initialize(this)) {
NexPdfLicense.LICENSED, NexPdfLicense.TRIAL -> Unit
-4 -> Log.e("NexPDF", "license expired: renew it in the dashboard")
-6, -7 -> Log.e("NexPDF", "license is for another platform or app id: ${NexPdfJni.lastError()}")
-8 -> Log.w("NexPDF", "no license configured")
else -> Log.e("NexPDF", "license rejected ($rc): ${NexPdfJni.lastError()}")
}
```
| Code | Meaning |
|---|---|
| -1 | Malformed key |
| -2 | Bad signature |
| -3 | Unsupported key version |
| -4 | Expired |
| -5 | Not yet valid (check the clock) |
| -6 | Wrong platform |
| -7 | Wrong application id |
| -8 | No key in the manifest or the assets (`initialize(context)` only) |
A call that needs a module your key does not include fails, and `lastError()` says why:
```kotlin
if (!NexPdfJni.encryptAes256(doc.handle(), "user", "owner")) {
Log.e("NexPDF", NexPdfJni.lastError()) // the active license does not include the 'security' module
}
```
Without a license, or after a rejected key, the SDK stays in viewer mode: it opens, renders,
extracts text and searches, and rendered pages carry the "NexPDF • Unlicensed" watermark.
# Platform notes (/docs/android/platform-notes)
## Threading [#threading]
- Every NexPDF call is **synchronous** and runs on the thread that calls it. Opening a large file,
rendering, OCR, signing and conversion can take long enough to drop frames or cause an ANR, so
call them off the main thread.
- A document is **not thread-safe**. Use each `NexPdfDocument` (or raw handle) from one thread at a
time. Different documents can be used on different threads at the same time. The state shared
between documents (the license and the renderer's caches) is thread-safe.
- To work on the same content from two threads, open a second document from `doc.saveBytes()`.
- The license is **process-wide**: one `NexPdfLicense.initialize` call covers every thread.
- Errors are tracked **per thread**: read `NexPdfJni.lastError()` on the thread that made the
failing call.
A single-thread dispatcher keeps all calls on a document in order, without locks:
```kotlin
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.nexdevit.nexpdf.NexPdfDocument
import java.util.concurrent.Executors
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.withContext
val pdfThread = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
suspend fun open(bytes: ByteArray): NexPdfDocument = withContext(pdfThread) {
NexPdfDocument.openBytes(bytes)
}
suspend fun render(doc: NexPdfDocument, page: Int, density: Float): Bitmap? = withContext(pdfThread) {
val png = doc.renderPagePng(page, 72.0 * density) // one PDF point per dp
if (png.isEmpty()) null else BitmapFactory.decodeByteArray(png, 0, png.size)
}
// In an Activity or Fragment:
lifecycleScope.launch {
imageView.setImageBitmap(render(doc, 0, resources.displayMetrics.density))
}
```
The [reader](/docs/android/reader) already does this: it renders pages on its own background
thread, from a private copy of the document reopened after each change, so the main thread never
shares a native document with it. `NexPdfReaderActivity.setEventListener` delivers events on the
main thread. The listener is static and shared by every reader, so clear it with `null` when you no
longer need it.
### Several processes [#several-processes]
Each process loads its own copy of the engine and needs its own license activation. Android runs
`Application.onCreate()` in every process of the app, so activating there covers a `:remote`
service or any other process you declare.
## Memory [#memory]
- A document is read fully into memory when it is opened: `openBytes` takes the whole file as a
`byte[]` and the engine keeps its own copy, so budget at least twice the file size while it opens,
plus the decoded pages you touch. Native memory does not count against the Java heap limit, but it
does count towards the memory the system allows your app.
- A page rendered with `renderPagePng` is PNG data; decoded into a `Bitmap` it takes width x height
x 4 bytes. A full A4 page at 216 dpi is about 1786 x 2526 pixels, or 18 MB. Render at the size
you show, use `renderThumbPng` for thumbnails, and keep only the pages on screen.
- The renderer keeps process-wide caches of parsed fonts, glyphs and decoded images, shared by
every document so a font or logo used on many pages is decoded once. Each cache is bounded by size
and drops its least recently used entries first; together they can hold up to about 1.3 GB in a
process that renders many large, image-heavy files. Memory that stays high after rendering is this
cache being reused, not a leak.
- `NexPdfJni.memoryUsageBytes(handle)` estimates what a document uses. `NexPdfJni.trimMemory(handle)`
compacts its internal buffers and drops objects nothing refers to any more, and returns the bytes
reclaimed. The document stays usable. `close()` frees everything; a document that is never closed
is never freed, because `NexPdfDocument` has no finalizer.
Call `trimMemory` from `onTrimMemory`, on the document's own thread:
```kotlin
override fun onTrimMemory(level: Int) {
super.onTrimMemory(level)
lifecycleScope.launch(pdfThread) { NexPdfJni.trimMemory(doc.handle()) }
bitmapCache.evictAll() // and drop your own rendered bitmaps
}
```
The reader holds two native copies of the document (one for editing, one for rendering), renders
pages at most 3072 pixels on the long side, and keeps a full copy of the PDF bytes for each of the
last 25 edits for undo. Editing a very large document in the reader uses several times its size.
## ABIs and app size [#abis-and-app-size]
- The AAR has the engine for `arm64-v8a`, `armeabi-v7a` and `x86_64`, as two libraries per ABI:
`libnexpdf_ffi.so` (the engine) and `libnexpdf_jni.so` (a small JNI bridge). The arm64 engine is
about 20 MB uncompressed. 32-bit x86 is not included.
- An **Android App Bundle** (`.aab`) lets Google Play deliver only the device's ABI, so users
download one engine, not three. This is the default for Play Store releases.
For APKs you distribute yourself, build one APK per ABI with ABI splits instead of one universal
APK that carries all three:
```kotlin title="app/build.gradle.kts"
android {
splits {
abi {
isEnable = true
reset()
include("arm64-v8a", "armeabi-v7a", "x86_64")
isUniversalApk = false
}
}
}
```
- To drop an ABI entirely, for example `armeabi-v7a` if you only target 64-bit devices,
set
`ndk { abiFilters += listOf("arm64-v8a", "x86_64") }`. Devices of a dropped ABI cannot load
NexPDF.
- The 64-bit libraries are aligned for 16 KB memory pages, which Android 15 devices with 16 KB pages
need.
- The engine compiles in the Liberation fonts (about 4 MB) used for non-embedded standard fonts and
PDF/A.
- The AAR has no dependencies; the reader is plain Android views and needs no AndroidX.
## Deployment [#deployment]
- Android 7.0 (API 24) or later.
- Android keys are bound to the package name (`applicationId`): each app, and each build variant
with its own `applicationIdSuffix`, needs a key issued for it. See [License](/docs/android/license).
- The AAR's keep rules for R8 and ProGuard are applied automatically; see
[Troubleshooting](/docs/android/troubleshooting) if you repackage the classes.
## Network [#network]
The engine makes no network calls of its own: license keys are verified offline and documents
never leave the app. Only signing options you set (`tsa_url` for a timestamp, `ltv` for OCSP and CRL
lookups) and `NexPdfJni.addLtv` contact the servers named in the options and the certificates. The
AAR does not request the `INTERNET` permission; add it to your manifest if you use those options.
# Reader (/docs/android/reader)
The reader is `com.nexdevit.nexpdf.ui.NexPdfReaderActivity`, part of the AAR and already declared
in its manifest. Its editing modes call the same engine functions as the API, so each needs the
license module of that feature; viewing works without a key.
The reader is a complete PDF screen: page view, search, thumbnails, page editor, bookmarks,
attachments, a More menu with security, signatures, OCR, PDF/A, export and more, and the modes
**viewer**, **annotations**, **content** (text and image editing), **forms** and **redaction**. It
needs no AndroidX.
## Open the reader [#open-the-reader]
```kotlin
import com.nexdevit.nexpdf.ui.NexPdfReaderActivity
NexPdfReaderActivity.setEventListener { type, data ->
Log.d("NexPDF", "$type $data")
}
startActivity(NexPdfReaderActivity.intent(this, pdfUri, null))
```
```java
import com.nexdevit.nexpdf.ui.NexPdfReaderActivity;
NexPdfReaderActivity.setEventListener((type, data) -> Log.d("NexPDF", type + " " + data));
startActivity(NexPdfReaderActivity.intent(this, pdfUri, null));
```
`intent(context, document, configJson)` takes a `content:` or `file:` URI (or `null` to open the
reader empty, with its Open button) and the configuration JSON (or `null`). The intent grants the
reader read access to the URI.
`NexPdfReaderActivity.closeCurrent()` closes the reader that is on screen. The user saves the
edited PDF with **Save as** in the More menu.
## Configure it [#configure-it]
The configuration is the shared NexPDF UI configuration, the same JSON as on the web, iOS, Flutter
and React Native. Every key is optional and unknown keys are ignored.
```kotlin
val config = """
{
"modeConfig": { "initialMode": "annotations", "availableModes": ["viewer", "annotations", "forms"] },
"toolbarConfig": {
"hiddenItems": ["search", "menu.ocr"],
"customItems": [{ "id": "send", "title": "Send to CRM", "icon": "send", "location": "top" }]
},
"annotationsConfig": { "availableTools": ["ink", "highlight", "note"], "defaultColor": "#0F766E" },
"globalConfig": { "themeMode": "dark", "accentColor": "#0F766E", "language": "pt" }
}
"""
startActivity(NexPdfReaderActivity.intent(this, pdfUri, config))
```
The reader takes its configuration from, in order:
1. the `configJson` of the intent (the `NexPdfReaderActivity.EXTRA_CONFIG` extra);
2. `assets/nexpdf_ui_config.json`;
3. the defaults.
To build the configuration in code, subclass the activity, override `loadConfig()` and declare
your subclass in the manifest:
```kotlin
class MyReaderActivity : NexPdfReaderActivity() {
override fun loadConfig(): NexPdfUIConfig =
NexPdfUIConfig.parseOrEmpty("""{"modeConfig":{"readOnly":true}}""")
}
```
| Key | What it does on Android |
|---|---|
| `modeConfig.initialMode`, `availableModes` | The mode to open in and the modes offered: `viewer`, `annotations`, `content`, `forms`, `redaction`. With one mode, the switcher is hidden |
| `modeConfig.readOnly` | Viewing only: hides undo, redo, open, the page editor and every editing row |
| `toolbarConfig.hiddenItems` | Built-in items to hide, such as `search`, `pages`, `more`, `undo`, `redo`, or More menu rows as `menu.` |
| `toolbarConfig.customItems` | Your own buttons: `id`, `title`, `icon`, `location` (`top`, `toolbar` or `more`) and `modes` |
| `annotationsConfig` | `availableTools`, `defaultColor`, `defaultOpacity`, `colorPalette`, `presets`, `rememberStyles`, `stamps` |
| `formsConfig.availableTools` | The form field tools to offer |
| `readerConfig.nightMode` | Shows pages with inverted colours |
| `globalConfig` | `themeMode` (`system`, `light`, `dark`), `accentColor`, `language`, `strings`, `languages` |
Layout, zoom, item order, `defaultFontSize`, brand and CSS keys are web only and are ignored on
Android.
## Events [#events]
`setEventListener` receives the events of every reader on the main thread, as a type and an
`org.json.JSONObject`. Pass `null` to stop.
| Event | `data` |
|---|---|
| `documentLoaded`, `documentChanged` | `filename`, `pageCount`, `canUndo`, `canRedo` |
| `modeChanged` | `mode` |
| `pageChanged` | `page` (1-based), `pageCount` |
| `customItemTapped` | `id`, `mode`, `page` |
| `closed` | `filename` |
```kotlin
NexPdfReaderActivity.setEventListener { type, data ->
if (type == "customItemTapped" && data.optString("id") == "send") {
NexPdfReaderActivity.closeCurrent()
upload()
}
}
```
# Troubleshooting (/docs/android/troubleshooting)
The device's ABI has no NexPDF library in the APK. The AAR ships `arm64-v8a`, `armeabi-v7a` and
`x86_64` only, so:
- 32-bit x86 emulators (`x86`) are not supported; use an `x86_64` or arm64 system image;
- if you set `ndk.abiFilters`, or `splits.abi`, keep to those three ABIs;
- check the APK in Android Studio (**Build > Analyze APK**): `lib//` must contain both
`libnexpdf_ffi.so` and `libnexpdf_jni.so`.
The JNI bridge looks up `NexPdfJni` methods by name, so R8 must not rename them. The AAR carries
consumer keep rules for `NexPdfJni`, `NexPdfLicense`, `NexPdfReaderActivity` and `NexPdfUIConfig`.
If you repackage its classes (for example into another AAR), those rules are lost; add them to your
own `proguard-rules.pro`:
```text title="proguard-rules.pro"
-keep class com.nexdevit.nexpdf.NexPdfJni { native ; *; }
-keep class com.nexdevit.nexpdf.NexPdfLicense { *; }
-keep class com.nexdevit.nexpdf.ui.NexPdfReaderActivity { *; }
-keep class com.nexdevit.nexpdf.ui.NexPdfUIConfig { *; }
```
Local unit tests (`src/test`) run on your computer's JVM, which cannot load the Android `.so`
files in the AAR.
Run tests that call NexPDF as instrumented tests (`src/androidTest`) on a device or emulator.
Check `JSONObject(NexPdfLicense.status()).optString("state")` in the process that renders:
- `unlicensed`: `NexPdfLicense.initialize` was never called, or it returned a negative code. Call it
in `Application.onCreate()` so it also runs in every extra process your app starts.
- `trial`: trial keys always keep the "NexPDF • Trial" watermark.
- `licensed`: commercial keys render without a watermark. If you still see one, the bitmap comes
from a cache of an earlier render.
Android keys are bound to the platform `android` and the package name read from the `Context`
(`applicationId`). A `-7` usually means a build variant changed the package name, for example an
`applicationIdSuffix` of `.debug`. Ask for a key for that id, or drop the suffix. You can change the
platform and app id in the [dashboard](/dashboard) and download a re-signed key.
`NexPdfLicense.initialize(context)` found no key: neither the manifest meta-data
`com.nexdevit.nexpdf.license_key` nor `assets/nexpdf_license.xml`. Check the file is in
`app/src/main/assets/` (not `res/`), or pass the key with `initialize(context, key)`.
`NexPdfReaderActivity` calls `NexPdfLicense.initialize(this)` itself when it starts, which reads
the manifest meta-data or `assets/nexpdf_license.xml`. If your app passes the key in code only, that
call finds nothing and the reader shows the message, while the key your app activated stays active.
Put the key in the assets or the manifest as well to avoid the message.
The device's clock is earlier than the key's issue date. Fix the date and time and activate again.
Your plan does not include that module. See [Modules and tiers](/docs/guides/modules) for which
plan unlocks it, and check the key's `modules` to hide the feature.
`NexPdfDocument.openBytes` converts EPUB, FictionBook, XPS/OpenXPS and CBZ files since 1.1, and so
does the reader. With 1.0.x, update to 1.1. If a book still fails, check that the key includes the
`conversion` module, and try `NexPdfDocument.openEbook(bytes)` to get the e-book converter's own
error. See [Opening and saving](/docs/android/guides/opening-and-saving).
The PDF uses a standard font (Helvetica, Times, Courier) without embedding it. The engine bundles
the Liberation fonts as substitutes; `NexPdfJni.hasBundledFonts()` tells you whether your build
has them, and `NexPdfJni.registerStandardFont(fontBytes)` adds them at run time.
The page is a scanned image with no text layer. Run [OCR](/docs/android/guides/ocr) first; it adds
an invisible text layer that extraction and search then read.
With `"engine": "auto"`, Tesseract is used only when the `tesseract` program can be run and has
data for every requested language. Android has no such program, so OCR uses a loaded neural model
when one reads the requested languages, and otherwise the built-in engine, which reads Latin-script
text. See [OCR](/docs/android/guides/ocr#other-scripts-neural-models).
The built-in engine reads Latin-script text only. Load a detection model and a recognition model
for the script with `NexPdfJni.ocrLoadModel` before calling `ocrJson`, and pass matching
`languages`. `NexPdfJni.ocrModelsJson()` lists what is loaded; the report's `engine` says
`neural ()` when a model was used. Keep `.onnx` files uncompressed in the APK
(`noCompress`). See [OCR](/docs/android/guides/ocr#other-scripts-neural-models).
The file is a dynamic XFA form, which most viewers no longer lay out. Convert it with
`xfaToAcroform()` or `xfaFlatten()`; see [XFA forms](/docs/android/guides/xfa-forms). Scripts in
the form (FormCalc, JavaScript) are not run.
The document was converted as far as possible, but some PDF/A rules still fail;
`NexPdfJni.lastError()` lists their clauses. Run `validatePdfaJson(level)` to see each failure with
its page and object. See [PDF/A and PDF/UA validation](/docs/android/guides/conformance).
`tsa_url`, `ltv`, `addLtv` and the document timestamp calls contact the timestamp authority and the OCSP and CRL servers named in
the certificates. The AAR does not request the `INTERNET` permission; add it to your app's manifest:
```xml title="AndroidManifest.xml"
```
Signing returns the complete signed file as a `byte[]`. Write those bytes unchanged. Calling
`saveBytes()` on the document afterwards rewrites the file and invalidates the signature. See
[Signatures](/docs/android/guides/signatures).
Render at the size you show: a page bitmap takes width x height x 4 bytes, so an A4 page rendered
at 216 dpi (about 1786 x 2526 pixels) is about 18 MB. Keep only the pages on screen, call
`NexPdfJni.trimMemory(handle)` from `onTrimMemory`, and close documents you no longer need. See
[Platform notes](/docs/android/platform-notes#memory).
Every NexPDF call is synchronous and runs on the calling thread. Move opening, rendering, OCR,
signing and conversion off the main thread. See
[Platform notes](/docs/android/platform-notes#threading).
Still stuck? Check [Error handling](/docs/android/error-handling) for the meaning of each error,
or the general [FAQ](/docs/guides/faq).
# Running without a license key (/docs/android/without-license)
You do not need a key to add the AAR, write code against it or run it. Until
`NexPdfLicense.initialize` returns `1` or `2`, the SDK runs in **view-only mode**:
- the `viewer` module works: open, render, extract text, search and read document information;
- pages rendered with `renderPagePng` carry a "NexPDF • Unlicensed" watermark;
- every call that needs another module fails (`false`, `0`, `-1` or an empty result), and
`NexPdfJni.lastError()` says why.
```kotlin
import com.nexdevit.nexpdf.NexPdfDocument
import com.nexdevit.nexpdf.NexPdfJni
import com.nexdevit.nexpdf.NexPdfLicense
import org.json.JSONObject
NexPdfDocument.openBytes(bytes).use { doc -> // no initialize call
Log.i("NexPDF", JSONObject(NexPdfLicense.status()).optString("state")) // "unlicensed"
val png = doc.renderPagePng(0, 144.0) // works, with the watermark
val text = doc.pageText(0) // works
if (!NexPdfJni.rotatePage(doc.handle(), 0, 90)) { // needs the editor module
Log.w("NexPDF", NexPdfJni.lastError())
// no license activated: 'editor' requires a NexPDF license key
}
}
```
## What works without a key [#what-works-without-a-key]
| Area | Methods |
|---|---|
| Opening and saving | `NexPdfDocument.openBytes`, `NexPdfJni.openBytesWithPassword`, `saveBytes`, `insertImagePages` |
| Rendering | `renderPagePng`, `renderThumbPng`, `pageWidth`, `pageHeight`, `pageView`, `pageViewJson` (`renderPagePng` output is watermarked) |
| Text | `pageText` / `extractPageText`, `toMarkdown` / `extractMarkdown`, `pageBlocksJson`, `searchJson` |
| Reading structure | `metadataJson`, `outlinesJson`, `layersJson`, `setLayerVisible`, `attachmentsJson`, `attachmentData` |
| Reading annotations | `annotationsJson`, `measurementsJson` |
| Security | `securityJson` |
| Comparing and memory | `compareJson`, `compareOverlayPng`, `trimMemory`, `memoryUsageBytes` |
`saveLinearized`, `setOverprint`, `pageLabelsJson` and `askDocument` work without a key too, and so
do the word-level comparison calls `compareTextJson` and `compareAnnotate`.
Everything else (annotating, filling forms, editing, encrypting, redacting, signing, converting,
OCR and PDF/A) needs a key that includes the module. The
[API reference](/docs/android/api-reference) names the module of every method.
The [reader](/docs/android/reader) works the same way: viewing, search, bookmarks and thumbnails
work without a key. When it starts without a key it shows "No NexPDF license: view-only mode", and
an editing action that needs a module shows "This feature needs a NexPDF license".
## Check the mode at run time [#check-the-mode-at-run-time]
`NexPdfLicense.status()` returns the license as JSON. A small helper tells you whether a module is
unlocked:
```kotlin
fun isLicensed(module: String): Boolean {
val modules = JSONObject(NexPdfLicense.status()).optJSONArray("modules") ?: return false
return (0 until modules.length()).any { modules.getString(it) == module }
}
val status = JSONObject(NexPdfLicense.status())
when (status.optString("state")) {
"unlicensed" -> Log.i("NexPDF", "view-only mode, pages are watermarked")
"trial" -> Log.i("NexPDF", "trial, ${status.optInt("days_left")} days left")
else -> Log.i("NexPDF", "licensed for ${status.optJSONArray("modules")}")
}
```
Use `isLicensed("redaction")` to hide features your key does not unlock instead of waiting for the
error. To limit the reader to what the key unlocks, pass only those modes in
`modeConfig.availableModes`.
## Evaluate with a trial key [#evaluate-with-a-trial-key]
A trial key unlocks **every module** so you can try annotations, signing, redaction and the rest. It
keeps a "NexPDF • Trial" watermark on rendered pages, and `initialize` returns
`NexPdfLicense.TRIAL` (`1`) instead of `NexPdfLicense.LICENSED` (`2`). Trial keys last 30 days; ask
for one from the [pricing page](/pricing) with your package name, and activate it exactly like a
commercial key; see [License](/docs/android/license).
The watermark is drawn on the pixels of rendered pages only; documents you save are not changed. Even so,
view-only and trial modes are for development and evaluation. Play Store builds need a commercial
key for the modules they use. See [Licensing](/docs/guides/licensing) and the
[modules per plan](/docs/guides/modules).
# Accessibility (PDF/UA) (/docs/cloud/accessibility)
The `pdfua` action tags the document for PDF/UA: its structure is marked up and its language
declared, so screen readers and other assistive technology can read it. `part` is `1` (PDF/UA-1)
or `2`; `lang` is the document's language (such as `en-US`).
It helps you meet the European Accessibility Act, Section 508 and WCAG for documents you publish.
Cost: 1 unit per page.
## Tag a report [#tag-a-report]
# AI extraction and classification (/docs/cloud/ai)
Two endpoints read a document's text with Claude, Anthropic's model, and answer with JSON in the
shape you ask for:
| Endpoint | Fields | Answers |
| --- | --- | --- |
| `POST /v1/ai/extract` | `document`; `schema` (a JSON Schema); `prompt` (optional) | `{ "data": … }`, following your schema |
| `POST /v1/ai/classify` | `document`; `labels` (a JSON list); `prompt` (optional) | `{ "label": …, "reason": … }` |
Any file `convert` accepts works, uploaded or [by link](/docs/cloud/files-by-url). Scanned
documents need text first: run [OCR](/docs/cloud/ocr) and send its result.
## Extract data [#extract-data]
Describe what you want with a JSON Schema whose top level is an object. The answer always parses
and always matches the schema: required fields are present and types are right. Fields the
document does not state come back empty or `null` rather than invented, so make a field optional
(leave it out of `required`) when a document may not have it.
```json
{
"data": {
"invoice_number": "INV-2026-0412",
"issue_date": "2026-11-03",
"supplier": "Northwind Traders Ltd",
"total": 1840.5,
"currency": "EUR",
"lines": [
{ "description": "Consulting, October", "amount": 1500 },
{ "description": "Travel", "amount": 340.5 }
]
}
}
```
Schemas may use `type`, `properties`, `required`, `items`, `enum`, `const`, `anyOf`, `format`
(such as `date` and `email`), `description` and `$defs`. Objects are closed: properties you did not
list are never returned. `minimum`, `maximum`, `minLength` and `maxLength` are not supported and
are ignored; check ranges in your code. A `description` on a field is the best place to say what
you mean ("ISO 4217 code", "the date the invoice was issued, not the due date").
## Classify documents [#classify-documents]
Give 2 to 100 labels, as names or as `{ "name", "description" }` when a name alone is ambiguous.
The answer is always one of your labels, with a sentence on what decided it.
```json
{ "label": "invoice", "reason": "It lists amounts due with a payment deadline and an invoice number." }
```
## Instructions [#instructions]
`prompt` adds your own instructions, up to 4,000 characters: "Amounts are in thousands", "Use the
billing address, not the shipping address". The document's own text is treated as data, never as
instructions, so a document cannot change what the model does.
## Cost and limits [#cost-and-limits]
- 1 unit per 4,000 characters of text, 2 at least, plus the conversion to PDF when the document is
not one. A 10-page contract is usually about 8 units. The response's `x-nexpdf-units` header
says what each request cost.
- Up to 300,000 characters of text (about 100 pages). Longer documents are refused with
`413 document_too_long` rather than cut short, so an answer never silently comes from part of a
document: [split](/docs/cloud/split) the document first.
- If the model declines to process a document, the request fails with `422 ai_refused`; if the
answer would be longer than the model can write, with `422 ai_incomplete` (ask for fewer fields).
Neither is charged.
## Privacy [#privacy]
The document's text is sent to Anthropic's API to answer the request. Under Anthropic's commercial
terms, API data is not used to train its models, and NexPDF Cloud keeps nothing after the response. When documents must
not leave your own network, use the [NexPDF SDK](/docs) instead, which extracts text and structure
on your own servers. See [security and privacy](/docs/cloud/security-and-privacy).
# Authentication and keys (/docs/cloud/authentication)
Every request except `GET /v1/health` needs an API key, sent as a bearer token:
```http
Authorization: Bearer nxp_live_...
```
Create and revoke keys in the dashboard under [Cloud API keys](/dashboard/api-keys).
## Test and live keys [#test-and-live-keys]
| Key | Prefix | Output | Limits |
| --- | --- | --- | --- |
| Test | `nxp_test_` | Every PDF carries a "NexPDF Cloud test key" watermark. Free on every account. | 5 MB per file, 20 requests a minute, 1,000 units a month |
| Live | `nxp_live_` | Clean output, counted against your plan. | Your plan's limits ([see pricing](/docs/cloud/limits-and-pricing)) |
Use test keys in development and CI; they exercise every endpoint with the same validation as live
keys. Editing Excel and Word files needs a live key.
## Keep keys secret [#keep-keys-secret]
- A key is shown once, when you create it. NexPDF keeps only a hash, so a lost key cannot be
shown again: create a new one.
- Keep keys on your server, in an environment variable or a secret manager. Never put one in a
web page, a mobile app or a public repository.
- Use one key per app or environment, so you can revoke one without stopping the others.
- If a key leaks, revoke it in the dashboard. Requests with it stop working within a minute.
## Configure the clients [#configure-the-clients]
Every client reads the key from `NEXPDF_API_KEY` and the address from `NEXPDF_API_BASE` (default
`https://api.nexpdf.dev`). You can also pass both when you create the client, along with the
timeout (300 seconds by default) and the number of retries (2 by default). See
[client libraries](/docs/cloud/sdks).
A client created without a key fails at once with the code `missing_api_key`, before it sends
anything.
# Build API (/docs/cloud/build-api)
`POST /v1/build` takes `multipart/form-data`: each file in a field of its own, and an
`instructions` field with JSON. The instructions name the files by their field.
```json
{
"parts": [ … ],
"actions": [ … ],
"output": { … }
}
```
Unknown fields are refused with `invalid_request`, so a typo never passes silently. Every file
sent must be used by a part.
## Parts [#parts]
Up to 20, joined in order. Each part has either `file` or `html`.
## Actions [#actions]
Up to 50, applied in order to the joined document. `pages` lists count from 0.
| `type` | Fields | Guide |
| --- | --- | --- |
| `ocr` | `languages` (optional, such as `eng+por`) | [OCR](/docs/cloud/ocr) |
| `watermark` | `text` | [Watermark](/docs/cloud/watermark) |
| `rotate` | `degrees` (90, 180 or 270; negative turns the other way); `pages` (optional, all pages when left out) | [Pages](/docs/cloud/merge-and-pages) |
| `delete_pages` | `pages` | [Pages](/docs/cloud/merge-and-pages) |
| `flatten_annotations`, `flatten_forms` | None | [Forms](/docs/cloud/forms) |
| `fill_form` | `values`: `{ "field name": value }` | [Forms](/docs/cloud/forms) |
| `redact` | `query`; `mode`: `text` (default), `regex` or `pattern`; `fill_white` | [Redaction](/docs/cloud/redaction) |
| `pdfa` | `level`: `1a`, `1b`, `2a`, `2b` (default), `2u`, `3a`, `3b` or `3u` | [PDF/A](/docs/cloud/pdfa) |
| `pdfua` | `part` (1 or 2), `lang` | [Accessibility](/docs/cloud/accessibility) |
| `optimize` | None | [Optimize](/docs/cloud/optimize) |
| `encrypt` | `owner_password`; `user_password` and `permissions` (optional). Last action only, with PDF output. | [Encrypt](/docs/cloud/encrypt) |
| `sign` | All optional: `certificate` (the field of an uploaded PKCS#12 file; self-signed when left out), `password`, `name`, `reason`, `location`, `contact`, `field`, `appearance` (`page`, `rect`, `text`). Last action only, with PDF output that is not linearised. | [Digital signatures](/docs/cloud/signatures) |
## Output [#output]
Optional; a PDF when left out.
| `type` | Fields | Returns |
| --- | --- | --- |
| `pdf` | `linearize` | PDF |
| `png` | `page` (from 0), `dpi` (36–300, default 150) | A PNG of one page |
| `markdown`, `html`, `json` | None | The text of the document |
| `docx`, `xlsx` | None | A Word or Excel file |
| `split` | `every` (pages per file) or `ranges` (a list of `{ "start", "end" }`) | A ZIP of PDFs, `part-1.pdf`, `part-2.pdf`… ([Split](/docs/cloud/split)) |
## Cost [#cost]
The parts and actions are counted as if they were separate calls; see
[limits and pricing](/docs/cloud/limits-and-pricing). A job that would need more units than are
left this month is refused before it runs.
# Choose a workflow (/docs/cloud/choose-a-workflow)
## Single-purpose endpoints [#single-purpose-endpoints]
Use these when you need exactly one thing. They take one field and need no JSON.
| You want | Endpoint |
| --- | --- |
| A PDF from Word, Excel, PowerPoint, an image or EPUB | [`/v1/convert/pdf`](/docs/cloud/convert-to-pdf) |
| A searchable PDF from a scan | [`/v1/ocr`](/docs/cloud/ocr) |
| Several files joined, in order | [`/v1/merge`](/docs/cloud/merge-and-pages) |
| The text of a document as Markdown, for search or an LLM | [`/v1/extract/markdown`](/docs/cloud/extraction) |
| An Excel file with cells changed and recalculated | [`/v1/xlsx/edit`](/docs/cloud/office-editing) |
| A Word file with text replaced | [`/v1/docx/edit`](/docs/cloud/office-editing) |
| One PDF cut into several, by size or by ranges | [`/v1/split`](/docs/cloud/split) |
| The signatures in a PDF checked | [`/v1/verify`](/docs/cloud/signatures#verify-signatures) |
## Build: everything else [#build-everything-else]
[`/v1/build`](/docs/cloud/build-api) does what the others do and more, in one request: it joins
**parts** (files, page ranges, HTML pages), applies **actions** in order (OCR, redact, watermark,
rotate, fill forms, PDF/A, encrypt, sign…) and writes one **output** (PDF, PNG, Markdown, HTML,
JSON, Word, Excel, or a ZIP of split PDFs).
One request instead of several means one upload, one download, and no intermediate file on
your side. Each part and action costs its units, as if you had made the calls one by one.
## Common pipelines [#common-pipelines]
| Job | Parts | Actions | Output |
| --- | --- | --- | --- |
| Make scanned archives searchable and safe to share | the scan | `ocr`, `redact` (patterns) | `pdf` |
| Send a contract packet | contract, annex | `redact`, `watermark`, `encrypt` | `pdf`, linearised |
| File invoices for the long term | the invoice | `pdfa` | `pdf` |
| Publish an accessible report | the report | `pdfua` | `pdf` |
| Feed documents to search or an LLM | the document | `ocr` if scanned | `markdown` or `json` |
| Close a submitted form | the form | `fill_form`, `flatten_forms` | `pdf` |
| Sign an approved contract | the contract and your `.p12` | `sign` | `pdf` |
| Issue one payslip per employee | the batch | `redact` (patterns) | `split`, every page |
| Show a preview | the document | none | `png` |
## Cloud, SDK or MCP? [#cloud-sdk-or-mcp]
| | Cloud API | SDK | [MCP server](/docs/cloud/mcp) |
| --- | --- | --- | --- |
| Runs | On our servers | In your app or on your servers | Next to an AI assistant, calling the Cloud API |
| Install | Nothing (a small client, optional) | A native library | One command |
| Cost | Units per operation | A licence, no per-request cost | Units per operation |
| Files leave your network | Yes, for the length of the request | No | Yes, for the length of the request |
| Best for | Serverless, occasional jobs, any language | High volume, offline, mobile, private data | Asking an assistant in plain words |
# Convert to PDF (/docs/cloud/convert-to-pdf)
`POST /v1/convert/pdf` takes one file in the `document` field and answers with a PDF. The
conversion runs on the NexPDF engine, with no Office or LibreOffice behind it, so layout, fonts and
tables come out the same every time.
Accepted: Word (`.docx`), Excel (`.xlsx`), PowerPoint (`.pptx`), EPUB, JPEG and PNG images, and
PDF (passed through, so you can use the same call for any upload).
Cost: 1 unit per file.
## Convert one file [#convert-one-file]
## Images to one PDF [#images-to-one-pdf]
To join several images or documents into one PDF, list them as parts of a build. Without `output`, a build makes a PDF.
## Related [#related]
- [HTML to PDF](/docs/cloud/html-to-pdf)
- [Merge and pages](/docs/cloud/merge-and-pages)
- [PDF/A](/docs/cloud/pdfa), to make the result fit for archiving in the same call
# Encrypt (/docs/cloud/encrypt)
The `encrypt` action protects the PDF with AES-256. `user_password` is needed to open it;
`owner_password` is needed to change it (leave `user_password` out and anyone can open it, with
the permissions enforced). `permissions` (optional) is the sum of what readers may do without the
owner password: 1 print, 2 modify, 4 copy, 8 annotate, 16 fill forms, 32 assemble pages. By
default they may print and fill forms.
`encrypt` must be the last action and the output must be PDF, since nothing can work on the file
once it is encrypted.
Cost: 1 unit per action.
## Lock a payslip [#lock-a-payslip]
To open an encrypted PDF in a build, give its password in the part: `{ "file": "doc", "password": "…" }`.
# Endpoints (/docs/cloud/endpoints)
Base address: `https://api.nexpdf.dev`. Every endpoint takes a bearer key except health and the
specification. Requests that send files use `multipart/form-data`, and any file field may be sent
as a [link](/docs/cloud/files-by-url) instead (`document_url`). The whole API is also described in
[OpenAPI](/docs/cloud/openapi).
| Endpoint | Fields | Returns |
| --- | --- | --- |
| `POST /v1/build` | `instructions` (JSON, see [Build API](/docs/cloud/build-api)) and the files it names | As `output` says |
| `POST /v1/convert/pdf` | `document`: Word, Excel, PowerPoint, image, EPUB or PDF | PDF |
| `POST /v1/ocr` | `document`; `languages` (optional, such as `eng+por`) | Searchable PDF |
| `POST /v1/merge` | `file1`, `file2`, … in the order to join them | PDF |
| `POST /v1/extract/markdown` | `document` | Markdown |
| `POST /v1/xlsx/edit` | `document` (.xlsx); `edits` (JSON). Live keys only. | .xlsx |
| `POST /v1/docx/edit` | `document` (.docx); `ops` (JSON). Live keys only. | .docx |
| `POST /v1/split` | `document`; `every` (a number of pages) or `ranges` (JSON list of `{ "start", "end" }`) | ZIP of PDFs |
| `POST /v1/verify` | `document` (PDF) | JSON: one object per signature ([keys](/docs/cloud/signatures#verify-signatures)) |
| `POST /v1/sign/prepare` | `document`; `certificate` (PEM or DER); `options` (JSON), `expires_in` (optional) | `201` and the bytes to sign ([two-step signing](/docs/cloud/signatures#sign-with-a-key-you-hold)). Free. |
| `POST /v1/sign/complete` | `id`; `signature` (base64) | The signed PDF |
| `DELETE /v1/sign/{id}` | None | `204` |
| `POST /v1/estimate` | As `/v1/build` | JSON: `units`, `pages`, `operations` ([estimates](/docs/cloud/estimate)). Free. |
| `POST /v1/jobs` | As `/v1/build` | `202` and the job ([background jobs](/docs/cloud/jobs)) |
| `POST /v1/batch` | `instructions`; `document1`, `document2`, … | `202` and the job |
| `GET /v1/jobs/{id}` | None | JSON: the job |
| `GET /v1/jobs/{id}/result` | None | The job's output |
| `DELETE /v1/jobs/{id}` | None | `204` |
| `POST /v1/viewer` | `document`; `expires_in`, `download` (optional) | `201` and the link ([hosted viewer](/docs/cloud/viewer)) |
| `DELETE /v1/viewer/{id}` | None | `204` |
| `POST /v1/ai/extract` | `document`; `schema` (JSON Schema); `prompt` (optional) | JSON: `{ "data": … }` ([AI](/docs/cloud/ai)) |
| `POST /v1/ai/classify` | `document`; `labels` (JSON list); `prompt` (optional) | JSON: `{ "label", "reason" }` |
| `GET /v1/health` | None, and no key | `{"ok":true,"version":"1.1.0"}` |
| `GET /v1/openapi.json` | None, and no key | The [OpenAPI](/docs/cloud/openapi) document |
## Response headers [#response-headers]
| Header | Meaning |
| --- | --- |
| `x-nexpdf-units` | The units the request cost. |
| `x-request-id` | The request's id. Quote it when you write to us. |
| `retry-after` | On `429` and `503`: seconds to wait before trying again. |
| `cache-control` | `no-store`, except viewer page images. |
# Errors (/docs/cloud/errors)
Errors are JSON, with a stable `code` to branch on and a `message` for people:
```json
{ "error": { "code": "invalid_request", "message": "the \"instructions\" field is missing" }, "request_id": "req_…" }
```
Failed requests cost nothing.
| Status | `code` | Meaning | What to do |
| --- | --- | --- | --- |
| 400 | `invalid_request` | A field is missing, unknown or malformed. | Fix the request; the message says which field. |
| 401 | `unauthorized` | The key is missing, malformed, unknown or revoked. | Check `NEXPDF_API_KEY`. |
| 402 | `payment_required` | The account's billing needs attention. | Update the payment method in the dashboard. |
| 404 | `not_found` | No such job or viewer link, or not this key's. | Check the id; results are deleted 24 hours after a job ends. |
| 409 | `not_ready` | The job has not finished. | Wait for `retry-after`, or use `waitForJob` in the clients. |
| 409 | `job_failed` | The job failed; it has no result. | Read the job's `error`. |
| 413 | `file_too_large` | A file is over the key's size limit. | Split the file, or move to a larger plan. |
| 413 | `document_too_long` | The text is over the AI endpoints' 300,000 characters. | Split the document first. |
| 422 | `fetch_failed` | A file sent as a link could not be downloaded, or your own time-stamp authority (`timestamp_authority`) refused or did not answer; the message says why. | Check that the link works from the internet and has not expired; for a time-stamp authority, its address and credentials. |
| 422 | `ai_refused`, `ai_incomplete` | The model declined the document, or the answer would be too long. | Ask for fewer fields; check the document. |
| 422 | `processing_failed` | The document could not be processed (damaged file, wrong password, page out of range), the job needs more units than are left, or a test key was used to edit Excel or Word. | Check the file and the message. |
| 422 | `not_available` | This server does not offer what the request asks for, such as ICP-Brasil AD-RT without a time-stamp authority. Refused before any work, at no cost. | For AD-RT, give your own ACT in [`timestamp_authority`](/docs/cloud/signatures#your-own-time-stamp-authority), or sign at `B-B` (AD-RB). |
| 429 | `rate_limited` | Too many requests this minute. | Retried by the clients; wait for `retry-after`. |
| 429 | `concurrency_limited` | Too many requests in progress at once. | Retried by the clients; wait for `retry-after`. |
| 429 | `quota_exceeded` | No units left this month. | Upgrade, or wait for the next month. |
| 503 | `busy`, `unavailable` | Our side is busy, or a timestamp authority did not answer. | Retried by the clients; wait for `retry-after`. |
| 503 | `ai_unavailable` | AI endpoints are not enabled on this server. | Write to us. |
| 504 | `timeout` | Processing took too long. | Split the job into smaller requests. |
## In the clients [#in-the-clients]
Every client raises one error type carrying the status, the `code`, the message, the request id
and `retryAfter`. See [client libraries](/docs/cloud/sdks#errors). Retries for `rate_limited`,
`concurrency_limited`, `503` and network failures happen before the error reaches you.
# Cost estimates (/docs/cloud/estimate)
`POST /v1/estimate` takes exactly what [`/v1/build`](/docs/cloud/build-api) takes (the same
`instructions`, the same files or links) and answers with what the build would cost, without
running it:
```json
{
"units": 14,
"pages": 12,
"operations": [
{ "op": "ocr", "units": 12 },
{ "op": "redact", "units": 1 },
{ "op": "sign", "units": 1 },
{ "op": "timestamp", "units": 1 }
]
}
```
`operations` lists what each step costs, by the [price list](/docs/cloud/limits-and-pricing);
`pages` is the length of the document the build would produce before any split.
Estimates cost nothing and do not count against the plan's units (they do count toward the
request rate). The instructions and files are checked as a build checks them, so an estimate is
also a way to validate a request before sending it for real.
## How exact it is [#how-exact-it-is]
The estimate opens the files (converting those that are not PDFs) and counts their pages, so
per-page operations such as OCR are counted from the real document. The final bill can only be
lower, never higher: an action that fails costs nothing.
For AI extraction and the viewer, see their own pages: their cost depends on the document's text
and is shown in the response's `x-nexpdf-units` header.
# Extraction (/docs/cloud/extraction)
Extraction gives you the content of a document in a form code can use: Markdown for search
indexes and LLMs, HTML for display, JSON for its structure.
Scanned documents have no text to extract; add an `ocr` action first.
Cost: Markdown and HTML, 1 unit per file; JSON, 1 unit per page.
## Markdown [#markdown]
`POST /v1/extract/markdown` keeps headings, lists, tables and links.
## JSON [#json]
With a build and `output: { type: "json" }`.
# Files by URL (/docs/cloud/files-by-url)
Any file field can be sent as a link instead: add `_url` to the field's name and give an
`http` or `https` address. `document` becomes `document_url`, `file1` becomes `file1_url`, a build's
`doc` becomes `doc_url`. The server downloads the file and the request goes on as if you had
uploaded it. Uploads and links can be mixed in one request.
Useful when the file is already in object storage (a presigned S3, Google Cloud Storage or Azure
link), on a CDN, or too large to pass through your own server first.
## Convert a file from a link [#convert-a-file-from-a-link]
## Mix uploads and links [#mix-uploads-and-links]
Here the cover page is uploaded and the contract comes from storage:
## What is allowed [#what-is-allowed]
- `http` and `https` only, on ports 80 and 443, with no user name or password in the URL (put
credentials in a presigned query string instead).
- The address must be public: private, loopback, link-local and cloud metadata addresses are
refused, and so is a redirect to one. At most 5 redirects.
- The file counts toward the key's size limit like an upload, and the download must finish within
30 seconds.
- Up to 10 links per request.
A link that cannot be fetched fails the request with `422 fetch_failed` (the message says why); one
that is not allowed fails with `400 invalid_request`; a file over the limit with
`413 file_too_large`. Nothing is charged for a request that fails.
In the client libraries a URL is a file input like a path: `url('https://…')` in TypeScript,
`File.from_url` in Python, `nexpdfcloud.URL` in Go, `Input::url` in Rust (see
[client libraries](/docs/cloud/sdks)). The client never downloads the file itself.
# Forms (/docs/cloud/forms)
The `fill_form` action sets form fields by name: text fields take text, checkboxes take `true`
or `false`, and choice fields take one of their options. `flatten_forms` then turns the fields into
ordinary page content, so the answers can no longer be changed.
To find a form's field names, extract the form as JSON.
Cost: 1 unit per action.
## Fill and flatten [#fill-and-flatten]
`flatten_annotations` does the same for comments, highlights and stamps.
# Get started (/docs/cloud/getting-started)
### Create a key [#create-a-key]
Sign in and open [Cloud API keys](/dashboard/api-keys) in the dashboard. Create a **test** key to
start: it is free, and every PDF it makes carries a small "NexPDF Cloud test key" watermark.
The key is shown once. Keep it on your server and pass it through an environment variable:
```bash
export NEXPDF_API_KEY="nxp_test_..."
```
Every client library reads `NEXPDF_API_KEY` by itself, so the samples below never contain a key.
### Install a client [#install-a-client]
Pick your language once and every sample on these pages follows it.
Nothing to install: curl ships with macOS, Linux and Windows 10+.
```bash
npm install @nexdevit/nexpdf-cloud
```
Node 18+, Bun, Deno and edge runtimes. No dependencies.
```bash
pip install nexpdf-cloud
```
Python 3.9+. Standard library only.
```bash
go get github.com/nexdevit/nexpdf-cloud-go
```
Go 1.21+. Standard library only.
```bash
cargo add nexpdf-cloud
```
```bash
composer require nexdevit/nexpdf-cloud
```
PHP 8.1+ with `ext-curl`.
```bash
dotnet add package Nexdevit.NexPdf.Cloud
```
.NET 8+ (C#, F#, VB).
```xml
com.nexdevit
nexpdf-cloud
1.1.0
```
Java 11+ and Kotlin. Gradle: `implementation("com.nexdevit:nexpdf-cloud:1.1.0")`.
```bash
gem install nexpdf-cloud
```
Ruby 3.0+.
```swift
.package(url: "https://github.com/nexdevit/nexpdf-cloud-swift", from: "1.1.0")
```
Swift 5.9+ on macOS, Linux and server-side Swift.
### Convert a document [#convert-a-document]
Turn a Word file into a PDF. Any Word, Excel, PowerPoint, image or EPUB file works the same way.
The answer is the PDF itself. The client prints the units the request cost; with curl, add `-i`
to see the `x-nexpdf-units` header.
### Chain steps [#chain-steps]
Ask for several things at once with [`/v1/build`](/docs/cloud/build-api). This one OCRs a scan and
blacks out every e-mail address it finds:
### Go live [#go-live]
When it works, create a **live** key. Live output has no watermark and draws on your plan's
monthly units (the Free plan includes 500). See [limits and pricing](/docs/cloud/limits-and-pricing).
## Next [#next]
- [Choose a workflow](/docs/cloud/choose-a-workflow): which endpoint fits which job.
- [Errors](/docs/cloud/errors): what can go wrong and what the clients retry for you.
# HTML to PDF (/docs/cloud/html-to-pdf)
Send an HTML page as a file and name it in an `html` part of a build.
For safety, the page cannot load anything: external images, style sheets, fonts and scripts are
skipped. Put styles in a `