# API reference (/docs/android/api-reference) This page is generated from the sources of `com.nexdevit:nexpdf-android`. It lists 220 members. Options and results that are JSON strings use the same JSON in every NexPDF SDK. **Module** is the license module a call needs; calls marked "always available" work without a license key. ## Setup and lifecycle [#setup-and-lifecycle] ### initialize [#initialize] ```java public static int initialize(Context context) public static int initialize(Context context, String keyOrXml) ``` Activates the key from the manifest meta-data, else from `assets/nexpdf_license.xml`. On `NexPdfLicense (static)` ### status [#status] ```java public static String status() ``` Current state as JSON: `state` (unlicensed|trial|licensed), licensee, modules, days_left… On `NexPdfLicense (static)` ### openBytes [#openbytes] ```java public static NexPdfDocument openBytes(byte[] bytes) public static NexPdfDocument openBytes(byte[] bytes, String password) ``` Opens PDF bytes, or JPEG / PNG / TIFF pictures (one page each). Word / Excel / PowerPoint files and EPUB / FictionBook / XPS books and CBZ comics are converted (module: conversion). On `NexPdfDocument` ### isPasswordError [#ispassworderror] ```java public static boolean isPasswordError(Throwable e) ``` Whether an exception from `#openBytes` means the password is missing or wrong. On `NexPdfDocument` ### openEbook [#openebook] ```java public static NexPdfDocument openEbook(byte[] bytes) ``` EPUB, FictionBook (.fb2 / .fb2.zip), XPS / OpenXPS or CBZ comic bytes to a new PDF (module: conversion). On `NexPdfDocument` ### openImage [#openimage] ```java public static NexPdfDocument openImage(byte[] bytes) ``` JPEG / PNG / TIFF pictures to a new PDF, one page per picture. On `NexPdfDocument` ### openOffice [#openoffice] ```java public static NexPdfDocument openOffice(byte[] bytes) ``` Converts DOCX / XLSX / PPTX bytes to a new PDF. On `NexPdfDocument` ### fromHtml [#fromhtml] ```java public static NexPdfDocument fromHtml(String html) ``` Lays out HTML as a new PDF. On `NexPdfDocument` ### handle [#handle] ```java public long handle() ``` The native handle, for `NexPdfJni` calls. @Override On `NexPdfDocument` ### pageCount [#pagecount] ```java public int pageCount() ``` On `NexPdfDocument` ### pageWidth [#pagewidth] ```java public double pageWidth(int pageIndex) ``` Displayed page width in points: the crop box (clipped to the media box), after /Rotate and /UserUnit. On `NexPdfDocument` ### pageHeight [#pageheight] ```java public double pageHeight(int pageIndex) ``` Displayed page height in points: the crop box (clipped to the media box), after /Rotate and /UserUnit. On `NexPdfDocument` ### pageView [#pageview] ```java public PageView pageView(int pageIndex) ``` How the page is displayed (crop box, rotation, user unit) and the PDF <-> display transform. Use it for every screen/PDF coordinate conversion. Never null: falls back to an unrotated page of `#pageWidth` x `#pageHeight` at the origin. On `NexPdfDocument` ### renderPagePng [#renderpagepng] ```java public byte[] renderPagePng(int pageIndex, double dpi) ``` On `NexPdfDocument` ### pageText [#pagetext] ```java public String pageText(int pageIndex) ``` On `NexPdfDocument` ### toMarkdown [#tomarkdown] ```java public String toMarkdown() ``` On `NexPdfDocument` ### toJson [#tojson] ```java public String toJson() ``` On `NexPdfDocument` ### toDocx [#todocx] ```java public byte[] toDocx() ``` On `NexPdfDocument` ### searchJson [#searchjson] ```java public String searchJson(String query) ``` Finds `query`; a JSON array of `{page, context, llx, lly, urx, ury`\}: the 0-based page, the surrounding text and the match rectangle in PDF points (origin bottom-left). On `NexPdfDocument` ### saveBytes [#savebytes] ```java public byte[] saveBytes() ``` The document, with all changes, as PDF bytes. On `NexPdfDocument` ### saveLinearized [#savelinearized] ```java public byte[] saveLinearized() ``` Linearized ("Fast Web View") PDF bytes: the first page shows before the download ends. On `NexPdfDocument` ### pageLabelsJson [#pagelabelsjson] ```java public String pageLabelsJson() ``` `{"labels":["i","ii","1"],"ranges":[{"start":0,"style":"roman","prefix":"","first":1`]\}\}. On `NexPdfDocument` ### setPageLabelsJson [#setpagelabelsjson] ```java public boolean setPageLabelsJson(String rangesJson) ``` Sets the page label ranges (`[]` removes them; module: editor). On `NexPdfDocument` ### trimMemory [#trimmemory] ```java public long trimMemory() ``` Compacts internal buffers; returns the approximate number of bytes reclaimed. On `NexPdfDocument` ### prepareExternalSignature [#prepareexternalsignature] ```java public byte[] prepareExternalSignature(byte[] cert, String optionsJson) ``` External signing, step 1 of 3: this document with an empty signature, to pass to `#externalSignatureData` and then `#completeExternalSignature`. `cert` is the signer certificate in PEM or DER, optionally followed by its chain. On `NexPdfDocument` ### externalSignatureData [#externalsignaturedata] ```java public static byte[] externalSignatureData(byte[] prepared, byte[] cert) ``` External signing, step 2: the bytes the HSM / card / KMS signs (DER signed attributes). On `NexPdfDocument` ### completeExternalSignature [#completeexternalsignature] ```java public static byte[] completeExternalSignature(byte[] prepared, byte[] cert, byte[] signature, int algorithm, String optionsJson) ``` External signing, step 3: the signed PDF. `algorithm` 0 = RSA PKCS#1 v1.5 SHA-256, 1 = ECDSA SHA-256 (DER or raw r||s). Options `{"tsa_url":"…","ltv":true`\} or null. On `NexPdfDocument` ### fromDocxTemplate [#fromdocxtemplate] ```java public static NexPdfDocument fromDocxTemplate(byte[] template, String dataJson, String optionsJson) ``` Fills a Word template with `dataJson` and converts it to PDF. Throws when it fails (e.g. a strict missing field). On `NexPdfDocument` ### fromHtmlTemplate [#fromhtmltemplate] ```java public static NexPdfDocument fromHtmlTemplate(String html, String dataJson, String optionsJson) ``` Fills an HTML template with `dataJson` and lays it out as a new PDF. On `NexPdfDocument` ### fillDocxTemplate [#filldocxtemplate] ```java public static byte[] fillDocxTemplate(byte[] template, String dataJson) ``` Fills a Word template; the new .docx (empty on failure, see `NexPdfJni#lastError()`). On `NexPdfDocument` ### fillTemplate [#filltemplate] ```java public int fillTemplate(String dataJson, String optionsJson) ``` Fills this PDF's form fields and text placeholders; the number filled, or -1. On `NexPdfDocument` ### addDocumentTimestamp [#adddocumenttimestamp] ```java public byte[] addDocumentTimestamp(String optionsJson) ``` This document with a PAdES document time-stamp from `tsa_url` (module: signatures). On `NexPdfDocument` ### prepareDocumentTimestamp [#preparedocumenttimestamp] ```java public byte[] prepareDocumentTimestamp(String optionsJson) ``` Own TSA / HSM, step 1 (then `NexPdfJni#documentTimestampRequest`, `NexPdfJni#completeDocumentTimestamp`). On `NexPdfDocument` ### replyToAnnotation [#replytoannotation] ```java public int replyToAnnotation(int pageIndex, int num, int gen, String author, String text) ``` Replies to annotation num / gen; the reply's object number, or 0. On `NexPdfDocument` ### annotationRepliesJson [#annotationrepliesjson] ```java public String annotationRepliesJson(int pageIndex, int num, int gen) ``` The thread under an annotation, oldest first, as JSON. On `NexPdfDocument` ### setAnnotationState [#setannotationstate] ```java public int setAnnotationState(int pageIndex, int num, int gen, String author, String state) ``` Sets a reviewer state ("Accepted", "Rejected", "Completed", "Marked", …); the state reply's number, or 0. On `NexPdfDocument` ### extractTablesJson [#extracttablesjson] ```java public String extractTablesJson(int pageIndex, String optionsJson) ``` Tables of `pageIndex` (< 0 = every page) as JSON. On `NexPdfDocument` ### extractKeyValuesJson [#extractkeyvaluesjson] ```java public String extractKeyValuesJson(String optionsJson) ``` On `NexPdfDocument` ### extractionPromptJson [#extractionpromptjson] ```java public String extractionPromptJson(String schemaJson, String optionsJson) ``` On `NexPdfDocument` ### extractionValidateJson [#extractionvalidatejson] ```java public String extractionValidateJson(String schemaJson, String answerJson) ``` Validates a language model's answer against the schema, grounded on this document's pages. On `NexPdfDocument` ### classifyJson [#classifyjson] ```java public String classifyJson(String labelsJson) ``` On `NexPdfDocument` ### xfaInfoJson [#xfainfojson] ```java public String xfaInfoJson() ``` On `NexPdfDocument` ### xfaExportData [#xfaexportdata] ```java public String xfaExportData(String format) ``` "xml" (null) or "json"; "" when there is no XFA. On `NexPdfDocument` ### xfaImportData [#xfaimportdata] ```java public int xfaImportData(String data, String format) ``` On `NexPdfDocument` ### xfaToAcroform [#xfatoacroform] ```java public int xfaToAcroform() ``` On `NexPdfDocument` ### xfaFlatten [#xfaflatten] ```java public int xfaFlatten() ``` On `NexPdfDocument` ### xfaRemove [#xfaremove] ```java public int xfaRemove() ``` On `NexPdfDocument` ### compareTextJson [#comparetextjson] ```java public String compareTextJson(NexPdfDocument newer, String optionsJson) ``` Word-level changes from this (old) document to `newer`, as JSON (module: viewer). On `NexPdfDocument` ### compareAnnotate [#compareannotate] ```java public byte[] compareAnnotate(NexPdfDocument newer, String optionsJson) ``` The comparison as a PDF with highlight annotations (open it with `#openBytes`). On `NexPdfDocument` ### readBarcodesJson [#readbarcodesjson] ```java public String readBarcodesJson(int pageIndex, String optionsJson) ``` Barcodes on `pageIndex` (< 0 = every page) as JSON, rectangles in PDF points. On `NexPdfDocument` ### readBarcodesImageJson [#readbarcodesimagejson] ```java public static String readBarcodesImageJson(byte[] image, String optionsJson) ``` Barcodes in a PNG or JPEG picture as JSON, rectangles in pixels. On `NexPdfDocument` ### addBarcode [#addbarcode] ```java public boolean addBarcode(int pageIndex, double llx, double lly, double urx, double ury, String format, String text) ``` Draws `text` as a vector barcode into the rectangle (PDF points). On `NexPdfDocument` ### validatePdfaJson [#validatepdfajson] ```java public String validatePdfaJson(String level) ``` On `NexPdfDocument` ### validatePdfuaJson [#validatepdfuajson] ```java public String validatePdfuaJson() ``` On `NexPdfDocument` ### convertPdfaLevel [#convertpdfalevel] ```java public boolean convertPdfaLevel(String level) ``` Converts to a PDF/A level; false when clauses still fail (`NexPdfJni#lastError()` lists them). On `NexPdfDocument` ### isClosed [#isclosed] ```java public boolean isClosed() ``` On `NexPdfDocument` ### close [#close] ```java public void close() ``` On `NexPdfDocument` ### setEventListener [#seteventlistener] ```java public static void setEventListener(EventListener l) ``` Receives the events of every reader (main thread). Pass null to stop. On `NexPdfReaderActivity (static)` ### closeCurrent [#closecurrent] ```java public static void closeCurrent() ``` Closes the reader that is on screen, if any (used by the React Native and Flutter bridges). On `NexPdfReaderActivity (static)` ### intent [#intent] ```java public static Intent intent(android.content.Context ctx, Uri document, String configJson) ``` An intent that opens `document` (content: or file: URI, may be null) with `configJson`. On `NexPdfReaderActivity (static)` ## Library and licensing [#library-and-licensing] ### version [#version] ```java public static native String version(); ``` The engine version. On `NexPdfJni (static)` · always available · C `nexpdf_version` ### licenseActivate [#licenseactivate] ```java public static native int licenseActivate(String keyOrXml, String platform, String appId); ``` Activates a license key or license XML for the process. Returns 2 (licensed), 1 (trial) or a negative error code (-1 malformed, -2 bad signature, -3 unsupported version, -4 expired, -5 not yet valid, -6 wrong platform, -7 wrong app id). On `NexPdfJni (static)` · always available · C `nexpdf_license_activate` ### licenseStatusJson [#licensestatusjson] ```java public static native String licenseStatusJson(); ``` The active license as JSON: `state` (`unlicensed`, `trial` or `licensed`), `licensee`, `id`, `tier`, `modules`, `expires_at`, `days_left` and `watermark`. On `NexPdfJni (static)` · always available · C `nexpdf_license_status_json` ### lastError [#lasterror] ```java public static native String lastError(); ``` Why the last call on this thread failed, or nothing. On `NexPdfJni (static)` · always available · C `nexpdf_last_error` ### clearError [#clearerror] ```java public static native void clearError(); ``` Clears the last error of this thread. On `NexPdfJni (static)` · always available · C `nexpdf_clear_error` ### invoke [#invoke] ```java public static native String invoke(String requestJson); ``` The whole API behind one JSON call, for bridges that only pass strings: `{"fn":"to_xlsx","args":[handle]}` returns `{"ok":true,"result":...}` or `{"ok":false,"error":"..."}`. Documents are handle numbers and byte buffers base64. On `NexPdfJni (static)` · always available · C `nexpdf_invoke` ### registerStandardFont [#registerstandardfont] ```java public static native boolean registerStandardFont(byte[] fontBytes); ``` Registers a Helvetica, Times or Courier compatible TrueType font (for example Liberation) used for non-embedded standard fonts and PDF/A. Needed only by builds without bundled fonts. 1 on success, 0 if the font is not such a font. On `NexPdfJni (static)` · always available · C `nexpdf_register_standard_font` ### hasBundledFonts [#hasbundledfonts] ```java public static native boolean hasBundledFonts(); ``` 1 when the Liberation fonts are compiled in, 0 in the lighter builds. On `NexPdfJni (static)` · always available · C `nexpdf_has_bundled_fonts` ### free [#free] ```java public static native void free(long handle); ``` Frees a document. On `NexPdfJni (static)` · always available · C `nexpdf_free` ## Opening and saving [#opening-and-saving] ### openBytes [#openbytes-1] ```java public static native long openBytes(byte[] pdfBytes); ``` Opens a PDF from bytes. JPEG, PNG and TIFF pictures are also accepted (one page per picture). On `NexPdfJni (static)` · always available · C `nexpdf_open_bytes` ### openBytesWithPassword [#openbyteswithpassword] ```java public static native long openBytesWithPassword(byte[] pdfBytes, String password); ``` Opens an encrypted PDF with its user or owner password (RC4, AES-128, AES-256). Fails with "password required" or "incorrect password" when the password is the problem. On `NexPdfJni (static)` · always available · C `nexpdf_open_bytes_with_password` ### fromHtml [#fromhtml-1] ```java public static native long fromHtml(String html); ``` Lays out HTML as a new PDF document. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_from_html` ### openOffice [#openoffice-1] ```java public static native long openOffice(byte[] data); ``` Converts Word, Excel or PowerPoint bytes (format detected) to a new PDF document. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_open_office` ### openEbook [#openebook-1] ```java public static native long openEbook(byte[] data); ``` Converts EPUB, FictionBook (.fb2, .fb2.zip), XPS/OpenXPS or a CBZ comic archive to a new PDF document. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_open_ebook` ### openImage [#openimage-1] ```java public static native long openImage(byte[] data); ``` Converts JPEG, PNG or TIFF bytes to a new PDF, one page per picture. On `NexPdfJni (static)` · always available · C `nexpdf_open_image` ### saveBytes [#savebytes-1] ```java public static native byte[] saveBytes(long handle); ``` The document, with every change, as PDF bytes (full rewrite). On `NexPdfJni (static)` · always available · C `nexpdf_save_bytes` ### saveLinearized [#savelinearized-1] ```java public static native byte[] saveLinearized(long handle); ``` A linearized ("Fast Web View") PDF: the first page shows before the download ends. On `NexPdfJni (static)` · always available · C `nexpdf_save_linearized` ## Pages and rendering [#pages-and-rendering] ### pageCount [#pagecount-1] ```java public static native int pageCount(long handle); ``` Number of pages. On `NexPdfJni (static)` · always available · C `nexpdf_page_count` ### pageWidth [#pagewidth-1] ```java public static native double pageWidth(long handle, int pageIndex); ``` Displayed page width in points (crop box, rotation and /UserUnit applied). On `NexPdfJni (static)` · always available · C `nexpdf_page_width` ### pageHeight [#pageheight-1] ```java public static native double pageHeight(long handle, int pageIndex); ``` Displayed page height in points (crop box, rotation and /UserUnit applied). On `NexPdfJni (static)` · always available · C `nexpdf_page_height` ### pageViewJson [#pageviewjson] ```java public static native String pageViewJson(long handle, int pageIndex); ``` How the page is displayed: `width`, `height`, `rotation`, `user_unit`, `crop` and the PDF-to-display matrix `to_display`. On `NexPdfJni (static)` · always available · C `nexpdf_page_view_json` ### renderPagePng [#renderpagepng-1] ```java public static native byte[] renderPagePng(long handle, int pageIndex, double dpi); ``` Renders a page to PNG at the given resolution (dots per inch). Unlicensed and trial renders carry a watermark. On `NexPdfJni (static)` · always available · C `nexpdf_render_page_png` ### renderThumbPng [#renderthumbpng] ```java public static native byte[] renderThumbPng(long handle, int pageIndex, int maxDim); ``` Renders a thumbnail PNG whose longer side is at most `max_dim` pixels. On `NexPdfJni (static)` · always available · C `nexpdf_render_thumb_png` ### setOverprint [#setoverprint] ```java public static native boolean setOverprint(long handle, int mode); ``` Overprint simulation for later renders: 0 = PDF/X documents only (default), 1 = always, 2 = never. On `NexPdfJni (static)` · always available · C `nexpdf_set_overprint` ## Text, search and assistant [#text-search-and-assistant] ### extractPageText [#extractpagetext] ```java public static native String extractPageText(long handle, int pageIndex); ``` The text of a page in reading order. On `NexPdfJni (static)` · always available · C `nexpdf_extract_page_text` ### extractMarkdown [#extractmarkdown] ```java public static native String extractMarkdown(long handle); ``` The whole document as Markdown (headings, lists, tables). On `NexPdfJni (static)` · always available · C `nexpdf_extract_markdown` ### searchJson [#searchjson-1] ```java public static native String searchJson(long handle, String query); ``` Finds a text in every page (case-insensitive). Returns a JSON array of hits: `page`, `context` and the rectangle `llx`, `lly`, `urx`, `ury` in PDF points. On `NexPdfJni (static)` · always available · C `nexpdf_search_json` ### pageBlocksJson [#pageblocksjson] ```java public static native String pageBlocksJson(long handle, int pageIndex); ``` The text blocks of a page as JSON: `text`, font `size` and the rectangle `llx`, `lly`, `urx`, `ury`. On `NexPdfJni (static)` · always available · C `nexpdf_page_blocks_json` ### askDocument [#askdocument] ```java public static native String askDocument(long handle, String question, int k, int maxChars); ``` Document assistant retrieval, offline (BM25): the `k` passages most relevant to a question and a page-tagged context of at most `max_chars` characters (0 = 200000) to send to a language model. Returns `{"passages":[{"page","text","score"}],"context":"...","context_pages":[...]}`. On `NexPdfJni (static)` · always available · C `nexpdf_ask_document` ## Conversion [#conversion] ### toHtml [#tohtml] ```java public static native String toHtml(long handle); ``` The document as HTML. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_to_html` ### toJson [#tojson-1] ```java public static native String toJson(long handle); ``` The document content as JSON. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_to_json` ### toXml [#toxml] ```java public static native String toXml(long handle); ``` The document content as XML. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_to_xml` ### toCsv [#tocsv] ```java public static native String toCsv(long handle); ``` Tables of the document as CSV. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_to_csv` ### toRtf [#tortf] ```java public static native String toRtf(long handle); ``` The document as RTF. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_to_rtf` ### toDocx [#todocx-1] ```java public static native byte[] toDocx(long handle); ``` The document as a Word (.docx) file. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_to_docx` ### toXlsx [#toxlsx] ```java public static native byte[] toXlsx(long handle); ``` The document as an Excel workbook, one sheet per page. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_to_xlsx` ### toPptx [#topptx] ```java public static native byte[] toPptx(long handle); ``` The document as a PowerPoint presentation, one slide per page. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_to_pptx` ### reflowHtml [#reflowhtml] ```java public static native String reflowHtml(long handle, String optionsJson); ``` The text as responsive HTML for small screens. Options (may be omitted): `{"pages":[0],"images":true,"full_page":true,"title":"..."}`. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_to_reflow_html` ## Templates [#templates] ### templateDocxToPdf [#templatedocxtopdf] ```java public static native long templateDocxToPdf(byte[] template, String dataJson, String optionsJson); ``` Fills a Word template with JSON data and converts it to a new PDF document. Options: `{"strict":false,"locale":"en"}`; with `strict` a missing field fails the call. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_template_docx_to_pdf` ### templateDocxFill [#templatedocxfill] ```java public static native byte[] templateDocxFill(byte[] template, String dataJson); ``` Fills a Word template with JSON data and returns the new .docx bytes. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_template_docx_fill` ### templateHtmlToPdf [#templatehtmltopdf] ```java public static native long templateHtmlToPdf(String html, String dataJson, String optionsJson); ``` Fills an HTML template with JSON data (values HTML-escaped, `{{{raw}}}` not) and lays it out as a new PDF document. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_template_html_to_pdf` ### templateFillPdf [#templatefillpdf] ```java public static native int templateFillPdf(long handle, String dataJson, String optionsJson); ``` Fills a PDF template in place: AcroForm fields by name and placeholders in the page text. Options `{"flatten","fields","text","strict","locale"}`. Returns the number of fields and text lines filled. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_template_fill_pdf` ## Structured extraction and barcodes [#structured-extraction-and-barcodes] ### extractTablesJson [#extracttablesjson-1] ```java public static native String extractTablesJson(long handle, int pageIndex, String optionsJson); ``` Ruled and unruled tables of a page (every page when the index is negative) with cells, spans, CSV and Markdown. Options `{"ruled","unruled","min_unruled_lines"}`. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_extract_tables_json` ### extractKeyValuesJson [#extractkeyvaluesjson-1] ```java public static native String extractKeyValuesJson(long handle, String optionsJson); ``` Label/value pairs from the layout and typed entities (dates, amounts, IBANs, e-mails, phones, VAT numbers) with normalised values. Options `{"pages","date_order"}`. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_extract_key_values_json` ### extractionPromptJson [#extractionpromptjson-1] ```java public static native String extractionPromptJson(long handle, String schemaJson, String optionsJson); ``` A prompt (`system`, `prompt`, `response_schema`) for extracting a JSON schema with the language model of your choice. The engine makes no network calls. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_extraction_prompt_json` ### extractionValidateJson [#extractionvalidatejson-1] ```java public static native String extractionValidateJson(long handle, String schemaJson, String answerJson); ``` Validates and coerces a model answer against the schema and grounds each value on the pages: `valid`, `value`, `errors`, `warnings`, `fields`. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_extraction_validate_json` ### classifyDocumentJson [#classifydocumentjson] ```java public static native String classifyDocumentJson(long handle, String labelsJson); ``` Classifies the document into one of the given labels by keywords, with scores and a prompt for LLM classification. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_classify_document_json` ### readBarcodesJson [#readbarcodesjson-1] ```java public static native String readBarcodesJson(long handle, int pageIndex, String optionsJson); ``` Reads the barcodes of a page (every page when the index is negative): QR, Data Matrix, Aztec, PDF417, Code 128/39/93, EAN/UPC, ITF, Codabar and more, with positions in PDF points. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_read_barcodes_json` ### readBarcodesImageJson [#readbarcodesimagejson-1] ```java public static native String readBarcodesImageJson(byte[] image, String optionsJson); ``` Reads the barcodes of a PNG or JPEG image, with positions in pixels. On `NexPdfJni (static)` · module `conversion` · C `nexpdf_read_barcodes_image_json` ### addBarcode [#addbarcode-1] ```java public static native boolean addBarcode(long handle, int pageIndex, double llx, double lly, double urx, double ury, String format, String text); ``` Draws text as a vector barcode (white background, quiet zone) into a rectangle of a page, in PDF points. On `NexPdfJni (static)` · module `editor` · C `nexpdf_add_barcode` ## Annotations [#annotations] ### addAnnotation [#addannotation] ```java public static native boolean addAnnotation(long handle, int pageIndex, String kind, String colorHex, double opacity, String contents, double llx, double lly, double urx, double ury); ``` Adds an annotation. `kind` is a PDF annotation subtype such as `Highlight`, `Underline`, `StrikeOut`, `Squiggly`, `Square`, `Circle`, `FreeText` or `Text`; text markup is fitted to the lines under the rectangle. Colour is `#RRGGBB`, the rectangle is in PDF points. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_add_annotation` ### addInk [#addink] ```java public static native boolean addInk(long handle, int pageIndex, String colorHex, double strokeWidth, double opacity, String coords); ``` Adds a freehand ink annotation. `coords` is `"x,y;x,y;..."` in PDF points. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_add_ink` ### addLine [#addline] ```java public static native boolean addLine(long handle, int pageIndex, String kind, String colorHex, double opacity, double strokeWidth, double x1, double y1, double x2, double y2); ``` Adds a line or arrow (`kind` is `Line` or `Arrow`) from (x1, y1) to (x2, y2) in PDF points. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_add_line` ### annotationsJson [#annotationsjson] ```java public static native String annotationsJson(long handle, int pageIndex); ``` The annotations of a page as JSON: `num`, `gen`, `kind`, `color`, `contents` and the rectangle. On `NexPdfJni (static)` · always available · C `nexpdf_annotations_json` ### removeAnnotation [#removeannotation] ```java public static native boolean removeAnnotation(long handle, int pageIndex, int num, int gen); ``` Removes the annotation with object number `num` and generation `gen` from a page. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_remove_annotation` ### moveAnnotation [#moveannotation] ```java public static native boolean moveAnnotation(long handle, int num, int gen, double dx, double dy); ``` Moves an annotation by (dx, dy) PDF points. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_move_annotation` ### setAnnotationContents [#setannotationcontents] ```java public static native boolean setAnnotationContents(long handle, int num, int gen, String contents); ``` Replaces the text contents of an annotation. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_set_annotation_contents` ### exportXfdf [#exportxfdf] ```java public static native String exportXfdf(long handle); ``` Exports every annotation as an XFDF document. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_export_xfdf` ### importXfdf [#importxfdf] ```java public static native int importXfdf(long handle, String xfdf); ``` Imports annotations from an XFDF document. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_import_xfdf` ### flattenAnnotations [#flattenannotations] ```java public static native int flattenAnnotations(long handle, int pageIndex); ``` Burns annotations into the page content. A negative page index flattens every page. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_flatten_annotations` ### addImageStamp [#addimagestamp] ```java public static native boolean addImageStamp(long handle, int pageIndex, double llx, double lly, double urx, double ury, byte[] rgba, int width, int height, double opacity); ``` Adds a picture stamp annotation from RGBA pixels (transparency kept). 1 on success. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_add_image_stamp` ### addMeasurement [#addmeasurement] ```java public static native String addMeasurement(long handle, int pageIndex, String json); ``` Stores a measurement: `{"kind":"distance|perimeter|area","points":[[x,y],...],"unit":"mm","per_point":0.3528,"label":"1:100","color":"#2f54d6"}`. Returns `{"num","gen","value","text"}`. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_add_measurement` ### measurementsJson [#measurementsjson] ```java public static native String measurementsJson(long handle); ``` The stored measurements as JSON. On `NexPdfJni (static)` · always available · C `nexpdf_measurements_json` ### addFileAttachmentAnnot [#addfileattachmentannot] ```java public static native boolean addFileAttachmentAnnot(long handle, int pageIndex, double x, double y, String name, byte[] data, String mime, String description); ``` Adds a paperclip annotation carrying a file; (x, y) is the top-left corner of the icon in PDF points. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_add_file_attachment_annot` ### addInkSignature [#addinksignature] ```java public static native boolean addInkSignature(long handle, int pageIndex, String colorHex, double strokeWidth, String strokes); ``` Adds a handwritten signature: an ink annotation with several strokes (`"x,y;x,y|x,y;x,y"`, PDF points) and subject "Signature". Visual only; use a PAdES signature for a cryptographic one. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_add_ink_signature` ### replyToAnnotation [#replytoannotation-1] ```java public static native int replyToAnnotation(long handle, int pageIndex, int num, int gen, String author, String text); ``` Adds a reply by `author` to an annotation (or to another reply). Returns the reply object number (generation 0). On `NexPdfJni (static)` · module `annotations` · C `nexpdf_reply_to_annotation` ### annotationRepliesJson [#annotationrepliesjson-1] ```java public static native String annotationRepliesJson(long handle, int pageIndex, int num, int gen); ``` The thread under an annotation, oldest first: `num`, `gen`, `in_reply_to`, `author`, `date`, `text`, `state`, `state_model`. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_annotation_replies_json` ### setAnnotationState [#setannotationstate-1] ```java public static native int setAnnotationState(long handle, int pageIndex, int num, int gen, String author, String state); ``` Sets a review state (`Accepted`, `Rejected`, `Cancelled`, `Completed`, `None`) or marked state (`Marked`, `Unmarked`) as a hidden state reply. Returns its object number. On `NexPdfJni (static)` · module `annotations` · C `nexpdf_set_annotation_state` ## Forms [#forms] ### formFieldsJson [#formfieldsjson] ```java public static native String formFieldsJson(long handle); ``` The form fields as JSON: `name`, `kind`, `value`, `page`, rectangle, `read_only` and `required`. On `NexPdfJni (static)` · module `forms` · C `nexpdf_form_fields_json` ### fillFormField [#fillformfield] ```java public static native boolean fillFormField(long handle, String name, String value); ``` Sets a field value as a viewer would: the keystroke and validate scripts check the value, then every calculated field is recomputed. Check boxes take `"true"` or `"false"`, list fields the option text. On `NexPdfJni (static)` · module `forms` · C `nexpdf_fill_form_field` ### addFormField [#addformfield] ```java public static native boolean addFormField(long handle, int pageIndex, String kind, String name, double llx, double lly, double urx, double ury); ``` Adds a form field named `name` in a rectangle of a page. `kind`: `text` (default), `checkbox`, `radio`, `combobox`, `listbox`, `button`, `signature` or `barcode`. On `NexPdfJni (static)` · module `forms` · C `nexpdf_add_form_field` ### flattenForms [#flattenforms] ```java public static native int flattenForms(long handle); ``` Burns the form fields into the page content. On `NexPdfJni (static)` · module `forms` · C `nexpdf_flatten_forms` ### recalculateForms [#recalculateforms] ```java public static native int recalculateForms(long handle); ``` Runs every calculate script; returns how many fields changed. On `NexPdfJni (static)` · module `forms` · C `nexpdf_recalculate_forms` ### exportFormJson [#exportformjson] ```java public static native String exportFormJson(long handle); ``` The field values as a JSON object. On `NexPdfJni (static)` · module `forms` · C `nexpdf_export_form_json` ### importFormJson [#importformjson] ```java public static native int importFormJson(long handle, String json); ``` Fills fields from a JSON object of names and values. On `NexPdfJni (static)` · module `forms` · C `nexpdf_import_form_json` ### exportFormFdf [#exportformfdf] ```java public static native byte[] exportFormFdf(long handle, String pdfName); ``` The field values as an FDF file; `pdf_name` is the file name recorded in it. On `NexPdfJni (static)` · module `forms` · C `nexpdf_export_form_fdf` ### importFormFdf [#importformfdf] ```java public static native int importFormFdf(long handle, byte[] fdf); ``` Fills fields from an FDF file. On `NexPdfJni (static)` · module `forms` · C `nexpdf_import_form_fdf` ### exportFormXfdf [#exportformxfdf] ```java public static native String exportFormXfdf(long handle, String pdfName); ``` The field values as XFDF. On `NexPdfJni (static)` · module `forms` · C `nexpdf_export_form_xfdf` ### importFormXfdf [#importformxfdf] ```java public static native int importFormXfdf(long handle, String xfdf); ``` Fills fields from XFDF. On `NexPdfJni (static)` · module `forms` · C `nexpdf_import_form_xfdf` ## XFA forms [#xfa-forms] ### xfaInfoJson [#xfainfojson-1] ```java public static native String xfaInfoJson(long handle); ``` Whether the document has XFA, whether it is dynamic, field and data counts and the XDP packets. On `NexPdfJni (static)` · module `forms` · C `nexpdf_xfa_info_json` ### xfaExportData [#xfaexportdata-1] ```java public static native String xfaExportData(long handle, String format); ``` The XFA data as `xml` (default) or flat `json` (`{"path":"value"}`). Fails when the document has no XFA. On `NexPdfJni (static)` · module `forms` · C `nexpdf_xfa_export_data` ### xfaImportData [#xfaimportdata-1] ```java public static native int xfaImportData(long handle, String data, String format); ``` Imports XFA data: XML replaces the data, JSON sets the given values. Static forms get their AcroForm fields updated. Returns the number of values imported. On `NexPdfJni (static)` · module `forms` · C `nexpdf_xfa_import_data` ### xfaToAcroform [#xfatoacroform-1] ```java public static native int xfaToAcroform(long handle); ``` Converts to a plain AcroForm PDF and removes XFA; dynamic forms are laid out into new pages and scripts run first. Text fields keep their formatted display value as `/V`. Returns the number of AcroForm fields. On `NexPdfJni (static)` · module `forms` · C `nexpdf_xfa_to_acroform` ### xfaFlatten [#xfaflatten-1] ```java public static native int xfaFlatten(long handle); ``` Converts and flattens the XFA form: a plain PDF with the values drawn. Returns the number of flattened widgets. On `NexPdfJni (static)` · module `forms` · C `nexpdf_xfa_flatten` ### xfaRemove [#xfaremove-1] ```java public static native int xfaRemove(long handle); ``` Removes XFA and keeps the AcroForm fields and pages: 1 removed, 0 no XFA. On `NexPdfJni (static)` · module `forms` · C `nexpdf_xfa_remove` ## Page editing [#page-editing] ### rotatePage [#rotatepage] ```java public static native boolean rotatePage(long handle, int pageIndex, int degrees); ``` Rotates a page by a multiple of 90 degrees. On `NexPdfJni (static)` · module `editor` · C `nexpdf_rotate_page` ### deletePage [#deletepage] ```java public static native boolean deletePage(long handle, int pageIndex); ``` Deletes a page. On `NexPdfJni (static)` · module `editor` · C `nexpdf_delete_page` ### duplicatePage [#duplicatepage] ```java public static native boolean duplicatePage(long handle, int pageIndex); ``` Inserts a copy of a page after it. On `NexPdfJni (static)` · module `editor` · C `nexpdf_duplicate_page` ### addBlankPage [#addblankpage] ```java public static native boolean addBlankPage(long handle); ``` Appends a blank page. On `NexPdfJni (static)` · module `editor` · C `nexpdf_add_blank_page` ### reversePages [#reversepages] ```java public static native boolean reversePages(long handle); ``` Reverses the page order. On `NexPdfJni (static)` · module `editor` · C `nexpdf_reverse_pages` ### movePage [#movepage] ```java public static native boolean movePage(long handle, int from, int to); ``` Moves the page at `from` to index `to`. On `NexPdfJni (static)` · module `editor` · C `nexpdf_move_page` ### cropPage [#croppage] ```java public static native boolean cropPage(long handle, int pageIndex, double llx, double lly, double urx, double ury); ``` Sets the crop box of a page (PDF points). On `NexPdfJni (static)` · module `editor` · C `nexpdf_crop_page` ### extractPages [#extractpages] ```java public static native long extractPages(long handle, int[] pageIndices); ``` A new document made of the given pages (split). On `NexPdfJni (static)` · module `editor` · C `nexpdf_extract_pages` ### appendDocument [#appenddocument] ```java public static native boolean appendDocument(long handle, long other); ``` Appends the pages of another document (merge). On `NexPdfJni (static)` · module `editor` · C `nexpdf_append_document` ### insertImagePages [#insertimagepages] ```java public static native int insertImagePages(long handle, int index, byte[] data); ``` Inserts the pictures of a JPEG, PNG or TIFF file as pages before `index` (clamped; the page count appends). Returns the number of pages added. On `NexPdfJni (static)` · always available · C `nexpdf_insert_image_pages` ### setPageBackground [#setpagebackground] ```java public static native int setPageBackground(long handle, String optionsJson, byte[] rgb, int width, int height); ``` Sets a page background: a colour and/or an RGB picture. Options: `{"color":"#fbf4e2","fit":"cover|stretch|center","scale":1,"opacity":1,"pages":[]}`. Returns the pages changed. On `NexPdfJni (static)` · module `editor` · C `nexpdf_set_page_background` ### removePageBackground [#removepagebackground] ```java public static native int removePageBackground(long handle, String pagesJson); ``` Removes NexPDF backgrounds from the pages in `pages_json` (`"[0,2]"`), or from every page. On `NexPdfJni (static)` · module `editor` · C `nexpdf_remove_page_background` ## Content editing [#content-editing] ### pageContentJson [#pagecontentjson] ```java public static native String pageContentJson(long handle, int pageIndex); ``` The text lines and images of a page as JSON: `id`, `kind` (`text` or `image`), `text`, `rect`, `size`, `color`, `font`, `family`, `bold`, `italic`. Ids stay valid until the next edit of that page. On `NexPdfJni (static)` · module `editor` · C `nexpdf_page_content_json` ### editText [#edittext] ```java public static native boolean editText(long handle, int pageIndex, String id, String changeJson); ``` Edits a text line: `{text?, size?, color?, dx?, dy?, family?, bold?, italic?}`. Empty text deletes it. On `NexPdfJni (static)` · module `editor` · C `nexpdf_edit_text` ### addPageText [#addpagetext] ```java public static native boolean addPageText(long handle, int pageIndex, String json); ``` Adds editable page text: `{text, x, y (baseline), size, color, family, bold, italic}`. On `NexPdfJni (static)` · module `editor` · C `nexpdf_add_page_text` ### deleteContent [#deletecontent] ```java public static native boolean deleteContent(long handle, int pageIndex, String id); ``` Deletes a text line or an image of the page content. On `NexPdfJni (static)` · module `editor` · C `nexpdf_delete_content` ### transformImage [#transformimage] ```java public static native boolean transformImage(long handle, int pageIndex, String id, double llx, double lly, double urx, double ury); ``` Moves or resizes an image to a rectangle (PDF points). On `NexPdfJni (static)` · module `editor` · C `nexpdf_transform_image` ### replaceImage [#replaceimage] ```java public static native boolean replaceImage(long handle, int pageIndex, String id, byte[] rgb, int width, int height); ``` Replaces an image with RGB pixels (width x height x 3 bytes). On `NexPdfJni (static)` · module `editor` · C `nexpdf_replace_image` ### editTextBlock [#edittextblock] ```java public static native boolean editTextBlock(long handle, int pageIndex, String text, String colorHex, double fontSize, boolean bold, boolean italic, boolean replaceExisting, double llx, double lly, double urx, double ury); ``` Writes a text block into a rectangle with colour, size and style, optionally replacing the text already there. On `NexPdfJni (static)` · module `editor` · C `nexpdf_edit_text_block` ## Metadata, bookmarks, layers and attachments [#metadata-bookmarks-layers-and-attachments] ### metadataJson [#metadatajson] ```java public static native String metadataJson(long handle); ``` The document information (title, author, subject, keywords, ...) as JSON. On `NexPdfJni (static)` · always available · C `nexpdf_metadata_json` ### setMetadata [#setmetadata] ```java public static native boolean setMetadata(long handle, String title, String author, String subject, String keywords); ``` Sets the title, author, subject and keywords. Omitted (null) values keep the current one. On `NexPdfJni (static)` · module `editor` · C `nexpdf_set_metadata` ### outlinesJson [#outlinesjson] ```java public static native String outlinesJson(long handle); ``` The bookmarks as JSON: `[{"title","page","children":[...]}]`. On `NexPdfJni (static)` · always available · C `nexpdf_outlines_json` ### setOutlinesJson [#setoutlinesjson] ```java public static native boolean setOutlinesJson(long handle, String json); ``` Replaces the bookmarks with a JSON tree in the same shape. On `NexPdfJni (static)` · module `editor` · C `nexpdf_set_outlines_json` ### pageLabelsJson [#pagelabelsjson-1] ```java public static native String pageLabelsJson(long handle); ``` Page labels: `{"labels":["i","ii","1"],"ranges":[{"start":0,"style":"roman","prefix":"","first":1}]}`. On `NexPdfJni (static)` · always available · C `nexpdf_page_labels_json` ### setPageLabelsJson [#setpagelabelsjson-1] ```java public static native boolean setPageLabelsJson(long handle, String rangesJson); ``` Sets the page label ranges (`[]` removes the labels). Styles: `decimal`, `roman`, `ROMAN`, `letters`, `LETTERS`, `none`. On `NexPdfJni (static)` · module `editor` · C `nexpdf_set_page_labels_json` ### layersJson [#layersjson] ```java public static native String layersJson(long handle); ``` The optional content groups (layers): `[{"num","gen","name","visible","printable"}]`. On `NexPdfJni (static)` · always available · C `nexpdf_layers_json` ### setLayerVisible [#setlayervisible] ```java public static native boolean setLayerVisible(long handle, int num, int gen, boolean visible); ``` Shows or hides a layer. On `NexPdfJni (static)` · always available · C `nexpdf_set_layer_visible` ### attachmentsJson [#attachmentsjson] ```java public static native String attachmentsJson(long handle); ``` The embedded files: `[{"name","description","mime","size","page"}]`; `page` is null for document-level files. On `NexPdfJni (static)` · always available · C `nexpdf_attachments_json` ### attachmentData [#attachmentdata] ```java public static native byte[] attachmentData(long handle, String name); ``` The bytes of an embedded file. On `NexPdfJni (static)` · always available · C `nexpdf_attachment_data` ### addAttachment [#addattachment] ```java public static native boolean addAttachment(long handle, String name, byte[] data, String mime, String description); ``` Embeds a file at document level. On `NexPdfJni (static)` · module `editor` · C `nexpdf_add_attachment` ### removeAttachment [#removeattachment] ```java public static native boolean removeAttachment(long handle, String name); ``` Removes an embedded file. On `NexPdfJni (static)` · module `editor` · C `nexpdf_remove_attachment` ## Encryption, watermarks and stamping [#encryption-watermarks-and-stamping] ### encryptAes256 [#encryptaes256] ```java public static native boolean encryptAes256(long handle, String userPw, String ownerPw); ``` Encrypts with AES-256 using a user (open) password and an owner password. On `NexPdfJni (static)` · module `security` · C `nexpdf_encrypt_aes256` ### encryptWithPermissions [#encryptwithpermissions] ```java public static native boolean encryptWithPermissions(long handle, String userPw, String ownerPw, int permissions); ``` Encrypts with AES-256 and a permission mask: print 1, modify 2, copy 4, annotate 8, fill forms 16, assemble 32. On `NexPdfJni (static)` · module `security` · C `nexpdf_encrypt_with_permissions` ### securityJson [#securityjson] ```java public static native String securityJson(long handle); ``` The encryption state: `{"encrypted","revision","owner","print","modify","copy","annotate","fill_forms","assemble"}`. On `NexPdfJni (static)` · always available · C `nexpdf_security_json` ### removePassword [#removepassword] ```java public static native boolean removePassword(long handle, String ownerPassword); ``` Removes the protection. Needs owner access: the document was opened with the owner password, or pass it here. On `NexPdfJni (static)` · module `security` · C `nexpdf_remove_password` ### addWatermark [#addwatermark] ```java public static native boolean addWatermark(long handle, String text); ``` Stamps a text watermark on every page. On `NexPdfJni (static)` · module `security` · C `nexpdf_add_watermark` ### removeWatermarks [#removewatermarks] ```java public static native int removeWatermarks(long handle); ``` Removes the watermarks NexPDF added. On `NexPdfJni (static)` · module `security` · C `nexpdf_remove_watermarks` ### addHeaderFooter [#addheaderfooter] ```java public static native boolean addHeaderFooter(long handle, String header, String footer, double fontSize); ``` Adds a header and/or footer to every page. `{page}` and `{total}` are replaced; a font size of 0 or less uses the default. On `NexPdfJni (static)` · module `security` · C `nexpdf_add_header_footer` ### addBates [#addbates] ```java public static native boolean addBates(long handle, String prefix, long start, int digits); ``` Adds Bates numbering: `prefix`, first number and number of digits. On `NexPdfJni (static)` · module `security` · C `nexpdf_add_bates` ## Redaction [#redaction] ### applyRedaction [#applyredaction] ```java public static native boolean applyRedaction(long handle, int pageIndex, double llx, double lly, double urx, double ury, boolean fillWhite); ``` Permanently removes the text, images and annotations under a rectangle and paints an opaque box over it, black or white. On `NexPdfJni (static)` · module `redaction` · C `nexpdf_apply_redaction` ### redactMatches [#redactmatches] ```java public static native int redactMatches(long handle, String query, int mode, boolean fillWhite); ``` Finds and permanently redacts every match. `mode`: 0 = text, 1 = regular expression, 2 = pattern id (`email`, `phone`, `credit-card`, `iban`, `pt-nif`, `us-ssn`, `ipv4`, `url`, `date`). Returns the number of areas redacted. On `NexPdfJni (static)` · module `redaction` · C `nexpdf_redact_matches` ## Digital signatures [#digital-signatures] ### signPades [#signpades] ```java public static native byte[] signPades(long handle, String signer, String reason, String location); ``` Signs with a new self-signed test certificate (PAdES B-B) and returns the signed file. Write the bytes as they are: saving the document again breaks the signature. On `NexPdfJni (static)` · module `signatures` · C `nexpdf_sign_pades` ### signPkcs12 [#signpkcs12] ```java public static native byte[] signPkcs12(long handle, byte[] p12, String password, String optionsJson); ``` Signs with a PKCS#12 (.p12/.pfx) identity and returns the signed file. Options: `{"name","reason","location","contact","field","tsa_url","ltv":true,"appearance":{"page":0,"rect":[llx,lly,urx,ury],"ink":"x,y;x,y|...","text":"..."}}`. Without a .p12 a self-signed certificate is created. On `NexPdfJni (static)` · module `signatures` · C `nexpdf_sign_pkcs12` ### pkcs12InfoJson [#pkcs12infojson] ```java public static native String pkcs12InfoJson(byte[] p12, String password); ``` The certificate summary of a PKCS#12 file; fails with "incorrect password" on a wrong password. On `NexPdfJni (static)` · module `signatures` · C `nexpdf_pkcs12_info_json` ### prepareExternalSignature [#prepareexternalsignature-1] ```java public static native byte[] prepareExternalSignature(long handle, byte[] cert, String optionsJson); ``` External signing (HSM, smart card, cloud KMS), step 1: a PDF with an empty signature for the signer certificate (PEM or DER, optionally followed by its chain). Options as for PKCS#12 signing. On `NexPdfJni (static)` · module `signatures` · C `nexpdf_prepare_external_signature` ### externalSignatureData [#externalsignaturedata-1] ```java public static native byte[] externalSignatureData(byte[] prepared, byte[] cert); ``` External signing, step 2: the bytes to sign (DER signed attributes; sign their SHA-256 on devices that take a digest). On `NexPdfJni (static)` · module `signatures` · C `nexpdf_external_signature_data` ### completeExternalSignature [#completeexternalsignature-1] ```java public static native byte[] completeExternalSignature(byte[] prepared, byte[] cert, byte[] signature, int algorithm, String optionsJson); ``` External signing, step 3: embeds the signature and returns the signed PDF. `algorithm`: 0 RSA PKCS#1 v1.5 SHA-256, 1 ECDSA SHA-256. Options: `{"tsa_url":"...","ltv":true}`. On `NexPdfJni (static)` · module `signatures` · C `nexpdf_complete_external_signature` ### verifySignaturesJson [#verifysignaturesjson] ```java public static native String verifySignaturesJson(byte[] pdfBytes); ``` Verifies every signature of a signed file (its exact bytes). Each entry has `field`, `signer`, `subject`, `digest_ok`, `signature_ok`, `covers_whole_document`, `reason`, `signing_time`, `timestamp_ok`, `chain_ok`, `trusted`, `revocation`, `ltv`, `level` and more. On `NexPdfJni (static)` · always available · C `nexpdf_verify_signatures_json` ### verifySignaturesWithRootsJson [#verifysignatureswithrootsjson] ```java public static native String verifySignaturesWithRootsJson(byte[] pdfBytes, String rootsPem); ``` Verifies the signatures treating the PEM certificates in `roots_pem` as trust anchors. On `NexPdfJni (static)` · module `signatures` · C `nexpdf_verify_signatures_with_roots_json` ### addLtv [#addltv] ```java public static native byte[] addLtv(byte[] pdfBytes); ``` Adds long-term validation data (DSS with OCSP responses and CRLs) to a signed file. On `NexPdfJni (static)` · module `signatures` · C `nexpdf_add_ltv` ### addDocumentTimestamp [#adddocumenttimestamp-1] ```java public static native byte[] addDocumentTimestamp(long handle, String optionsJson); ``` Adds an RFC 3161 document timestamp from a TSA (PAdES B-LTA). Options: `{"tsa_url" (required),"hash","field","reserved","ltv"}`; with `ltv` the validation data of earlier signatures goes into the DSS first. Returns the new file. On `NexPdfJni (static)` · module `signatures` · C `nexpdf_add_document_timestamp` ### addDocumentTimestampBytes [#adddocumenttimestampbytes] ```java public static native byte[] addDocumentTimestampBytes(byte[] pdfBytes, String optionsJson); ``` Adds a document timestamp to the bytes of a PDF file (for example straight from signing). Same options. Returns the new file. On `NexPdfJni (static)` · module `signatures` · C `nexpdf_add_document_timestamp_bytes` ### prepareDocumentTimestamp [#preparedocumenttimestamp-1] ```java public static native byte[] prepareDocumentTimestamp(long handle, String optionsJson); ``` Document timestamp from your own TSA or HSM, step 1: the PDF with an empty timestamp (options as for adding one, without `tsa_url`). On `NexPdfJni (static)` · module `signatures` · C `nexpdf_prepare_document_timestamp` ### documentTimestampRequest [#documenttimestamprequest] ```java public static native byte[] documentTimestampRequest(byte[] prepared, String hash); ``` Document timestamp, step 2: the DER TimeStampReq to send to the TSA as `application/timestamp-query` (hash SHA-256 by default). On `NexPdfJni (static)` · module `signatures` · C `nexpdf_document_timestamp_request` ### completeDocumentTimestamp [#completedocumenttimestamp] ```java public static native byte[] completeDocumentTimestamp(byte[] prepared, byte[] token); ``` Document timestamp, step 3: the timestamped PDF, from the prepared file and the TSA token (TimeStampResp or TimeStampToken). On `NexPdfJni (static)` · module `signatures` · C `nexpdf_complete_document_timestamp` ## PDF/A, PDF/X and PDF/UA [#pdfa-pdfx-and-pdfua] ### convertPdfA [#convertpdfa] ```java public static native boolean convertPdfA(long handle); ``` Converts the document to PDF/A (ISO 19005) for archiving. On `NexPdfJni (static)` · module `standards` · C `nexpdf_convert_pdfa` ### convertPdfX [#convertpdfx] ```java public static native boolean convertPdfX(long handle); ``` Converts the document to PDF/X for print exchange. On `NexPdfJni (static)` · module `standards` · C `nexpdf_convert_pdfx` ### autoTag [#autotag] ```java public static native String autoTag(long handle, String lang, boolean force); ``` Tags the document for accessibility (PDF/UA structure tree, language, title, metadata). `lang` is a BCP 47 tag (default en-US); `force` re-tags a document that is already tagged. Returns a JSON report. On `NexPdfJni (static)` · module `standards` · C `nexpdf_auto_tag` ### validatePdfaJson [#validatepdfajson-1] ```java public static native String validatePdfaJson(long handle, String level); ``` Rule-based PDF/A validation for `1a` to `4f` (the declared level, or 2b, when empty): `compliant`, `level` and `failures` with `clause`, `message`, `page` and `object`. On `NexPdfJni (static)` · module `standards` · C `nexpdf_validate_pdfa_json` ### validatePdfuaJson [#validatepdfuajson-1] ```java public static native String validatePdfuaJson(long handle); ``` PDF/UA validation (PDF/UA-1, or PDF/UA-2 when declared), with the same report as PDF/A validation. On `NexPdfJni (static)` · module `standards` · C `nexpdf_validate_pdfua_json` ### convertPdfaLevel [#convertpdfalevel-1] ```java public static native boolean convertPdfaLevel(long handle, String level); ``` Converts to a chosen PDF/A level (2b when empty); level A tags the document first. 1 when the result validates; otherwise the error lists the clauses still failing. On `NexPdfJni (static)` · module `standards` · C `nexpdf_convert_pdfa_level` ## OCR [#ocr] ### ocrJson [#ocrjson] ```java public static native String ocrJson(long handle, String optionsJson); ``` Recognises scanned pages and adds an invisible, searchable text layer. Options (may be omitted): `{"engine":"auto|builtin|tesseract|neural","languages":"por+eng","dpi":300,"pages":[0],"force":false}`. Returns a JSON report. On `NexPdfJni (static)` · module `ocr` · C `nexpdf_ocr` ### ocrLoadModel [#ocrloadmodel] ```java public static native boolean ocrLoadModel(String optionsJson, byte[] model, String dictionary); ``` Loads a neural OCR model (ONNX) at run time: `{"kind":"detection"|"recognition"|"classification","languages","name","input_height","max_side"}`; a recognition model needs its character dictionary, a detection model or a text-direction classifier (0°/180°) takes none. On `NexPdfJni (static)` · module `ocr` · C `nexpdf_ocr_load_model` ### ocrModelsJson [#ocrmodelsjson] ```java public static native String ocrModelsJson(); ``` The loaded OCR models: `kind`, `name`, `languages`, `symbols`, `size`. On `NexPdfJni (static)` · module `ocr` · C `nexpdf_ocr_models_json` ### ocrUnloadModels [#ocrunloadmodels] ```java public static native int ocrUnloadModels(String languages); ``` Unloads the OCR models of the given languages (all when empty). Returns the number removed. On `NexPdfJni (static)` · module `ocr` · C `nexpdf_ocr_unload_models` ## Compare, optimise and memory [#compare-optimise-and-memory] ### compareJson [#comparejson] ```java public static native String compareJson(long a, long b, double dpi); ``` Compares two documents (text and visual differences per page) at the given resolution, as JSON. On `NexPdfJni (static)` · always available · C `nexpdf_compare_json` ### compareOverlayPng [#compareoverlaypng] ```java public static native byte[] compareOverlayPng(long a, long b, int pageIndex, double dpi); ``` A PNG overlay of the visual differences of one page of two documents. On `NexPdfJni (static)` · always available · C `nexpdf_compare_overlay_png` ### optimize [#optimize] ```java public static native String optimize(long handle); ``` Optimises the document (removes unused objects, recompresses streams); returns a JSON report. On `NexPdfJni (static)` · module `editor` · C `nexpdf_optimize` ### subsetFonts [#subsetfonts] ```java public static native String subsetFonts(long handle); ``` Subsets the embedded fonts to the glyphs the document uses; returns a JSON report. On `NexPdfJni (static)` · module `editor` · C `nexpdf_subset_fonts` ### trimMemory [#trimmemory-1] ```java public static native long trimMemory(long handle); ``` Drops cached data of the document; returns the bytes freed. On `NexPdfJni (static)` · always available · C `nexpdf_trim_memory` ### memoryUsageBytes [#memoryusagebytes] ```java public static native long memoryUsageBytes(long handle); ``` Approximate memory used by the document, in bytes. On `NexPdfJni (static)` · always available · C `nexpdf_memory_usage_bytes` ### compareTextJson [#comparetextjson-1] ```java public static native String compareTextJson(long oldHandle, long newHandle, String optionsJson); ``` Word-level text comparison of two documents: inserted, deleted, replaced and moved text with positions, and a summary. Options `{"ignore_case","ignore_punctuation","detect_moves","min_move_words","align","page_map"}`. On `NexPdfJni (static)` · always available · C `nexpdf_compare_text_json` ### compareAnnotate [#compareannotate-1] ```java public static native byte[] compareAnnotate(long oldHandle, long newHandle, String optionsJson); ``` The word-level comparison as a new PDF with highlight annotations (deleted red, inserted green, moved blue). Options add `output`, `author` and the colours. On `NexPdfJni (static)` · always available · C `nexpdf_compare_annotate` # Changelog (/docs/android/changelog) Versions follow [semantic versioning](https://semver.org). The AAR, the native engine and every other NexPDF SDK share one version number. See the [release notes for all SDKs](/docs/guides/changelog). ## 1.1.0 [#110] Released 29 November 2026. ### Added [#added] - Templates: `NexPdfDocument.fromDocxTemplate`, `fromHtmlTemplate`, `fillDocxTemplate` and `fillTemplate` (`NexPdfJni.templateDocxToPdf`, `templateHtmlToPdf`, `templateDocxFill`, `templateFillPdf`) fill Word, HTML and PDF templates from JSON data. See [Templates](/docs/android/guides/templates). - PAdES B-LTA: the `level` signing option (`B-B`, `B-T`, `B-LT`, `B-LTA`), `addDocumentTimestamp`, `NexPdfJni.addDocumentTimestampBytes` and the three-step `prepareDocumentTimestamp` / `documentTimestampRequest` / `completeDocumentTimestamp`. Verification reports `document_timestamp` and `pades_level`. See [Long-term signatures](/docs/android/guides/long-term-signatures). - Comment threads: `replyToAnnotation`, `annotationRepliesJson` and `setAnnotationState`. - Structured extraction: `extractTablesJson`, `extractKeyValuesJson`, `extractionPromptJson`, `extractionValidateJson` and `classifyJson` (`NexPdfJni.classifyDocumentJson`). - XFA forms: `xfaInfoJson`, `xfaExportData`, `xfaImportData`, `xfaToAcroform`, `xfaFlatten` and `xfaRemove`. - OCR of any script with neural models loaded at run time: `NexPdfJni.ocrLoadModel`, `ocrModelsJson` and `ocrUnloadModels`, and the `neural` OCR engine. - Barcodes: `readBarcodesJson`, `readBarcodesImageJson` and `addBarcode`. - Word-level comparison: `compareTextJson` and `compareAnnotate`. - PDF/A and PDF/UA validation with clause ids: `validatePdfaJson`, `validatePdfuaJson`, and `convertPdfaLevel` for any PDF/A level. - Real-time collaboration: `NexPdfSyncClient`, a ready-made client for the NexPDF sync server (WebSocket through the built-in `NexPdfSyncSocket`, with a Server-Sent Events + POST fallback, `NexPdfSyncClient.Transport`, push, presence, reconnect), and `NexPdfSyncJni` with `exportJson`, `exportLocalJson`, `applyJson`, `snapshotJson` and `setClientId`. See [Real-time collaboration](/docs/android/guides/collaboration). Change sets use `nexpdf-sync/2`: pages and shared objects are records, and changes merge per property. - A TSA callback: `NexPdfTsa.setCallback` and `NexPdfTsa.clearCallback`. See [Long-term signatures](/docs/android/guides/long-term-signatures). - OCR: the `classification` model kind for `NexPdfJni.ocrLoadModel`, page orientation and skew correction, slanted lines, vertical CJK columns. - XFA scripts (FormCalc and JavaScript), picture clauses, images, rich text, right-to-left layout, Unicode fonts and vector barcode fields, run by `xfaToAcroform` and `xfaFlatten`. - Full PDF/UA-2 validation. - Conversion: Excel formula calculation, Word columns and conditional table styles, OpenType shaping and bidi in Word, Excel, PowerPoint and HTML. - PDF templates break rows onto new pages, with `header_height`, `footer_height` and `font` options. - Text the engine writes (form field appearances, templates, XFA layout) is shaped with OpenType and ordered with Unicode bidi, in embedded fonts. - Reached through `NexPdfJni.invoke` (no typed method): `xfa_to_acroform_json`, `xfa_run_scripts_json`, `register_fallback_font`, `validate_pdfua_part_json`, `convert_pdfua_json`, `convert_pdfa_json`, `register_substitute_font`, `open_docx_with_options_json`, `open_xlsx_with_clock`, `template_docx_fill_with`, `validate_lta_json`, `signature_timestamp_request`, `add_signature_timestamp`, `ltv_requests_json`, `add_ltv_with_responses`, `page_words_json` and `add_barcode_ex`. - `NexPdfJni` methods for the C functions that had none in 1.0: `askDocument`, `toHtml`, `toXml`, `toCsv`, `toRtf`, `saveLinearized`, `setOverprint`, `pageLabelsJson`, `setPageLabelsJson`, `subsetFonts`, `convertPdfX`, `openEbook`, `openImage`, `registerStandardFont`, `hasBundledFonts`, `clearError`, `prepareExternalSignature`, `externalSignatureData` and `completeExternalSignature`. `NexPdfDocument` and the Kotlin `NexPdfAndroidDocument` wrap the common ones (`openEbook`, `openImage`, `saveLinearized`, `pageLabelsJson`, `setPageLabelsJson`, `trimMemory` and external signing). The newest engine functions listed below have no typed method yet: call them through `NexPdfJni.invoke`. - `NexPdfDocument.openBytes(bytes, password)` and `NexPdfDocument.isPasswordError(e)`. ### Changed [#changed] - XFA conversion to AcroForm stores the formatted display value as the field value `/V` (it was the raw value). Export the XFA data first if you need the raw values. - PDF templates: a text row that starts in the bottom 72 pt of the page is now treated as a repeated footer by default (`footer_height`). Set `"footer_height":0` for the old flow. - Simple fonts without `/Widths` take their widths from the embedded Type 1 or CFF program, and Symbol and ZapfDingbats use their standard metrics, so text positions in extraction and rendering are more accurate. - `NexPdfDocument.openBytes` converts EPUB, FictionBook (`.fb2` and `.fb2.zip`), XPS/OpenXPS and CBZ files, as well as Word, Excel and PowerPoint files, and so does `NexPdfReaderActivity`. With a password, Office files, e-books and comics are converted first and the password is used only for PDFs. ## 1.0.1 [#101] Released 28 November 2026. No changes in this SDK; the engine is the same as 1.0.0. The version follows the other SDKs, whose generic open calls now detect e-books. On Android 1.0.1, EPUB, FictionBook, XPS and CBZ files open with `open_ebook` through `NexPdfJni.invoke`; from 1.1.0, `NexPdfDocument.openBytes` opens them. ## 1.0.0 [#100] Released 28 November 2026. First stable release. ### Added [#added-1] - The AAR `com.nexdevit:nexpdf-android` with the native engine for `arm64-v8a`, `armeabi-v7a` and `x86_64`, for Android 7.0 (API 24) and later, without dependencies. - `NexPdfDocument`, a `Closeable` class for opening, rendering, text, search, Markdown, JSON and Word output and saving. - `NexPdfJni` with static native methods for the rest of the engine, and `invoke` for the whole C API as one JSON call. - `PageView` for mapping between PDF points and view pixels. - Offline `NEX2.` license keys with `NexPdfLicense`: `initialize` from the manifest meta-data, the assets or an explicit key, bound to the platform `android` and the package name, and `status`. - `NexPdfReaderActivity`, the ready-made reader with the viewer, annotations, content, forms and redaction modes, configured with the shared NexPDF UI configuration, and its events. - Rendering with overprint simulation, ICC colour and every PDF image codec; text extraction, Markdown and search. - Annotations (markup, shapes, ink, stamps, measurements, file attachments, XFDF), AcroForm filling with JavaScript calculation, and form data in JSON, FDF and XFDF. - Page and content editing, metadata, bookmarks, layers and attachments. - AES-256 encryption with permissions, watermarks, headers and footers, Bates numbering. - Destructive redaction by area, text, regular expression and preset patterns. - PAdES signatures from PKCS#12 files, timestamps, LTV and verification. - Conversion from Word, Excel, PowerPoint and HTML, and to Word, Excel, PowerPoint and JSON. - PDF/A conversion, PDF/UA auto-tagging, OCR, comparison and optimisation. - Consumer keep rules for R8 and ProGuard. # Error handling (/docs/android/error-handling) NexPDF for Android reports failures in two ways: - **`NexPdfDocument`** throws when a document cannot be opened or is used after `close()`. - **`NexPdfJni`** methods never throw. A failure returns a failure value, and `NexPdfJni.lastError()` gives the engine's reason on the same thread. ## Exceptions [#exceptions] | Exception | Thrown when | |---|---| | `IllegalArgumentException` | `NexPdfDocument.openBytes`, `openEbook`, `openImage`, `openOffice`, `fromHtml`, `fromDocxTemplate` or `fromHtmlTemplate` could not open or create the document. The message is the engine's error; `NexPdfDocument.isPasswordError(e)` is `true` for `password required` and `incorrect password` | | `IllegalStateException` | `handle()` (and so every method of `NexPdfDocument`) was called after `close()`: `document is closed` | | `UnsatisfiedLinkError` | The first use of `NexPdfJni` could not load `libnexpdf_jni.so` or `libnexpdf_ffi.so`, for example on an ABI the AAR does not include. Later uses throw `NoClassDefFoundError` | ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni try { NexPdfDocument.openBytes(upload).use { doc -> if (!NexPdfJni.addWatermark(doc.handle(), "CONFIDENTIAL")) { Log.w("NexPDF", "watermark failed: ${NexPdfJni.lastError()}") return } out.writeBytes(doc.saveBytes()) } } catch (e: IllegalArgumentException) { Log.w("NexPDF", "NexPDF could not open the upload: ${e.message}") } ``` ## Return values of NexPdfJni [#return-values-of-nexpdfjni] | Return type | Failure value | |---|---| | `boolean` (actions such as `rotatePage`, `fillFormField`) | `false` | | `int` counts (such as `flattenForms`, `redactMatches`, `insertImagePages`) | `-1` | | `long` handles (`openBytes`, `openBytesWithPassword`, `extractPages`, `openOffice`) | `0` | | `String` (JSON and text) | `""` | | `byte[]` (PNG, PDF, Office files) | an empty array | Read `NexPdfJni.lastError()` right after a call that returned a failure value, on the same thread. Errors are tracked per thread, and a successful call does not always clear the previous error, so an error message alone does not mean the last call failed. An empty string or array can also be a real result, for example the text of a scanned page with no text layer. ```kotlin val png = NexPdfJni.renderPagePng(h, 0, 144.0) if (png.isEmpty()) error("render failed: ${NexPdfJni.lastError()}") ``` Two rules protect the process, because handles are native pointers: - Never use a handle after `NexPdfJni.free(handle)` or `doc.close()`. `NexPdfDocument` checks this and throws; a raw `long` handle does not. - Pass `null` only where a method says it accepts it (for example the values of `setMetadata` or the pages of `removePageBackground`). Some methods hand their arguments straight to native code. ## Common engine messages [#common-engine-messages] | Message | Cause | What to do | |---|---|---| | `password required` | The file is encrypted and no password was given | Ask for the password and open with `NexPdfJni.openBytesWithPassword` | | `incorrect password` | The password matches neither the user nor the owner password | Ask again | | `no license activated: '' requires a NexPDF license key` | The call needs a module and no key is active | Call `NexPdfLicense.initialize` in `Application.onCreate()`; see [Running without a key](/docs/android/without-license) | | `the active license does not include the '' module` | Your plan does not include the module | Check the key's `modules`, or upgrade the plan | | `internal error: ...` | The engine caught an unexpected failure on this input | The app keeps running; report the file to support | Other messages describe the input: a malformed or truncated PDF, a page index out of range, invalid JSON options. They are meant to be logged as they are, not shown to users word for word. ## License codes [#license-codes] `NexPdfLicense.initialize` (and `NexPdfJni.licenseActivate`) return `2` for a commercial key, `1` for a trial key, or one of: | Code | Meaning | |---|---| | -1 | Malformed key | | -2 | Bad signature (the key was changed, or it is not a NexPDF key) | | -3 | Unsupported key version (update the SDK) | | -4 | Expired | | -5 | Not yet valid (check the device clock) | | -6 | Wrong platform (the key is not for `android`) | | -7 | Wrong application id (the package name) | | -8 | No key in the manifest or the assets (`initialize(context)` only) | A rejected key leaves the previous license state as it was, so an app that had no key stays in view-only mode, and an app that had a valid key keeps it. ## invoke errors [#invoke-errors] [`NexPdfJni.invoke`](/docs/android#the-generic-invoke-call) never throws either. It returns `{"ok":false,"error":"..."}` with the same messages; the `NexPdfInvoke.call` helper turns that into an `IllegalStateException`. ## Untrusted input [#untrusted-input] The engine is written in Rust and fuzzed; a malformed PDF produces a failure value or an `IllegalArgumentException`, it does not crash the app. When you open files from other apps, a `content:` URI or a server: - check every return value, and catch `IllegalArgumentException` per file, so one bad file does not stop a batch; - check the file size before opening it, since the whole file is read into memory; - open and process files off the main thread (see [Platform notes](/docs/android/platform-notes#threading)); - close documents with `use { }` or try-with-resources so native memory is freed on failure too. ```kotlin fun pageCountOrNull(bytes: ByteArray): Int? = try { NexPdfDocument.openBytes(bytes).use { it.pageCount() } } catch (e: IllegalArgumentException) { null } ``` ## Related [#related] - [Troubleshooting](/docs/android/troubleshooting) - [License](/docs/android/license) # Getting started (/docs/android/getting-started) This example opens a PDF from the app's assets, logs the page count, renders the first page to a `Bitmap` and logs the text of every page. It runs without a license key too: viewing is always allowed, and rendered pages then carry a watermark. ### Add the dependency [#add-the-dependency] Add `com.nexdevit:nexpdf-android:1.1.0` as described in [Installation](/docs/android/installation), and put `sample.pdf` (and, if you have one, `nexpdf_license.xml`) in `app/src/main/assets/`. ### Activate the license at start-up [#activate-the-license-at-start-up] ```kotlin title="App.kt" import android.app.Application import android.util.Log import com.nexdevit.nexpdf.NexPdfJni import com.nexdevit.nexpdf.NexPdfLicense class App : Application() { override fun onCreate() { super.onCreate() val rc = NexPdfLicense.initialize(this) // assets/nexpdf_license.xml or manifest meta-data if (rc < 0) Log.w("NexPDF", "license not active ($rc): ${NexPdfJni.lastError()}") } } ``` ```java title="App.java" public class App extends Application { @Override public void onCreate() { super.onCreate(); int rc = NexPdfLicense.initialize(this); // assets/nexpdf_license.xml or manifest meta-data if (rc < 0) Log.w("NexPDF", "license not active (" + rc + "): " + NexPdfJni.lastError()); } } ``` Register the class with `android:name=".App"` on `` in the manifest. ### Open, render and extract [#open-render-and-extract] ```kotlin title="MainActivity.kt" import android.graphics.BitmapFactory import com.nexdevit.nexpdf.NexPdfDocument val bytes = assets.open("sample.pdf").use { it.readBytes() } NexPdfDocument.openBytes(bytes).use { doc -> val count = doc.pageCount() Log.i("NexPDF", "$count pages, first page ${doc.pageWidth(0)} x ${doc.pageHeight(0)} pt") val png = doc.renderPagePng(0, 144.0) imageView.setImageBitmap(BitmapFactory.decodeByteArray(png, 0, png.size)) for (i in 0 until count) { Log.i("NexPDF", "--- page ${i + 1} ---\n" + doc.pageText(i)) } } ``` ```java title="MainActivity.java" byte[] bytes; try (InputStream in = getAssets().open("sample.pdf")) { bytes = in.readAllBytes(); // API 33+; use a ByteArrayOutputStream on older versions } try (NexPdfDocument doc = NexPdfDocument.openBytes(bytes)) { int count = doc.pageCount(); Log.i("NexPDF", count + " pages, first page " + doc.pageWidth(0) + " x " + doc.pageHeight(0) + " pt"); byte[] png = doc.renderPagePng(0, 144); imageView.setImageBitmap(BitmapFactory.decodeByteArray(png, 0, png.length)); for (int i = 0; i < count; i++) { Log.i("NexPDF", "--- page " + (i + 1) + " ---\n" + doc.pageText(i)); } } ``` ## What the code does [#what-the-code-does] - `NexPdfLicense.initialize(context)` reads the key from the manifest meta-data `com.nexdevit.nexpdf.license_key`, else from `assets/nexpdf_license.xml`, and activates it for the platform `android` and the app's package name. See [License](/docs/android/license). - `NexPdfDocument.openBytes(bytes)` opens a PDF. JPEG, PNG and TIFF pictures become one page each. Word, Excel and PowerPoint files, EPUB and FictionBook books, XPS packages and CBZ comics are converted (`conversion` module), and `openBytes(bytes, password)` opens encrypted PDFs. - `pageWidth(i)` and `pageHeight(i)` are the displayed size in points: crop box, rotation and `/UserUnit` applied. - `renderPagePng(i, dpi)` returns PNG bytes. 72 dpi is one pixel per point. - `pageText(i)` returns the page text in reading order. - `saveBytes()` returns the document, with your changes, as PDF bytes. Rendering and text extraction run on the calling thread: in a real app, call them from a background thread or a coroutine on `Dispatchers.Default`. ## Next steps [#next-steps] # Annotations (/docs/android/guides/annotations) Creating and changing annotations needs the `annotations` module (Indie tier and above). Listing annotations with `annotationsJson` works without a key. Coordinates are PDF points with the origin at the bottom-left of the page. Rectangles are `llx, lly, urx, ury`. Every call below is a static method of `NexPdfJni` that takes `doc.handle()`; those that return `Boolean` return `false` on failure, with the reason in `NexPdfJni.lastError()`. The [reader](/docs/android/reader) offers the same tools to the user. ## Add markup and shapes [#add-markup-and-shapes] `addAnnotation(handle, pageIndex, kind, colorHex, opacity, contents, llx, lly, urx, ury)` adds an annotation of a PDF subtype such as `Highlight`, `Underline`, `StrikeOut`, `Squiggly`, `Square`, `Circle`, `FreeText` or `Text` (a sticky note). Text markup is fitted to the lines under the rectangle. ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni NexPdfDocument.openBytes(bytes).use { doc -> val h = doc.handle() check(NexPdfJni.addAnnotation(h, 0, "Highlight", "#FFD400", 1.0, "", 72.0, 700.0, 300.0, 716.0)) { NexPdfJni.lastError() } NexPdfJni.addAnnotation(h, 0, "FreeText", "#E5484D", 1.0, "Checked", 72.0, 640.0, 260.0, 660.0) NexPdfJni.addAnnotation(h, 0, "Text", "#2563EB", 1.0, "Please confirm this date", 320.0, 700.0, 340.0, 720.0) val annotated = doc.saveBytes() } ``` ## Lines, arrows and ink [#lines-arrows-and-ink] ```kotlin // A red arrow from (100, 500) to (250, 560), 2 pt wide. NexPdfJni.addLine(h, 0, "Arrow", "#DC2626", 1.0, 2.0, 100.0, 500.0, 250.0, 560.0) // Freehand ink: points "x,y;x,y;..." in PDF points. NexPdfJni.addInk(h, 0, "#1D4ED8", 2.0, 1.0, "100,400;120,410;140,405;160,420") ``` A handwritten signature is an ink annotation with several strokes separated by `|`: ```kotlin NexPdfJni.addInkSignature(h, 0, "#111827", 1.5, "300,120;320,130;340,118|350,125;380,128") ``` This is a visual signature only. For a cryptographic signature see [Signatures](/docs/android/guides/signatures). ## Image stamps and measurements [#image-stamps-and-measurements] ```kotlin // A picture stamp from RGBA pixels (width x height x 4 bytes), here 240 x 120. NexPdfJni.addImageStamp(h, 0, 400.0, 60.0, 520.0, 120.0, rgba, 240, 120, 1.0) // A stored distance measurement; per_point converts PDF points to the unit. val m = """{"kind":"distance","points":[[100,100],[300,100]],"unit":"mm","per_point":0.3528}""" val result = JSONObject(NexPdfJni.addMeasurement(h, 0, m)) Log.i("NexPDF", result.getString("text")) ``` `kind` is `distance`, `perimeter` or `area`. `NexPdfJni.measurementsJson(h)` lists the stored ones. ## List, edit, move and remove [#list-edit-move-and-remove] ```kotlin val annots = JSONArray(NexPdfJni.annotationsJson(h, 0)) for (i in 0 until annots.length()) { val a = annots.getJSONObject(i) Log.i("NexPDF", "${a.getInt("num")} ${a.getInt("gen")} ${a.getString("kind")} ${a.optString("contents")}") } val a = annots.getJSONObject(0) val num = a.getInt("num"); val gen = a.getInt("gen") NexPdfJni.setAnnotationContents(h, num, gen, "Updated note") NexPdfJni.moveAnnotation(h, num, gen, 10.0, -20.0) // dx, dy in points NexPdfJni.removeAnnotation(h, 0, num, gen) ``` Annotations are identified by their object number (`num`) and generation (`gen`). ## Flatten [#flatten] Flattening burns annotations into the page content so they can no longer be edited: ```kotlin NexPdfJni.flattenAnnotations(h, -1) // every page; pass a page index for one page ``` ## XFDF import and export [#xfdf-import-and-export] ```kotlin val xfdf = NexPdfJni.exportXfdf(h) NexPdfDocument.openBytes(cleanBytes).use { other -> NexPdfJni.importXfdf(other.handle(), xfdf) val withAnnotations = other.saveBytes() } ``` ## File attachments [#file-attachments] `addFileAttachmentAnnot(handle, pageIndex, x, y, name, data, mime, description)` adds a paperclip icon whose top-left corner is at `(x, y)`: ```kotlin NexPdfJni.addFileAttachmentAnnot(h, 0, 520.0, 760.0, "invoice.xml", xmlBytes, "application/xml", "Source data") ``` # Barcodes (/docs/android/guides/barcodes) Reading barcodes needs the `conversion` module and drawing them the `editor` module (both Startup tier and above). ## Read barcodes from pages [#read-barcodes-from-pages] `readBarcodesJson(pageIndex, optionsJson)` renders a page (every page with `-1`) and reads the barcodes on it. Positions are in PDF points. 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.JSONArray NexPdfDocument.openBytes(deliveryNote).use { doc -> val codes = JSONArray(doc.readBarcodesJson(-1, null)) for (i in 0 until codes.length()) { val code = codes.getJSONObject(i) Log.i("NexPDF", "${code.getInt("page")} ${code.getString("format")} ${code.getString("text")} ${code.getJSONArray("rect")}") } } ``` Each result has `format`, `text`, `bytes_base64` (the raw payload of 2D codes, `null` for linear codes), `page`, `rect` (`[llx, lly, urx, ury]`) and the corner `points`. Reading renders the pages, so run it off the main thread. ## Read barcodes from an image [#read-barcodes-from-an-image] `NexPdfDocument.readBarcodesImageJson(image, optionsJson)` (also `NexPdfJni.readBarcodesImageJson`) reads a PNG or JPEG, for example a camera picture. `rect` and `points` are then in pixels with the origin at the top-left, and `page` is `null`. ```kotlin val png = contentResolver.openInputStream(uri)!!.use { it.readBytes() } val codes = JSONArray(NexPdfDocument.readBarcodesImageJson(png, """{"formats":["qr_code"]}""")) ``` ## Options [#options] | Option | Default | Meaning | |---|---|---| | `formats` | every format | Limit the search, for example `["qr_code","code_128"]` | | `dpi` | `200` | Resolution pages are rendered at | | `try_harder` | `true` | Spend more time on hard images | | `pure_barcode` | `false` | The image holds only one barcode and nothing else | | `multiple` | `true` | Return every barcode, not just the first | | `tile_scan` | `true` | Also scan tiles of the page for small codes | Formats: `qr_code`, `data_matrix`, `aztec`, `pdf_417`, `code_128`, `code_39`, `code_93`, `ean_13`, `ean_8`, `upc_a`, `upc_e`, `itf`, `codabar` and more (MaxiCode and DataBar are also read). ## Draw a barcode [#draw-a-barcode] `addBarcode(pageIndex, llx, lly, urx, ury, format, text)` draws the text as a vector barcode, with a white background and a quiet zone, into the rectangle (PDF points). It is real page content, not an image, so it prints sharply at any size. It returns `false` on failure. ```kotlin NexPdfDocument.openBytes(label).use { doc -> check(doc.addBarcode(0, 400.0, 700.0, 520.0, 820.0, "qr_code", "https://example.com/track/8812")) { NexPdfJni.lastError() } doc.addBarcode(0, 72.0, 60.0, 300.0, 110.0, "code_128", "SHIP-8812-PT") doc.addBarcode(0, 320.0, 60.0, 460.0, 110.0, "ean_13", "560123456789") // check digit computed File(filesDir, "label-coded.pdf").writeBytes(doc.saveBytes()) } ``` Formats you can draw: `qr_code`, `data_matrix`, `aztec`, `pdf_417`, `code_128`, `code_39`, `code_93`, `ean_13` (12 digits plus a computed check digit, or 13), `ean_8`, `upc_a`, `upc_e`, `itf`, `codabar` and `telepen`. # Real-time collaboration (/docs/android/guides/collaboration) Sync needs the `annotations` module (Indie tier and above). NexPDF Sync lets several copies of one PDF (the browser viewer, apps, a server) edit the same document at the same time and converge. Copies exchange **records** with stable ids, not whole files: | Record `type` | What | `id` | |---|---|---| | `page` | One page: its dictionary and its place in the document | Stored on the page | | `annotation` | An annotation that is not a reply | Its `/NM` | | `comment` | A reply in a [comment thread](/docs/android/guides/comment-threads) | Its `/NM` | | `field` | The value of a form field | `field:` | | `bookmark` | One outline item | Its `/NM` | | `object` | A shared object: an appearance stream, font, image or content stream | `obj:` of its content | Page operations sync too: insert, delete, move and reorder, rotate, crop and content edits merge into the same page order on every copy. `/Dest` destinations follow their page. A shared object is sent once, however many records use it, and a copy that already holds it uses its own: shared, not copied. Change sets use the format `nexpdf-sync/2`; format 1 change sets are still read. Edits made with any other call are picked up automatically: every export and apply first finds the records that were added, changed or removed since the last sync. The sync state is saved in the PDF, so a reopened file continues where it left off. The Android SDK has two layers: `NexPdfSyncClient`, a ready-made client for the NexPDF sync server, and `NexPdfSyncJni`, the sync calls on a document handle for your own transport. ## Connect to a sync server [#connect-to-a-sync-server] Every copy must start from the server's file. Download it from `GET /api/sync/document` (with the same `Authorization` header; the `X-Sync-Seq` response header is the sequence to pass as `since`), open it, wrap its handle with `NexPdfSyncJni.engine(handle)` and connect. The client connects over a WebSocket (a built-in RFC 6455 client, `NexPdfSyncSocket`, for `ws://` and `wss://` with host name checks), streams the others' changes into the document and pushes your edits about once a second. When the socket never reaches `hello` (a proxy that does not pass upgrades, for example), it switches to Server-Sent Events + POST for the rest of the session. ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfSyncClient import com.nexdevit.nexpdf.NexPdfSyncJni val options = NexPdfSyncClient.Options("https://viewer.example.com/s/abc123").apply { token = sessionToken // sent as Authorization: Bearer name = "Ana" color = "#2563EB" since = serverSeq // X-Sync-Seq of the download, or 0 callbackExecutor = mainExecutor // listener callbacks on the main thread transport = NexPdfSyncClient.Transport.AUTO // or WEBSOCKET, SSE } val listener = object : NexPdfSyncClient.Listener { override fun onRemote(applyReportJson: String, changeCount: Int) = pageView.invalidate() override fun onPresence(peers: List) = showCursors(peers) override fun onStatus(status: NexPdfSyncClient.Status) = showStatus(status) override fun onError(error: Throwable) { Log.w("NexPDF", "sync", error) } } val doc = NexPdfDocument.openBytes(serverPdf) val sync = NexPdfSyncClient(NexPdfSyncJni.engine(doc.handle()), options, listener) sync.connect() if (!sync.awaitOnline(10_000)) Log.w("NexPDF", "sync still offline: ${sync.status()}") // off the main thread ``` Once a client exists, `sync.downloadDocument()` fetches the current file and updates `seq()`, which is what you use after `onReload`. Add the `INTERNET` permission to the manifest. Keep the document open while the client uses it, and `close()` the client before you close the document. ## Edit the document while syncing [#edit-the-document-while-syncing] The client calls the engine from its own threads, holding `sync.lock`. Make your own edits of the same document inside that lock, so they never run at the same time as a merge: ```kotlin synchronized(sync.lock) { NexPdfJni.addAnnotation(doc.handle(), 0, "Highlight", "#FFD400", 1.0, "", 72.0, 700.0, 300.0, 716.0) } withContext(Dispatchers.IO) { sync.flush() } // push now instead of waiting for the timer ``` Remote changes are merged into the document before `onRemote` runs: redraw the pages there. The client skips its own changes when the server echoes them back. ## NexPdfSyncClient [#nexpdfsyncclient] | Member | Does | |---|---| | `NexPdfSyncClient(engine, options, listener)` | Creates the client and sets the engine's client id. `listener` may be `null` | | `connect()` | Opens the change stream in the background and starts the push timer | | `awaitOnline(timeoutMs)` | Waits until the server said `hello`; `false` on timeout or when the client closed | | `close()` | Stops syncing. Local edits not yet pushed stay in the document; call `flush()` first to send them | | `flush()` | Pushes the local changes made since the last push and returns the server's result JSON, or `null` when there were none. Throws `IOException` | | `setPresence(page, cursor)` | Shares the page this person is on and a cursor in PDF points (`doubleArrayOf(x, y)`, or `null`) | | `downloadDocument()` | The server's current PDF as a `ByteArray`; also updates `seq()` | | `attach(engine)` | Switches to another document, for example one reopened after `onReload` | | `handleEvent(event, data)` | Handles one server event, for custom transports and tests | | `seq()`, `pushedClock()`, `status()`, `peers()` | Last server sequence seen, Lamport clock of the last push, the `Status` and the other people connected | | `transport()` | `WEBSOCKET` or `SSE` while connected, else `null` | | `clientId`, `lock` | This device's client id, and the lock held during every engine call | `flush()`, `setPresence()` and `downloadDocument()` do network I/O: call them off the main thread. ### Options [#options] | Field | Default | Meaning | |---|---|---| | `url` | (constructor) | Server URL, or a session URL such as `https://host/s/` | | `clientId` | random UUID | Stable id of this device (1 to 64 characters of `A-Z a-z 0-9 - _ . : @`) | | `name`, `color` | `""` | Shown to the others in presence (`color` is `#RRGGBB`) | | `token` | `null` | Session token, sent as `Authorization: Bearer` | | `since` | `0` | Server sequence to resume from (a previous `seq()`); `0` is everything since the document was loaded | | `flushIntervalMs` | `1000` | Push interval; `0` pushes only on `flush()` | | `reconnectDelayMs` | `1000` | First reconnect delay; it doubles up to 30 seconds | | `connectTimeoutMs` | `15000` | HTTP connect timeout | | `transport` | `AUTO` | `AUTO` (WebSocket, else SSE + POST), `WEBSOCKET` or `SSE` | | `callbackExecutor` | `null` | Where listener callbacks run, for example `context.mainExecutor`; `null` runs them on the client's threads | ### Listener [#listener] Every callback is optional (a default method). | Callback | When | |---|---| | `onRemote(applyReportJson, changeCount)` | Remote changes were applied; the engine's apply report (`applied`, `ignored`, `conflicts`, `errors`) | | `onPushed(pushResultJson)` | A push was stored by the server | | `onConflict(conflictsJson)` | Records where a local edit lost or won against a concurrent one | | `onPresence(peers)` | The list of other people changed. Each `Peer` has `client`, `name`, `color`, `user`, `page` and `cursor` (`[x, y]` in PDF points, or `null`) | | `onStatus(status)` | `CONNECTING`, `ONLINE`, `OFFLINE` or `CLOSED` | | `onReload(seq)` | The server's document was replaced: download it again and `attach` it | | `onError(error)` | A stream, push or merge error | The stream reconnects by itself and resumes from the last `seq()`. When the server answers `401`, `402`, `403` or `404` (bad token, read-only session, unlicensed server or no such session), retrying will not help: the client reports the error and closes. ### When the document is replaced [#when-the-document-is-replaced] ```kotlin override fun onReload(seq: Long) { ioScope.launch { val fresh = NexPdfDocument.openBytes(sync.downloadDocument()) sync.attach(NexPdfSyncJni.engine(fresh.handle())) val old = doc doc = fresh old.close() } } ``` ## Exchange changes yourself [#exchange-changes-yourself] `NexPdfSyncJni` has the sync calls on a document handle. The JSON methods return `null` on error, with the reason in `NexPdfJni.lastError()`: ```kotlin import com.nexdevit.nexpdf.NexPdfJni import com.nexdevit.nexpdf.NexPdfSyncJni import org.json.JSONObject NexPdfDocument.openBytes(shared).use { a -> NexPdfDocument.openBytes(shared).use { b -> NexPdfSyncJni.setClientId(a.handle(), "alice") NexPdfSyncJni.setClientId(b.handle(), "bob") NexPdfJni.addAnnotation(a.handle(), 0, "Highlight", "#FFD400", 1.0, "", 72.0, 700.0, 300.0, 716.0) val changes = NexPdfSyncJni.exportLocalJson(a.handle(), 0) ?: error(NexPdfJni.lastError()) val report = JSONObject(NexPdfSyncJni.applyJson(b.handle(), changes)) Log.i("NexPDF", "${report.get("applied")} ${report.get("ignored")} ${report.get("conflicts")}") val since = JSONObject(changes).getLong("clock") // pass it next time } } ``` | Call | Returns | |---|---| | `setClientId(handle, id)` | Sets the id this copy versions its changes under (1 to 64 characters of `A-Z a-z 0-9 - _ . : @`). `1` on success, `0` on error. Random when not set | | `exportLocalJson(handle, since)` | Only this copy's own changes with a clock above `since`: what a client sends. Keep the returned `clock` for the next call | | `exportJson(handle, since)` | Every change above `since`, from any client | | `applyJson(handle, changes)` | Applies a change set and returns a report | | `snapshotJson(handle)` | Every record with its version, base records and tombstones included | Every copy must start from **the same file**. Records that exist when a document is first synced get the base version and are not sent as changes. ## How changes merge [#how-changes-merge] A version is `{"lamport", "client"}`: a higher Lamport clock wins, then the higher client id, so every copy picks the same winner in whatever order changes arrive. **Every property of a record has its own version**, and the merge is last writer wins per property. Keys that only make sense together are one property: an annotation's geometry, a page's content and resources, a bookmark's parent and order. So Alice editing an annotation's text while Bob moves it keeps both edits, and a page rotated by one person and cropped by another keeps both. When a merge mixes properties from different writers, the appearance is redrawn the same way on every copy, for every annotation kind the engine creates. Deletion is a version too. A delete followed by an older edit stays deleted; a newer edit brings the record back with all its properties. The apply report has `ok`, `clock`, `applied` and `ignored` (changes that brought nothing newer) ids, `conflicts` (`id`, `winner`, `local`, `remote` and the `props` that met a concurrent edit), which are informational because the merge is already decided, and `errors` for single records that could not be written. A malformed change set fails as a whole. ## The sync server [#the-sync-server] The NexPDF web viewer server hosts the sync endpoint `NexPdfSyncClient` talks to, under the viewer session (`/s//…`): | Endpoint | Use | |---|---| | `GET /api/sync/document` | The PDF to start from | | `GET /api/sync/ws?since=&client=` | WebSocket (subprotocol `nexpdf-sync`, optionally `bearer.`): the stream events plus `pushed` and `error`; the client sends `push` and `presence` messages | | `GET /api/sync/stream?since=&client=` | Server-Sent Events: `hello`, `changes`, `presence`, `reload` | | `POST /api/sync/push` | A change set of the client's own changes | | `POST /api/sync/presence` | Name, colour, page and cursor of this client | | `GET /api/sync/changes?since=` | Catch-up as JSON, for polling | | `GET /api/sync/snapshot` | Every record and version | Each request sends `X-Client: ` and a session token as `Authorization: Bearer`. Viewers may stream; only editors may push. Edits in the browser viewer, page operations and undo and redo included, become changes too. The [Web](/docs/web/guides/collaboration), [Node.js](/docs/nodejs/guides/collaboration), [iOS](/docs/ios/guides/collaboration) and [Java](/docs/java/guides/collaboration) SDKs have the same client, so all of them can edit one document together. The server appends every accepted record to `/sync//changes.jsonl` next to `base.pdf`, and a restarted server rebuilds the document from both. The data directory is `NEXPDF_DATA_DIR` (`off`, `none` or `memory` keeps everything in memory), else `~/Library/Application Support/NexPDF/WebViewer` on macOS, `%LOCALAPPDATA%\NexPDF\WebViewer` on Windows and `$XDG_DATA_HOME/nexpdf/webviewer` elsewhere. A `changes` batch with `reset: true` means the server's log restarted and the batch is the full state. ## Limits [#limits] - Attachments are not records. Replacing the document on the server sends `reload`. # Comment threads (/docs/android/guides/comment-threads) Replies and review states need the `annotations` module (Indie tier and above). A comment thread is an annotation (a note, a highlight, any markup) with the replies people wrote under it. Replies are annotations too, so Acrobat and other viewers show the same thread. An annotation is named by its object number and generation (`num`, `gen`), as [`annotationsJson`](/docs/android/guides/annotations) lists them. ## Reply [#reply] `replyToAnnotation(pageIndex, num, gen, author, text)` adds a reply and returns the reply's object number (its generation is `0`), or `0` on failure with the reason in `NexPdfJni.lastError()`. Reply to a reply the same way. ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni import org.json.JSONArray NexPdfDocument.openBytes(review).use { doc -> val note = JSONArray(NexPdfJni.annotationsJson(doc.handle(), 0)).getJSONObject(0) val num = note.getInt("num") val gen = note.getInt("gen") val reply = doc.replyToAnnotation(0, num, gen, "Rui", "Agreed, changing the date.") check(reply != 0) { NexPdfJni.lastError() } doc.replyToAnnotation(0, reply, 0, "Ana", "Thanks!") File(filesDir, "review.pdf").writeBytes(doc.saveBytes()) } ``` ## Read a thread [#read-a-thread] `annotationRepliesJson(pageIndex, num, gen)` returns the thread under an annotation, oldest first, replies to replies included: ```kotlin val thread = JSONArray(doc.annotationRepliesJson(0, num, gen)) for (i in 0 until thread.length()) { val r = thread.getJSONObject(i) Log.i("NexPDF", "${r.getString("date")} ${r.getString("author")} ${r.getString("text")} ${r.get("in_reply_to")} ${r.opt("state")}") } ``` Each entry has `num`, `gen`, `in_reply_to` (`{"num", "gen"}`), `author`, `date` (ISO 8601), `text`, `state` and `state_model`. `state` and `state_model` are `null` for plain replies. ## Set a review state [#set-a-review-state] `setAnnotationState(pageIndex, num, gen, author, state)` records a reviewer's decision as a hidden state reply and returns its object number, or `0` on failure: | Model | States | |---|---| | Review | `Accepted`, `Rejected`, `Cancelled`, `Completed`, `None` | | Marked | `Marked`, `Unmarked` | ```kotlin doc.setAnnotationState(0, num, gen, "Ana", "Accepted") ``` For raw handles the same calls are `NexPdfJni.replyToAnnotation(handle, …)`, `annotationRepliesJson(handle, …)` and `setAnnotationState(handle, …)`. Threads and states are also part of [real-time collaboration](/docs/android/guides/collaboration): replies sync as `comment` records. # Compare and optimise (/docs/android/guides/compare-and-optimize) Comparing documents, linearized saving and the memory calls work without a key. `optimize` and `subsetFonts` need the `editor` module (Startup tier and above). ## Compare two versions [#compare-two-versions] `NexPdfJni.compareJson(a, b, dpi)` compares two documents page by page: whether the text changed and how much of the rendered page differs. `compareOverlayPng(a, b, pageIndex, dpi)` draws the differences of one page as a PNG. Both take two document handles. ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni import org.json.JSONObject NexPdfDocument.openBytes(v1Bytes).use { a -> NexPdfDocument.openBytes(v2Bytes).use { b -> val diff = JSONObject(NexPdfJni.compareJson(a.handle(), b.handle(), 72.0)) Log.i("NexPDF", "${diff.getInt("pages_a")} pages before, ${diff.getInt("pages_b")} after") val pages = diff.getJSONArray("pages") for (i in 0 until pages.length()) { val page = pages.getJSONObject(i) val changed = page.getDouble("visual_diff") if (page.getBoolean("text_changed") || changed > 0.001) { val n = page.getInt("page") Log.i("NexPDF", "page ${n + 1}: ${"%.2f".format(changed * 100)} % of the pixels changed") val overlay = NexPdfJni.compareOverlayPng(a.handle(), b.handle(), n, 110.0) File(cacheDir, "diff-${n + 1}.png").writeBytes(overlay) } } } } ``` To see which words changed (inserted, deleted, replaced and moved text, and an annotated PDF of the changes), use [Word-level comparison](/docs/android/guides/text-comparison). `visual_diff` is the share of differing pixels, from 0 to 1. A low resolution (72 dpi) is enough to find changed pages; the overlay resolution is clamped to 18-300 dpi. Comparing renders every page of both documents, so run it off the main thread. ## Make files smaller [#make-files-smaller] `NexPdfJni.optimize(handle)` compresses uncompressed streams and removes objects nothing refers to, and returns a JSON report. Save afterwards. ```kotlin NexPdfDocument.openBytes(largeBytes).use { doc -> val r = JSONObject(NexPdfJni.optimize(doc.handle())) Log.i("NexPDF", "${r.optInt("streams_compressed")} streams compressed, " + "${r.optInt("objects_pruned")} objects pruned, ${r.optLong("bytes_saved")} bytes saved") val small = doc.saveBytes() } ``` `NexPdfJni.subsetFonts(handle)` replaces embedded TrueType, OpenType and CFF fonts with subsets of the glyphs the document uses. It returns a JSON report, or an empty string on failure: ```kotlin val f = JSONObject(NexPdfJni.subsetFonts(doc.handle())) Log.i("NexPDF", "${f.optInt("fonts_subset")} fonts subset: ${f.optLong("bytes_before")} -> ${f.optLong("bytes_after")} bytes") val smaller = doc.saveBytes() ``` Fonts that may still be needed for new text are left whole and counted in `fonts_skipped`. ## Fast Web View [#fast-web-view] Linearized files let a browser show the first page before the rest downloads: ```kotlin File(filesDir, "web.pdf").writeBytes(doc.saveLinearized()) ``` ## Memory [#memory] `NexPdfJni.memoryUsageBytes(handle)` estimates the memory a document uses. `NexPdfJni.trimMemory(handle)` compacts its internal buffers and drops objects nothing refers to any more, and returns the bytes reclaimed. Call it after large edits, and from `onTrimMemory`: ```kotlin Log.i("NexPDF", "${NexPdfJni.memoryUsageBytes(doc.handle()) / 1024} KiB") val freed = NexPdfJni.trimMemory(doc.handle()) ``` The document stays fully usable. Closing it frees everything. See [Platform notes](/docs/android/platform-notes#memory) for threading and memory. # PDF/A and PDF/UA validation (/docs/android/guides/conformance) Validation and conversion need the `standards` module (Enterprise tier). NexPDF checks documents against the machine-checkable rules of PDF/A (ISO 19005-1 to -4) and PDF/UA (ISO 14289). Each failure names the clause of the standard that requires it, with the same numbers the veraPDF rule sets use. ## Validate PDF/A [#validate-pdfa] `validatePdfaJson(level)` takes `1a`, `1b`, `2a`, `2b`, `2u`, `3a`, `3b`, `3u`, `4`, `4e` or `4f` (or `PDF/A-2b`). `null` uses the level the document declares, or 2b. It returns an empty string on failure, with the reason in `NexPdfJni.lastError()`. ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni import org.json.JSONObject NexPdfDocument.openBytes(archive).use { doc -> val report = JSONObject(doc.validatePdfaJson("2b")) Log.i("NexPDF", "${report.getString("level")} ${if (report.getBoolean("compliant")) "compliant" else "not compliant"}") val failures = report.getJSONArray("failures") for (i in 0 until failures.length()) { val f = failures.getJSONObject(i) Log.i("NexPDF", "${f.getString("clause")} ${f.getString("message")} ${f.opt("page")} ${f.opt("object")}") } } ``` Each failure has `clause` (such as `6.2.11.4.1`), `message`, `page` (1-based, or `null`) and `object` (such as `12 0 R`, or `null`). The rules cover file structure, metadata (XMP, `pdfaid`, extension schemas), fonts (embedding, glyphs, widths, encodings), colour (output intents, ICC profiles), graphics and transparency, interactive features (annotations, actions, forms, embedded files) and, for level A, the tagged structure. ## Validate PDF/UA [#validate-pdfua] `validatePdfuaJson()` validates against the PDF/UA part the document declares, PDF/UA-1 by default. The report has the same shape, with `level` `PDF/UA-1` or `PDF/UA-2`. ```kotlin val ua = JSONObject(doc.validatePdfuaJson()) Log.i("NexPDF", "${ua.getString("level")} ${ua.getBoolean("compliant")} ${ua.getJSONArray("failures").length()}") ``` PDF/UA-1 follows the Matterhorn Protocol. PDF/UA-2 validation covers the PDF 2.0 namespaces (`/NS`, `/RoleMapNS`, the root `/RoleMap`, MathML), the ISO 14289-2 structure, annotation, form, destination and text-string rules, and the ISO/TS 32005 parent and child rules. ## Convert to a level [#convert-to-a-level] `convertPdfaLevel(level)` converts to the level you choose (`null` is 2b). Level A tags the document first. It returns `true` when the result validates against the level. When some clauses still fail, it returns `false`: the fixes that could be made are kept, and `NexPdfJni.lastError()` lists the clauses that are left: ```kotlin NexPdfDocument.openBytes(report).use { doc -> if (!doc.convertPdfaLevel("3a")) { Log.w("NexPDF", "still failing: ${NexPdfJni.lastError()}") // the document keeps the fixes that worked } File(filesDir, "report-pdfa3a.pdf").writeBytes(doc.saveBytes()) } ``` ## Calls without a typed method [#calls-without-a-typed-method] `NexPdfJni` has no typed method for these engine calls: | C function | Does | |---|---| | `validate_pdfua_part_json(doc, part)` | Validates against PDF/UA-1 (`1`) or PDF/UA-2 (`2`) whatever the document declares, with the same report | | `convert_pdfua_json(doc, part, lang)` | Converts to PDF/UA-1 or -2: tags an untagged document, embeds fonts; for part 2 uses the PDF 2.0 namespace, structure destinations and the annotation rules. `lang` (`null` or `""` is `en-US`) applies when the document has none. Returns `profile`, `compliant`, `fixed`, `warnings`, `substitutions` and `remaining` | | `convert_pdfa_json(doc, level, flatten_dpi, substitute_fonts)` | Converts like `convertPdfaLevel` but reports the clauses that remain instead of failing. `flatten_dpi` is the resolution PDF/A-1 transparency is flattened at (0 or less is 300); `substitute_fonts` 0 leaves non-embedded non-standard fonts alone. Returns `level`, `compliant`, `fixed`, `substitutions` (`original`, `substitute`, `exact`, `widths_adjusted`) and `remaining` (`clause`, `message`, `page`, `object`) | | `register_substitute_font(data)` | Registers TrueType font data (with `glyf` outlines) for PDF/A and PDF/UA substitution: non-embedded fonts with the same PostScript or family name use it. Returns the PostScript name | 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) val h = call("open_bytes", b64(report)) try { val ua2 = JSONObject(call("validate_pdfua_part_json", h, 2) as String) val conv = JSONObject(call("convert_pdfua_json", h, 2, "en-GB") as String) Log.i("NexPDF", "${conv.getString("profile")} ${conv.getBoolean("compliant")} ${conv.get("remaining")}") val pdf = Base64.decode(call("save_bytes", h) as String, Base64.DEFAULT) File(filesDir, "report-ua2.pdf").writeBytes(pdf) } finally { call("close", h) } ``` PDF/A conversion flattens PDF/A-1 transparency into opaque image patches (text stays text), fixes device colour (a CMYK output intent, Default colour spaces), draws missing appearance streams for widgets and markup annotations, substitutes metric-compatible fonts for non-embedded fonts and removes unreachable objects. For PDF/A-4e it keeps U3D and PRC 3D streams and 3D and RichMedia annotations. For raw handles the calls are `NexPdfJni.validatePdfaJson(handle, level)`, `validatePdfuaJson(handle)` and `convertPdfaLevel(handle, level)`. See [PDF/A, PDF/X and PDF/UA](/docs/android/guides/standards) for PDF/X and accessibility tagging. # Conversion (/docs/android/guides/conversion) Conversion to and from Office, HTML, e-book and data formats needs the `conversion` module (Startup tier and above). Images to PDF and Markdown export need no module. ## PDF to Office [#pdf-to-office] ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni NexPdfDocument.openBytes(bytes).use { doc -> val docx = doc.toDocx() val xlsx = NexPdfJni.toXlsx(doc.handle()) // one sheet per page, tables rebuilt val pptx = NexPdfJni.toPptx(doc.handle()) // one slide per page } ``` ## PDF to text formats [#pdf-to-text-formats] | Call | Output | |---|---| | `doc.toJson()` | The document content as JSON | | `doc.toMarkdown()` | Markdown (no module needed) | | `NexPdfJni.reflowHtml(handle, optionsJson)` | Responsive HTML for small screens | | `NexPdfJni.toHtml(handle)`, `toXml`, `toCsv`, `toRtf` | HTML, XML, the tables as CSV, RTF | ```kotlin val html = NexPdfJni.reflowHtml(doc.handle(), """{"images":true,"title":"Report"}""") webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null) ``` For HTML, XML, CSV and RTF, call the `NexPdfJni` methods on the handle. An empty string means the call failed; `NexPdfJni.lastError()` says why: ```kotlin val csv = NexPdfJni.toCsv(doc.handle()) val xml = NexPdfJni.toXml(doc.handle()) ``` ## Office and HTML to PDF [#office-and-html-to-pdf] ```kotlin NexPdfDocument.openOffice(docxBytes).use { pdf -> // Word, Excel or PowerPoint, format detected val proposal = pdf.saveBytes() } NexPdfDocument.fromHtml("

Invoice 1042

Total: 120 EUR

").use { pdf -> val invoice = pdf.saveBytes() } ``` `NexPdfDocument.openBytes` also converts e-books (EPUB, FictionBook, XPS/OpenXPS, CBZ). To skip the format detection, call `NexPdfDocument.openEbook` directly: ```kotlin NexPdfDocument.openEbook(epubBytes).use { book -> val bookPdf = book.saveBytes() } ``` ### Word and Excel options [#word-and-excel-options] Word conversion lays out section columns (equal or unequal, separators, column and continuous breaks), conditional table styles with banding, tight and through wrapping along wrap polygons, floats in table cells and text boxes, and tables in text boxes. Comments are always exported as PDF text annotations anchored at the commented text, with replies and resolved state. Excel formulas without a cached value are calculated; cached values still win. The calculation covers references across sheets, defined names, shared and array formulas, dynamic arrays that spill (`#SPILL!`), Excel error values, about 280 functions (including `*IFS`, `XLOOKUP`, `INDEX`, `OFFSET`, `INDIRECT`, `TEXT` format codes, dates, finance and `FILTER`/`SORT`/`UNIQUE`/`SEQUENCE`), `LET` and `LAMBDA` (named and recursive), `MAP`, `REDUCE`, `SCAN`, `MAKEARRAY`, `BYROW`, `BYCOL` and `ISOMITTED`. Circular references show 0 as Excel does, or iterate when the workbook turns on iterative calculation. Conditional formatting draws every built-in and x14 icon set and x14 data bars. Word, Excel, PowerPoint and HTML conversion shape text with OpenType (Arabic joining, Indic reordering, marks, ligatures) and order it with the full Unicode bidi algorithm, following the document's directions: `w:bidi` and `w:rtl` in Word, right-to-left sheets and `readingOrder` in Excel, right-to-left paragraphs in PowerPoint, `dir` and `direction` in HTML. `NexPdfJni` has no typed method for the two conversions with options. Reach them through `NexPdfJni.invoke`, the whole C API as one JSON call. The documents it returns are its own handles, not `NexPdfDocument` handles, so save them through `invoke` too: | C function | Does | |---|---| | `open_docx_with_options_json(data, options_json)` | Word with `{"show_comments":false,"show_revisions":false}`. `show_comments` draws comments in balloons in a markup area at the right of each page, the page content scaled down, as Word prints with markup. `show_revisions` shows tracked changes as markup (coloured underlined insertions, struck deletions, change bars) instead of the final document | | `open_xlsx_with_clock(data, clock_unix_seconds)` | Excel with `NOW()` and `TODAY()` fixed to that time (seconds since 1970-01-01 00:00, no time zone applied), for reproducible output | ```kotlin import android.util.Base64 import org.json.JSONArray import org.json.JSONObject 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) val h = call("open_docx_with_options_json", b64(docxBytes), """{"show_comments":true,"show_revisions":true}""") try { val markupPdf = Base64.decode(call("save_bytes", h) as String, Base64.DEFAULT) } finally { call("close", h) } val sheet = call("open_xlsx_with_clock", b64(xlsxBytes), 1_798_761_600.0) // 2027-01-01 00:00; save_bytes, then close ``` To fill Word, HTML and PDF templates with JSON data, see [Templates](/docs/android/guides/templates). ## Images to PDF [#images-to-pdf] `NexPdfDocument.openBytes` opens JPEG, PNG and TIFF pictures as a PDF with one page per picture (multi-page TIFF too): ```kotlin NexPdfDocument.openBytes(tiffBytes).use { pdf -> NexPdfJni.insertImagePages(pdf.handle(), pdf.pageCount(), jpegBytes) // append more pictures val scans = pdf.saveBytes() } ``` ## Page images [#page-images] To export pages as PNG, see [Rendering](/docs/android/guides/rendering). # Document structure (/docs/android/guides/document-structure) Reading metadata, bookmarks, page labels, layers and attachments, and switching layers on or off, work without a key. Changing metadata, bookmarks, page labels and attachments needs the `editor` module (Startup tier and above). Every call below is a static method of `NexPdfJni` that takes `doc.handle()`. JSON results are parsed with `org.json`. ## Metadata [#metadata] `metadataJson(handle)` returns the document information dictionary (title, author, subject, keywords and the other entries the file has). `setMetadata(handle, title, author, subject, keywords)` changes it; `null` keeps the current value. ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni import org.json.JSONArray import org.json.JSONObject NexPdfDocument.openBytes(bytes).use { doc -> val h = doc.handle() val info = JSONObject(NexPdfJni.metadataJson(h)) Log.i("NexPDF", "${info.optString("title")} ${info.optString("author")}") NexPdfJni.setMetadata(h, "Q3 report", "Finance", null, null) val titled = doc.saveBytes() } ``` ## Bookmarks [#bookmarks] Bookmarks (the outline) are a JSON tree of `title`, 0-based `page` and optional `children`. `setOutlinesJson` replaces the whole tree. ```kotlin fun walk(items: JSONArray, depth: Int = 0) { for (i in 0 until items.length()) { val item = items.getJSONObject(i) Log.i("NexPDF", " ".repeat(depth) + "${item.getString("title")} (page ${item.getInt("page") + 1})") item.optJSONArray("children")?.let { walk(it, depth + 1) } } } walk(JSONArray(NexPdfJni.outlinesJson(h))) NexPdfJni.setOutlinesJson(h, """[{"title":"Summary","page":0},{"title":"Details","page":2,"children":[{"title":"Costs","page":3}]}]""") ``` ## Page labels [#page-labels] Page labels are the page numbers a viewer shows, such as `i`, `ii` for a preface and `1`, `2` after it. `pageLabelsJson()` returns the label of every page and the ranges that produce them, and `setPageLabelsJson(rangesJson)` sets the ranges (`NexPdfJni.pageLabelsJson(handle)` and `setPageLabelsJson(handle, rangesJson)` for a raw handle): ```kotlin val labels = JSONObject(doc.pageLabelsJson()) Log.i("NexPDF", labels.getJSONArray("labels").toString()) // e.g. ["i","ii","1","2"] check(doc.setPageLabelsJson("""[{"start":0,"style":"roman"},{"start":2,"style":"decimal","first":1}]""")) { NexPdfJni.lastError() } val labelled = doc.saveBytes() ``` Styles are `decimal`, `roman`, `ROMAN`, `letters`, `LETTERS` and `none`. A range can also have a `prefix`, for example `"A-"`. `[]` removes the labels. ## Layers [#layers] Layers (optional content groups) are parts of a page that can be shown or hidden, common in CAD drawings and maps. Each layer is identified by its object number and generation. ```kotlin val layers = JSONArray(NexPdfJni.layersJson(h)) for (i in 0 until layers.length()) { val layer = layers.getJSONObject(i) Log.i("NexPDF", "${layer.getString("name")} ${if (layer.getBoolean("visible")) "visible" else "hidden"}") } val notes = (0 until layers.length()).map { layers.getJSONObject(it) }.first { it.getString("name") == "Notes" } NexPdfJni.setLayerVisible(h, notes.getInt("num"), notes.getInt("gen"), false) // hide; true shows it again val png = NexPdfJni.renderPagePng(h, 0, 144.0) // rendered without the layer ``` ## Attachments [#attachments] PDFs can carry files: at document level (an attachment list) or on a page (a paperclip annotation). `attachmentsJson(handle)` lists both; `page` is `null` for document-level files. ```kotlin val list = JSONArray(NexPdfJni.attachmentsJson(h)) for (i in 0 until list.length()) { val a = list.getJSONObject(i) Log.i("NexPDF", "${a.getString("name")} ${a.optString("mime")} ${a.optLong("size")} ${a.opt("page")}") } File(filesDir, "invoice.xml").writeBytes(NexPdfJni.attachmentData(h, "invoice.xml")) NexPdfJni.addAttachment(h, "data.csv", csvBytes, "text/csv", "Source data") NexPdfJni.removeAttachment(h, "old.csv") val withData = doc.saveBytes() ``` To attach a file to a page with a visible icon, use `addFileAttachmentAnnot`; see [Annotations](/docs/android/guides/annotations#file-attachments). The [reader](/docs/android/reader) shows bookmarks and attachments to the user. ## Related [#related] - [Editing](/docs/android/guides/editing): pages, text and images - [Opening and saving](/docs/android/guides/opening-and-saving) # Editing pages and documents (/docs/android/guides/editing) Page and content editing needs the `editor` module (Startup tier and above). Inserting pictures as pages needs no module. Page indices start at 0. Every call below is a static method of `NexPdfJni` that takes `doc.handle()`. Save with `doc.saveBytes()`. The [reader](/docs/android/reader) offers a page editor and content editing to the user. ## Merge and split [#merge-and-split] ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni NexPdfDocument.openBytes(aBytes).use { a -> NexPdfDocument.openBytes(bBytes).use { b -> NexPdfJni.appendDocument(a.handle(), b.handle()) // a now has the pages of a, then b } val merged = a.saveBytes() // extractPages returns a new native handle (0 on failure); free it yourself. val part = NexPdfJni.extractPages(a.handle(), intArrayOf(0, 1, 2)) try { val firstThree = NexPdfJni.saveBytes(part) } finally { NexPdfJni.free(part) } } ``` ## Insert, duplicate, delete and reorder [#insert-duplicate-delete-and-reorder] ```kotlin val h = doc.handle() NexPdfJni.addBlankPage(h) // appends a blank page NexPdfJni.duplicatePage(h, 0) // inserts a copy of page 0 after it NexPdfJni.movePage(h, 3, 0) // moves page 3 to the front NexPdfJni.deletePage(h, 5) NexPdfJni.reversePages(h) NexPdfJni.insertImagePages(h, 2, jpegBytes) // one page per picture, before page 2 ``` ## Rotate and crop [#rotate-and-crop] ```kotlin NexPdfJni.rotatePage(h, 0, 90) // multiples of 90 degrees NexPdfJni.cropPage(h, 1, 36.0, 36.0, 576.0, 756.0) // new crop box in PDF points ``` ## Page backgrounds [#page-backgrounds] ```kotlin NexPdfJni.setPageBackground(h, """{"color":"#fbf4e2","pages":[]}""", null, 0, 0) // every page NexPdfJni.removePageBackground(h, null) ``` Pass RGB pixels (width x height x 3 bytes) with their size to use a picture, and `"fit"` (`cover`, `stretch` or `center`), `"scale"` and `"opacity"` in the options. ## Edit page text and images [#edit-page-text-and-images] `pageContentJson(handle, page)` lists the text lines and images of a page with an `id` for each: ```kotlin val items = JSONArray(NexPdfJni.pageContentJson(h, 0)) val line = (0 until items.length()).map { items.getJSONObject(it) } .first { it.getString("kind") == "text" && it.optString("text").contains("Draft") } NexPdfJni.editText(h, 0, line.getString("id"), """{"text":"Final","color":"#111827"}""") NexPdfJni.addPageText(h, 0, """{"text":"Approved","x":72,"y":60,"size":14,"color":"#16A34A","bold":true}""") ``` Ids stay valid until the next edit of that page, so read the content again after each change. For images use `transformImage(handle, page, id, llx, lly, urx, ury)` to move or resize, `replaceImage(handle, page, id, rgb, width, height)` to swap the picture and `deleteContent(handle, page, id)` to remove it. ## Related [#related] - [Document structure](/docs/android/guides/document-structure): metadata, bookmarks, page labels and attachments - [Compare and optimise](/docs/android/guides/compare-and-optimize): compare versions and make files smaller # Forms (/docs/android/guides/forms) Every form call needs the `forms` module (Indie tier and above). Every call below is a static method of `NexPdfJni` that takes `doc.handle()`. In the [reader](/docs/android/reader) and in `NexPdfViewerScreen` (Compose), the user types straight into text fields on the page, ticks check boxes and radio buttons and picks from lists; each change runs the field's scripts and the page is drawn again. Tapping a signature field opens **Add signature**, with Draw (black, blue or indigo ink), Image and Type tabs, and puts the picture in the field. Read-only and digitally signed fields are not editable. Filling is off with `modeConfig.readOnly`; the forms mode also adds new fields. This page covers AcroForm fields. For XFA forms (XML Forms Architecture), see [XFA forms](/docs/android/guides/xfa-forms). To fill a PDF from JSON data with placeholders, see [Templates](/docs/android/guides/templates#pdf-templates). ## List the fields [#list-the-fields] ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni import org.json.JSONArray NexPdfDocument.openBytes(bytes).use { doc -> val fields = JSONArray(NexPdfJni.formFieldsJson(doc.handle())) for (i in 0 until fields.length()) { val f = fields.getJSONObject(i) Log.i("NexPDF", "${f.getString("name")} ${f.getString("kind")} ${f.opt("value")} ${if (f.optBoolean("required")) "required" else ""}") } } ``` Each field has `name`, `kind`, `value`, `page`, the rectangle (`llx`, `lly`, `urx`, `ury`), `read_only` and `required`. ## Fill fields [#fill-fields] `fillFormField(handle, name, value)` sets a value as a viewer would: the field's keystroke and validate scripts check it, then every calculated field is recomputed. It returns `false` if the value is rejected, with the script's message in `NexPdfJni.lastError()`. ```kotlin val h = doc.handle() NexPdfJni.fillFormField(h, "applicant.name", "Ana Silva") NexPdfJni.fillFormField(h, "quantity", "4") // calculated totals update NexPdfJni.fillFormField(h, "accept_terms", "true") // check boxes take "true" or "false" if (!NexPdfJni.fillFormField(h, "country", "Portugal")) { // list fields take the option text Log.w("NexPDF", NexPdfJni.lastError()) } val filled = doc.saveBytes() ``` Field appearances are drawn in embedded Unicode fonts (the bundled Liberation fonts, then registered fallback fonts), shaped with OpenType and ordered with Unicode bidi, so Arabic, Hebrew, Indic and other scripts show correctly. Right-to-left text without explicit alignment starts at the right. ## Fill many fields from JSON [#fill-many-fields-from-json] ```kotlin NexPdfJni.importFormJson(h, """{"applicant.name":"Ana Silva","quantity":"4"}""") val values = JSONObject(NexPdfJni.exportFormJson(h)) ``` ## FDF and XFDF [#fdf-and-xfdf] ```kotlin val fdf = NexPdfJni.exportFormFdf(h, "application.pdf") // ByteArray val xfdf = NexPdfJni.exportFormXfdf(h, "application.pdf") // String NexPdfDocument.openBytes(blankBytes).use { blank -> NexPdfJni.importFormFdf(blank.handle(), fdf) // or importFormXfdf val fromFdf = blank.saveBytes() } ``` ## Add fields [#add-fields] `addFormField(handle, pageIndex, kind, name, llx, lly, urx, ury)` creates a field. `kind` is `text`, `checkbox`, `radio`, `combobox`, `listbox`, `button`, `signature` or `barcode`. ```kotlin NexPdfJni.addFormField(h, 0, "text", "customer", 100.0, 700.0, 300.0, 720.0) NexPdfJni.addFormField(h, 0, "checkbox", "newsletter", 100.0, 670.0, 114.0, 684.0) NexPdfJni.addFormField(h, 0, "signature", "signature", 100.0, 100.0, 300.0, 150.0) ``` ## Put a signature picture in a signature field [#put-a-signature-picture-in-a-signature-field] A drawn, typed or scanned signature can be shown in a signature field without signing the document digitally, as when a person signs a form on screen. `doc.setSignatureAppearance(name, rgba, width, height)` takes the picture as RGBA pixels (`width × height × 4` bytes; transparent pixels stay transparent), scales it to fit every widget of the field and centres it. The field must be a signature field that is not read-only. A later digital signature into the same field replaces the picture. The field list then reports `has_appearance: true` for the field. ```kotlin val bmp = BitmapFactory.decodeFile(path).copy(Bitmap.Config.ARGB_8888, false) val rgba = ByteBuffer.allocate(bmp.byteCount).also { bmp.copyPixelsToBuffer(it) }.array() // RGBA order doc.setSignatureAppearance("signature", rgba, bmp.width, bmp.height) ``` The field list also describes how each field is drawn, so a custom UI can lay its own controls over the page: `align` (`left`, `center` or `right`), `font_size` (`null` when the size is automatic), `text_color` (`#rrggbb`); text fields add `multiline`, `password`, `comb`, `scroll` and `max_len`; signature fields add `signed` (signed digitally) and `has_appearance`. ## Recalculate and flatten [#recalculate-and-flatten] ```kotlin NexPdfJni.recalculateForms(h) // runs every calculate script; returns the number of fields changed NexPdfJni.flattenForms(h) // burns the values into the page; the form is no longer editable val final = doc.saveBytes() ``` # Long-term signatures (B-LTA) (/docs/android/guides/long-term-signatures) Signature levels and document timestamps need the `signatures` module (Business tier and above). Verification needs the same module. PAdES B-LTA keeps a signature verifiable for decades. On top of a timestamped signature with its validation data (B-LT), it adds a **document timestamp**: an RFC 3161 timestamp over the whole file, in an invisible signature field. Before the timestamp authority's certificate expires, you add another one (an **archive timestamp**), and so on. Every call on this page returns the complete new file as a `ByteArray`. Write those bytes as they are. An empty array means the call failed; `NexPdfJni.lastError()` says why. Calls with `tsa_url` or `ltv` go to the network: add the `INTERNET` permission to your manifest and run them off the main thread. ## Sign at a chosen level [#sign-at-a-chosen-level] `NexPdfJni.signPkcs12` and `completeExternalSignature` take a `level` option: | `level` | What you get | Needs | |---|---|---| | `B-B` | Signature only | | | `B-T` | Plus a signature timestamp | `tsa_url` or a TSA callback | | `B-LT` | Plus certificates, OCSP responses and CRLs (DSS) | `tsa_url` or a TSA callback | | `B-LTA` | Plus a document timestamp | `tsa_url` or a TSA callback | ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni val options = """ { "reason": "Approved", "level": "B-LTA", "tsa_url": "http://timestamp.example.com", "timestamp": { "hash": "SHA-256", "field": "Timestamp1" } } """ val signed = NexPdfDocument.openBytes(contract).use { doc -> NexPdfJni.signPkcs12(doc.handle(), p12Bytes, "p12-password", options) } check(signed.isNotEmpty()) { NexPdfJni.lastError() } File(filesDir, "contract-lta.pdf").writeBytes(signed) ``` `timestamp` is optional and configures the document timestamp: `hash`, `field` and `reserved` (bytes kept for the token). ## Add a document timestamp [#add-a-document-timestamp] `doc.addDocumentTimestamp(optionsJson)` timestamps an open document, and `NexPdfJni.addDocumentTimestampBytes(pdfBytes, optionsJson)` timestamps the bytes of a file, for example straight from a signing call. ```kotlin val data = File(filesDir, "contract-signed.pdf").readBytes() // a B-T signature val lta = NexPdfJni.addDocumentTimestampBytes(data, """{"tsa_url":"http://timestamp.example.com","ltv":true}""") check(lta.isNotEmpty()) { NexPdfJni.lastError() } ``` | Option | Default | Meaning | |---|---|---| | `tsa_url` | the TSA callback | The RFC 3161 timestamp authority. Required when no TSA callback is set | | `hash` | `SHA-256` | `SHA-256`, `SHA-384` or `SHA-512` | | `field` | `Timestamp1` | Name of the timestamp's signature field | | `reserved` | `16384` | Bytes reserved for the token | | `ltv` | | First add the certificates, OCSP responses and CRLs of every earlier signature and timestamp to the DSS | With `ltv`, the same call turns a B-T signature into B-LTA, and renews the archive timestamp of a B-LTA file. Run it again before the last timestamp's certificate expires. ## Your own TSA or HSM [#your-own-tsa-or-hsm] ### As a callback [#as-a-callback] `NexPdfTsa.setCallback(callback)` registers, process-wide, a timestamp authority your app provides: an HSM, or an HTTP client that adds authentication. The callback gets the DER RFC 3161 `TimeStampReq` and returns the DER `TimeStampResp` or `TimeStampToken`. ```kotlin import com.nexdevit.nexpdf.NexPdfTsa NexPdfTsa.setCallback { request -> companyTsa.timestamp(request) } // ByteArray -> ByteArray val signed = NexPdfJni.signPkcs12(doc.handle(), p12Bytes, "p12-password", """{"level":"B-LTA"}""") // no tsa_url needed NexPdfTsa.clearCallback() ``` The callback is used when no `tsa_url` is given, by `addDocumentTimestamp`, `NexPdfJni.addDocumentTimestampBytes`, and by `NexPdfJni.signPkcs12` and `completeExternalSignature` at level B-T, B-LT or B-LTA. A `tsa_url` always wins. It runs on the thread that called NexPDF, possibly several at once, and must not call `NexPdfTsa`. Throwing, or returning `null` or an empty array, fails the call with "TSA callback failed (code N)". A new callback replaces the earlier one. ### In steps [#in-steps] When the timestamp comes from your own service and you prefer no callback, do it in three steps with no state in between: ```kotlin val prepared = NexPdfDocument.openBytes(signedBytes).use { doc -> doc.prepareDocumentTimestamp("""{"field":"Archive2"}""") // options without tsa_url } val request = NexPdfJni.documentTimestampRequest(prepared, "SHA-256") // DER TimeStampReq val token = myTsa.post(request, "application/timestamp-query") // your call val stamped = NexPdfJni.completeDocumentTimestamp(prepared, token) check(stamped.isNotEmpty()) { NexPdfJni.lastError() } ``` `token` is the DER `TimeStampResp` or `TimeStampToken`. It must verify and match the document. `documentTimestampRequest` takes `null` for SHA-256. ## Calls without a typed method [#calls-without-a-typed-method] `NexPdfJni` has no typed method for online signing in steps or for B-LTA validation. Reach these engine calls through `NexPdfJni.invoke`, the whole C API as one JSON call (bytes as base64): | C function | Does | |---|---| | `signature_timestamp_request(data, hash)` | B-T: a DER `TimeStampReq` over the last signature value (`null` hash = SHA-256), to POST as `application/timestamp-query` | | `add_signature_timestamp(data, token)` | Stores the TSA's answer in the last signature without changing the signed bytes | | `ltv_requests_json(data, responses_json)` | B-LT: the HTTP requests still needed, `[{"method","url","content_type","body"}]`. Call again with the same objects plus `"response"` (base64) or `"error"` until it returns `[]` | | `add_ltv_with_responses(data, responses_json)` | Adds the DSS from those answers | | `validate_lta_json(data, trust_roots_pem)` | Full B-LTA validation, with OCSP checks | ```kotlin import android.util.Base64 import org.json.JSONArray import org.json.JSONObject 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) fun unb64(text: Any?) = Base64.decode(text as String, Base64.DEFAULT) val tsReq = unb64(call("signature_timestamp_request", b64(signed), null)) val token = myTsa.post(tsReq, "application/timestamp-query") // your call val bt = unb64(call("add_signature_timestamp", b64(signed), b64(token))) val lta = JSONObject(call("validate_lta_json", b64(ltaBytes), rootsPem) as String) Log.i("NexPDF", "complete: ${lta.getBoolean("complete")}") ``` `validate_lta_json` checks, for every document timestamp, whether the DSS of the revision it timestamps holds every certificate and revocation entry for the earlier signatures, their TSAs and earlier document timestamps. OCSP responses are verified: signature, responder (the issuing CA or a certificate it delegated with `id-kp-OCSPSigning`), responder chain to your roots, `thisUpdate`/`nextUpdate` around the timestamp that protects the DSS, and status. It returns `complete` and `timestamps`, each with `field`, `time`, `valid`, `has_dss`, `complete`, `covers` and `issues` (`field`, `role`, `subject`, `kind`). An issue `kind` is `missing-certificate`, `missing-revocation`, `revoked`, `ocsp-bad-signature`, `ocsp-unauthorized-responder`, `ocsp-untrusted-responder`, `ocsp-not-current` or `ocsp-unknown-status`. ## Verify [#verify] `NexPdfJni.verifySignaturesJson` reports every signature and every document timestamp. Two fields are new in 1.1: | Field | Meaning | |---|---| | `document_timestamp` | `true` for a document timestamp. Then `signer` is the TSA, `digest_ok` checks the message imprint and `trusted` checks the TSA chain against your roots | | `pades_level` | `B-B`, `B-T`, `B-LT` or `B-LTA` | ```kotlin val sigs = JSONArray(NexPdfJni.verifySignaturesJson(File(filesDir, "contract-lta.pdf").readBytes())) for (i in 0 until sigs.length()) { val s = sigs.getJSONObject(i) val kind = if (s.optBoolean("document_timestamp")) "timestamp" else "signature" Log.i("NexPDF", "$kind ${s.optString("signer")} ${s.optString("pades_level")} ${s.optBoolean("digest_ok") && s.optBoolean("signature_ok")}") } ``` See [Digital signatures](/docs/android/guides/signatures) for signing with PKCS#12 files and external devices. # OCR (/docs/android/guides/ocr) OCR needs the `ocr` module (Enterprise tier). `NexPdfJni.ocrJson(handle, optionsJson)` recognises the text of scanned pages and adds it as an invisible text layer, so the PDF becomes searchable and its text can be extracted. The page images are not changed. It returns the JSON report, or an empty result on failure. ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni import org.json.JSONObject val searchable = withContext(Dispatchers.Default) { // OCR takes time: keep it off the main thread NexPdfDocument.openBytes(scanBytes).use { doc -> val report = JSONObject(NexPdfJni.ocrJson(doc.handle(), """{"languages":"por+eng"}""")) Log.i("NexPDF", "${report.getString("engine")} ${report.getInt("pages")} ${report.getInt("words")} ${report.getDouble("confidence")}") doc.saveBytes() } } ``` ## Options [#options] | Option | Default | Meaning | |---|---|---| | `engine` | `auto` | `builtin`, `tesseract`, `neural`, or `auto`: a loaded neural model that reads the requested languages, else Tesseract when it is installed with every requested language, else the built-in engine | | `languages` | `por+eng+spa` | Language codes joined with `+` (Tesseract codes such as `chi_sim` or ISO 639-1 codes such as `ar`). The built-in engine reads Latin-script text in any language | | `dpi` | `300` | Resolution the pages are rendered at for recognition | | `pages` | every page | 0-based page indices | | `force` | `false` | Also process pages that already have text | Tesseract is the `tesseract` command-line program for desktops and servers. On Android, `auto` uses a loaded neural model or the built-in engine, which needs nothing else. ## Other scripts: neural models [#other-scripts-neural-models] The built-in engine reads printed Latin-script text (English, Portuguese, Spanish, French, German and others) with no models. For Chinese, Japanese, Korean, Arabic, Persian, Urdu, Cyrillic, Devanagari, Thai, Greek and other scripts, load **neural OCR models** at run time. No model is bundled: your app ships or downloads the ones it needs. You need one **text detection** model, which serves every language, and one **recognition** model per script with its **character dictionary** (UTF-8 text, one symbol per line). Any PaddleOCR detection and CTC recognition model exported to ONNX works (PP-OCRv3, v4 and v5). A ready-made set is [`monkt/paddleocr-onnx`](https://huggingface.co/monkt/paddleocr-onnx) on Hugging Face (Apache-2.0): | File | Use | `languages` | |---|---|---| | `detection/v3/det.onnx` (2.4 MB) | Detection, mobile | all | | `detection/v5/det.onnx` (88 MB) | Detection, server | all | | `languages/chinese/rec.onnx` + `dict.txt` | Chinese, Japanese | `zh+ja+en` | | `languages/korean/…` | Korean | `ko` | | `languages/arabic/…` | Arabic, Persian, Urdu | `ar+fa+ur` | | `languages/eslav/…` | Cyrillic | `ru+uk+be+bg` | | `languages/hindi/…` | Devanagari | `hi+mr+ne+sa` | The PaddleOCR model zoo (converted with `paddle2onnx`) and RapidOCR publish the same models. The dictionary must be the one the model was trained with; loading checks it. On phones, use the mobile models (a few MB): the server models are more accurate but much larger. Put the files in `assets/` and keep `.onnx` files uncompressed in the APK, so they are not inflated twice, or download them once into app storage: ```kotlin title="build.gradle.kts" android { androidResources { noCompress += "onnx" } } ``` Load them once, for example at start-up off the main thread. `NexPdfJni.ocrLoadModel(optionsJson, model, dictionary)` returns `false` on failure, with the reason in `NexPdfJni.lastError()`: ```kotlin import com.nexdevit.nexpdf.NexPdfJni val det = assets.open("ocr/det.onnx").use { it.readBytes() } val rec = assets.open("ocr/arabic/rec.onnx").use { it.readBytes() } val dict = assets.open("ocr/arabic/dict.txt").bufferedReader().use { it.readText() } check(NexPdfJni.ocrLoadModel("""{"kind":"detection"}""", det, null)) { NexPdfJni.lastError() } check(NexPdfJni.ocrLoadModel("""{"kind":"recognition","languages":"ar+fa+ur","name":"arabic"}""", rec, dict)) { NexPdfJni.lastError() } Log.i("NexPDF", NexPdfJni.ocrModelsJson()) // kind, name, languages, symbols, size NexPdfDocument.openBytes(scanBytes).use { doc -> val report = JSONObject(NexPdfJni.ocrJson(doc.handle(), """{"languages":"ara"}""")) Log.i("NexPDF", report.getString("engine")) // "neural (arabic)" val searchable = doc.saveBytes() } NexPdfJni.ocrUnloadModels("ar") // or null for every model ``` Models are loaded once per process and used by every document. `ocrLoadModel` options: | Option | Meaning | |---|---| | `kind` | `detection`, `recognition` or `classification` (required) | | `languages` | Languages a recognition model reads, joined with `+`, as ISO 639-1 (`ar`) or Tesseract (`ara`) codes | | `name` | Name in listings; loading the same kind and name again replaces the model | | `input_height` | Recognition input height when the model leaves it open (default 48) | | `max_side` | Detection: longest side, in pixels, of the page image the detector sees (default 1536) | A detection model takes `null` as its dictionary. `ocrUnloadModels(languages)` returns the number of models removed. An optional **classification** model is the PaddleOCR `cls` text-direction model (0 or 180 degrees, input 3x48x192). It also takes `null` as its dictionary: ```kotlin val cls = assets.open("ocr/cls.onnx").use { it.readBytes() } check(NexPdfJni.ocrLoadModel("""{"kind":"classification"}""", cls, null)) { NexPdfJni.lastError() } ``` Without it, upright or upside down is decided by the recogniser's confidence read both ways. With several languages (`"rus+chi_sim"`) every matching model reads each line and the most confident reading wins. Right-to-left lines are written in logical order: Arabic word spaces are restored from the gaps in the ink and presentation forms are mapped to plain letters. Vertical CJK columns are read right to left, in the report and in the text layer, and text extraction reads vertical text as columns right to left. Slanted lines are read as rotated boxes and the text layer follows the slant. Recognition runs on the calling thread: keep it off the main thread. ## Orientation and skew [#orientation-and-skew] Pages scanned sideways or upside down (0, 90, 180 or 270 degrees) and skewed pages are read upright, and the text layer is mapped back onto the original page. The built-in engine corrects skew up to 20 degrees, the neural engine up to 15 degrees either way (besides the quarter turns). The built-in engine also reads ß, œ, æ, ÿ, ì, Ò, Ù and the Catalan middle dot, and drops scanner specks. The OCR text layer uses glyph-less TrueType/CID fonts, so convert to PDF/A after OCR when the file must be PDF/A. Limits: curved lines are read only when the curve is gentle, and neural OCR does not correct skew beyond 15 degrees. ## The report [#the-report] | Field | Meaning | |---|---| | `engine` | The engine that ran | | `pages` | Pages recognised | | `skipped` | Pages skipped because they already had text | | `words` | Words recognised | | `confidence` | Average word confidence, 0 to 1 | | `text` | The recognised text, one string per page | # Office editing (/docs/android/guides/office-editing) Office editing needs the `conversion` module (Startup tier and above). NexPDF edits `.xlsx` workbooks and `.docx` documents directly. No Office install or server is involved. Only what you change is rewritten: styles, merged cells, column widths, conditional formats, charts, images, numbering and headers stay exactly as they were. The calls are `NexPdfFunctions.xlsxEdit`, `xlsxCellsJson`, `docxEdit` and `docxParagraphsJson`. Each takes the file bytes and JSON, and returns the new file. To get a PDF, open the result as an Office document. ## Excel: set cells and recalculate [#excel-set-cells-and-recalculate] ```kotlin import com.nexdevit.nexpdf.NexPdfFunctions import org.json.JSONArray import org.json.JSONObject val xlsx = context.assets.open("budget.xlsx").readBytes() val edits = JSONObject() .put("sheet", "Budget") .put("edits", JSONArray() .put(JSONObject().put("cell", "C2").put("value", 6.5)) .put(JSONObject().put("cell", "Summary!B1").put("value", "=SUM(Budget!D1:D3)"))) val edited = NexPdfFunctions.xlsxEdit(xlsx, edits.toString()) val cells = JSONObject(NexPdfFunctions.xlsxCellsJson(edited, """{"sheet":"Budget","range":"A1:D12"}""")) ``` Each edit names a `cell`: `C2`, `$C$2` or `Summary!B1`. With no sheet in the cell or in the edit, the top-level `sheet` applies, else the first sheet. The value decides what is written: | Value | Written as | |---|---| | a number | a number (the cell keeps its number format) | | `true` / `false` | a boolean | | text | text, kept as text even when it looks like a number | | text starting with `=` | a formula (`"formula": "SUM(A1:A3)"` says so explicitly) | | `"text": "=…"` | text that starts with `=` | | `null` | the cell is cleared (it keeps its format) | `ranges` writes rows of values from `start`, down and to the right, for tables and imports. After the edits, **every formula in the workbook is recalculated** by the built-in evaluator, across sheets and defined names, and the results are stored in the file. Readers that do not calculate, and the PDF converter, then show the new values. Chart caches are refreshed from their cells, and the workbook is marked to recalculate when Excel or LibreOffice opens it. Pass `"recalculate": false` to only write the cells. `clock_unix_seconds` fixes `NOW()` and `TODAY()`, and `rand_seed` fixes `RAND()`. - A cell that belongs to a **shared formula** gets its own formula, and the other cells of the group keep working with their references moved. - An **array formula** can be changed or cleared from its first cell. Changing another cell of its range is an error, as in Excel. - Text is written as inline strings, so the shared string table is never rewritten. `xlsx_cells_json` reads cells back: `{"sheets": [{"name", "cells": [{"cell", "row", "col", "type", "value", "formula"}]}]}`. `type` is `number`, `text`, `bool` or `error`; for an error, `value` is the error text, such as `#DIV/0!`. Options: `sheet`, `range` and `recalculate`. By default it returns the values stored in the file; `"recalculate": true` calculates the formulas first. ## Word: replace and insert text [#word-replace-and-insert-text] ```kotlin val docx = context.assets.open("offer.docx").readBytes() val paragraphs = JSONArray(NexPdfFunctions.docxParagraphsJson(docx)) val editedDocx = NexPdfFunctions.docxEdit(docx, """ [{"op": "replace", "find": "{client}", "replace": "ACME Ltd", "required": true}, {"op": "insert", "after": 3, "text": "Delivery within 10 working days."}, {"op": "delete", "paragraph": 7}] """.trimIndent()) ``` Operations run in order. Each one sees the document as the previous ones left it. | Operation | What it does | |---|---| | `replace` | Replaces every occurrence of `find` in the body, tables, headers, footers, footnotes and endnotes, also where Word split the text over several runs. The new text takes the format of the run where the match starts. `match_case` (default `true`); with `required`, finding nothing is an error. | | `set_text` | Replaces the text of a paragraph. It keeps the paragraph's style and settings and the format of its first run. Its other content (images, fields) is removed. | | `insert` | Adds a paragraph `before` or `after` a paragraph, or `at` `"start"` or `"end"` of the document. With a `style` (a style id such as `Heading2`) it takes that style. Without one, it copies the neighbouring paragraph, so inserting after a list item makes another list item. | | `delete` | Removes a paragraph. If it is the only paragraph of a table cell, it is emptied instead. | In text, `\n` is a line break and `\t` a tab. Paragraphs are numbered from 0 in document order, table cells included and text boxes left out. `docx_paragraphs_json` lists them as `[{"index", "style", "text", "in_table"}]`, so you can find the index to act on. To fill whole documents from data, with loops over table rows, conditions and images, use [templates](./templates). ## Limits [#limits] - Excel: rows and columns are not inserted or deleted, so references do not move. Formulas the evaluator does not know return `#NAME?` until Excel recalculates them on opening. - Word: tracked changes are not created, and edits are not tracked. Text inside fields and text boxes is not replaced. # Opening and saving (/docs/android/guides/opening-and-saving) Opening PDFs and pictures, saving and copying are part of the `viewer` module and work without a key. Creating a PDF from HTML, Office or e-book files needs the `conversion` module (Startup tier and above). ## Open bytes, a file or a content URI [#open-bytes-a-file-or-a-content-uri] Every open call takes the document's bytes. Read them from wherever the file is: a file in app storage, a `content:` URI from the system picker or another app, the assets, or a download. Do it off the main thread for large files. ```kotlin import com.nexdevit.nexpdf.NexPdfDocument val fromFile = File(filesDir, "contract.pdf").readBytes() val fromUri = contentResolver.openInputStream(uri)!!.use { it.readBytes() } NexPdfDocument.openBytes(fromUri).use { doc -> Log.i("NexPDF", "${doc.pageCount()} pages") } ``` `openBytes` also accepts JPEG, PNG and TIFF pictures (one page per picture), and converts Word, Excel and PowerPoint files, EPUB and FictionBook books, XPS/OpenXPS packages and CBZ comics; see below. A document holds native memory. Close it with `close()`, `use { }` or try-with-resources; after `close()` every method throws `IllegalStateException`. A document that is never closed is never freed. ## Encrypted documents [#encrypted-documents] `NexPdfDocument.openBytes(bytes)` fails with `password required` for an encrypted file. Pass the user (open) password or the owner password to `NexPdfDocument.openBytes(bytes, password)`. A missing or wrong password throws `IllegalArgumentException` with `password required` or `incorrect password`, and `NexPdfDocument.isPasswordError(e)` tells those apart from other failures: ```kotlin val doc = try { NexPdfDocument.openBytes(bytes, "s3cret") } catch (e: IllegalArgumentException) { if (NexPdfDocument.isPasswordError(e)) askTheUserAgain() else Log.e("NexPDF", e.message ?: "") return } doc.use { Log.i("NexPDF", it.pageText(0)) } ``` Office files, e-books and comics carry no PDF password: with a password, `openBytes` converts them as usual and ignores it. For a raw handle, `NexPdfJni.openBytesWithPassword(bytes, password)` returns `0` on failure, with the reason in `NexPdfJni.lastError()`; free it with `NexPdfJni.free`. RC4, AES-128 and AES-256 files are supported. Files that are only restricted by permissions (no open password) open with `openBytes`. `NexPdfJni.securityJson(handle)` reports the encryption and permissions; see [Security](/docs/android/guides/security). ## Create a PDF from other formats [#create-a-pdf-from-other-formats] | Source | Function | Module | |---|---|---| | JPEG, PNG, TIFF | `NexPdfDocument.openBytes(bytes)` or `openImage(bytes)` | none | | HTML | `NexPdfDocument.fromHtml(html)` | `conversion` | | Word, Excel, PowerPoint | `NexPdfDocument.openBytes(bytes)` or `openOffice(bytes)` | `conversion` | | EPUB, FictionBook, XPS/OpenXPS, CBZ | `NexPdfDocument.openBytes(bytes)` or `openEbook(bytes)` | `conversion` | ```kotlin NexPdfDocument.openBytes(tiffBytes).use { scan -> // one page per TIFF frame File(filesDir, "scan.pdf").writeBytes(scan.saveBytes()) } NexPdfDocument.fromHtml("

Invoice 42

Total: 120 EUR

").use { invoice -> File(filesDir, "invoice.pdf").writeBytes(invoice.saveBytes()) } NexPdfDocument.openBytes(epubBytes).use { book -> // EPUB, FictionBook, XPS or CBZ File(filesDir, "book.pdf").writeBytes(book.saveBytes()) } ``` `openBytes` reads the file names inside a ZIP (without decompressing anything) to pick the e-book or the Office converter. To add pictures to an existing document, use `NexPdfJni.insertImagePages(handle, index, bytes)`; see [Editing](/docs/android/guides/editing). ## Save [#save] `saveBytes()` returns the document with every change as a complete new file. Write it wherever it goes: a file, a `content:` URI from `ACTION_CREATE_DOCUMENT`, or an upload. ```kotlin val pdf = doc.saveBytes() File(filesDir, "out.pdf").writeBytes(pdf) contentResolver.openOutputStream(targetUri)!!.use { it.write(pdf) } ``` For a raw handle, `NexPdfJni.saveBytes(handle)` does the same. ### Fast Web View [#fast-web-view] A linearized file shows its first page before the download ends, which helps when PDFs are served over HTTP. `saveLinearized()` returns such a file (`NexPdfJni.saveLinearized(handle)` for a raw handle): ```kotlin val webReady = doc.saveLinearized() ``` Signing returns the finished signed file. Write those bytes as they are: saving the document object again rewrites the file and breaks the signature. See [Signatures](/docs/android/guides/signatures). ## Copy a document [#copy-a-document] There is no copy method. Open the saved bytes to get an independent document with the same content and changes, for example as an undo snapshot or to hand work to another thread: ```kotlin val snapshot = NexPdfDocument.openBytes(doc.saveBytes()) ``` ## In the reader [#in-the-reader] The [reader](/docs/android/reader) opens a `content:` or `file:` URI given in its intent, converts Word, Excel and PowerPoint files and pictures, asks for the password of encrypted files, and lets the user save with **Save as**. ## Related [#related] - [Document structure](/docs/android/guides/document-structure): metadata, bookmarks and attachments - [Conversion](/docs/android/guides/conversion): PDF to Word, Excel, HTML and more - [Compare and optimise](/docs/android/guides/compare-and-optimize): smaller files and memory # Redaction (/docs/android/guides/redaction) Redaction needs the `redaction` module (Business tier and above). Redaction in NexPDF is destructive: the text, images and annotations under the area are removed from the file, not just covered, and an opaque box is painted over it: black, or white with `fillWhite = true`. Save the document afterwards. The [reader](/docs/android/reader) has a redaction mode for the user. ## Redact an area [#redact-an-area] ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni NexPdfDocument.openBytes(bytes).use { doc -> // handle, page, llx, lly, urx, ury, fillWhite NexPdfJni.applyRedaction(doc.handle(), 0, 72.0, 600.0, 300.0, 620.0, false) val redacted = doc.saveBytes() } ``` ## Redact every match of a text, an expression or a pattern [#redact-every-match-of-a-text-an-expression-or-a-pattern] `NexPdfJni.redactMatches(handle, query, mode, fillWhite)` finds and redacts every match in the document and returns the number of areas redacted, or `-1` on error. | `mode` | `query` is | |---|---| | `0` | Plain text | | `1` | A regular expression | | `2` | A pattern id: `email`, `phone`, `credit-card`, `iban`, `pt-nif`, `us-ssn`, `ipv4`, `url`, `date` | ```kotlin val h = doc.handle() var n = NexPdfJni.redactMatches(h, "CONFIDENTIAL", 0, false) n += NexPdfJni.redactMatches(h, """\b\d{3}-\d{2}-\d{4}\b""", 1, false) n += NexPdfJni.redactMatches(h, "email", 2, false) Log.i("NexPDF", "$n areas redacted") val redacted = doc.saveBytes() ``` ## Review before redacting [#review-before-redacting] Use [search](/docs/android/guides/search) to show the matches to a reviewer first, for example as highlight annotations, and apply the redaction once they are approved. Redaction cannot be undone in the saved file. Keep the original if you may need it. # Rendering pages (/docs/android/guides/rendering) Rendering is part of the `viewer` module and works without a key. Unlicensed and trial renders carry a watermark; commercial keys render without one. ## Render a page [#render-a-page] `renderPagePng(pageIndex, dpi)` returns the PNG bytes of a page. At 72 dpi one pixel is one PDF point. For a sharp image, multiply 72 by the screen density and the zoom: ```kotlin import android.graphics.BitmapFactory import com.nexdevit.nexpdf.NexPdfDocument val dpi = 72.0 * resources.displayMetrics.density val png = doc.renderPagePng(0, dpi) val bitmap = BitmapFactory.decodeByteArray(png, 0, png.size) ``` Rendering is synchronous. Run it off the main thread: ```kotlin lifecycleScope.launch { val bitmap = withContext(Dispatchers.Default) { val png = doc.renderPagePng(3, 144.0) BitmapFactory.decodeByteArray(png, 0, png.size) } imageView.setImageBitmap(bitmap) } ``` ## Render a thumbnail [#render-a-thumbnail] `NexPdfJni.renderThumbPng(handle, pageIndex, maxDim)` fits the page into a square of `maxDim` pixels, keeping the aspect ratio: ```kotlin val thumb = NexPdfJni.renderThumbPng(doc.handle(), 0, 256) ``` ## Page size and orientation [#page-size-and-orientation] `pageWidth(i)` and `pageHeight(i)` return the displayed size in points, with the crop box, `/Rotate` and `/UserUnit` applied. `pageView(i)` returns a `PageView` with the rotation, the crop box and the transform from PDF user space to the displayed page: ```kotlin val view = doc.pageView(0) Log.i("NexPDF", "${view.width} x ${view.height}, rotation ${view.rotation}") val k = dpi / 72 // pixels per point val (x, y) = view.toView(k, 72.0, 700.0) // PDF point to bitmap pixels, origin top-left val pdf = view.toPdf(k, tapX.toDouble(), tapY.toDouble()) // a tap back to PDF points ``` `rectToView` and `rectToPdf` convert rectangles the same way, for example to draw a search hit on the bitmap. ## Memory [#memory] Decoded fonts, glyphs and images are cached by the renderer for the whole process, within a size limit, so a font or picture used on many pages is decoded once. `NexPdfJni.memoryUsageBytes(handle)` estimates what a document uses, and `NexPdfJni.trimMemory(doc.handle())` compacts its buffers from `onTrimMemory`. See [Platform notes](/docs/android/platform-notes#memory). ## Overprint simulation [#overprint-simulation] Renders simulate overprint for PDF/X documents only, the engine default. `NexPdfJni.setOverprint(handle, mode)` changes it for later renders of that document. Mode `0` is the default, `1` always simulates, `2` never: ```kotlin NexPdfJni.setOverprint(doc.handle(), 1) val png = doc.renderPagePng(0, 300.0) ``` ## Related [#related] - [`renderPagePng`](/docs/android/api-reference#renderpagepng), [`renderThumbPng`](/docs/android/api-reference#renderthumbpng) - [Text extraction](/docs/android/guides/text-extraction) # Search (/docs/android/guides/search) Search is part of the `viewer` module and works without a key. `searchJson(query)` searches every page, case-insensitively, and returns a JSON array of hits: ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import org.json.JSONArray NexPdfDocument.openBytes(bytes).use { doc -> val hits = JSONArray(doc.searchJson("termination")) for (i in 0 until hits.length()) { val hit = hits.getJSONObject(i) Log.i("NexPDF", "page ${hit.getInt("page") + 1}: ${hit.getString("context")}") } } ``` Each hit has: | Field | Meaning | |---|---| | `page` | 0-based page index | | `context` | The text around the match | | `llx`, `lly`, `urx`, `ury` | The rectangle of the match in PDF points | To draw a hit on a rendered page, convert its rectangle with `doc.pageView(page).rectToView(k, ...)`. See [Rendering](/docs/android/guides/rendering#page-size-and-orientation). ## Highlight every match [#highlight-every-match] With the `annotations` module you can turn the hits into highlight annotations: ```kotlin for (i in 0 until hits.length()) { val h = hits.getJSONObject(i) NexPdfJni.addAnnotation(doc.handle(), h.getInt("page"), "Highlight", "#FFD400", 1.0, "", h.getDouble("llx"), h.getDouble("lly"), h.getDouble("urx"), h.getDouble("ury")) } val highlighted = doc.saveBytes() ``` ## Redact every match [#redact-every-match] To remove the matches permanently instead, use `NexPdfJni.redactMatches`. See [Redaction](/docs/android/guides/redaction). ## Scanned documents [#scanned-documents] Search finds only real text. Run [OCR](/docs/android/guides/ocr) on scanned pages first. # Encryption and permissions (/docs/android/guides/security) Encrypting, removing passwords, watermarks, headers, footers and Bates numbering need the `security` module (Startup tier and above). Opening encrypted files and reading their security settings work without a key. ## Open an encrypted PDF [#open-an-encrypted-pdf] `NexPdfDocument` has no password parameter. Open encrypted files with `NexPdfJni.openBytesWithPassword`, which returns a native handle (`0` on failure). Use it with the `NexPdfJni` methods and free it with `NexPdfJni.free`: ```kotlin import com.nexdevit.nexpdf.NexPdfJni val h = NexPdfJni.openBytesWithPassword(bytes, "secret") if (h == 0L) { Log.e("NexPDF", NexPdfJni.lastError()) // "password required" or "incorrect password" return } try { val info = JSONObject(NexPdfJni.securityJson(h)) Log.i("NexPDF", "${info.optBoolean("encrypted")} ${info.optBoolean("owner")} ${info.optBoolean("print")}") val text = NexPdfJni.extractPageText(h, 0) } finally { NexPdfJni.free(h) } ``` The user (open) password or the owner password both work. RC4, AES-128 and AES-256 files are supported. `securityJson` reports `encrypted`, `revision`, `owner` (opened with owner access) and the permissions `print`, `modify`, `copy`, `annotate`, `fill_forms` and `assemble`. ## Encrypt with AES-256 [#encrypt-with-aes-256] ```kotlin NexPdfJni.encryptAes256(doc.handle(), "user-password", "owner-password") val encrypted = doc.saveBytes() ``` An empty user password lets anyone open the file while the owner password still protects the permissions. ## Set permissions [#set-permissions] `encryptWithPermissions(handle, userPw, ownerPw, permissions)` takes a bit mask of what users without the owner password may do. `NexPdfJni` has a constant for each flag: | Flag | Constant | Value | |---|---|---| | Print | `PERM_PRINT` | 1 | | Modify | `PERM_MODIFY` | 2 | | Copy text and images | `PERM_COPY` | 4 | | Annotate | `PERM_ANNOTATE` | 8 | | Fill forms | `PERM_FILL_FORMS` | 16 | | Assemble (insert, rotate, delete pages) | `PERM_ASSEMBLE` | 32 | ```kotlin NexPdfJni.encryptWithPermissions(doc.handle(), "", "owner-password", NexPdfJni.PERM_PRINT or NexPdfJni.PERM_FILL_FORMS) val printAndFillOnly = doc.saveBytes() ``` ## Remove a password [#remove-a-password] ```kotlin val h = NexPdfJni.openBytesWithPassword(encrypted, "owner-password") try { NexPdfJni.removePassword(h, null) // or pass the owner password here val decrypted = NexPdfJni.saveBytes(h) } finally { NexPdfJni.free(h) } ``` ## Watermarks, headers, footers and Bates numbers [#watermarks-headers-footers-and-bates-numbers] ```kotlin val h = doc.handle() NexPdfJni.addWatermark(h, "CONFIDENTIAL") NexPdfJni.addHeaderFooter(h, "Acme, Lda", "Page {page} of {total}", 9.0) // font size 0 = default NexPdfJni.addBates(h, "ACME-", 1, 6) // ACME-000001, ACME-000002, ... NexPdfJni.removeWatermarks(h) // removes NexPDF watermarks ``` # Digital signatures (/docs/android/guides/signatures) Signing, LTV and verification (with or without your own roots) need the `signatures` module (Business tier and above). Every signing call returns the **complete signed file** as a `ByteArray`. Write those bytes as they are: saving the document object again afterwards breaks the signature. An empty array means the call failed; `NexPdfJni.lastError()` says why. ## Sign with a PKCS#12 file [#sign-with-a-pkcs12-file] ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni val options = """ { "reason": "Approved", "location": "Lisbon", "tsa_url": "http://timestamp.example.com", "ltv": true, "appearance": { "page": 0, "rect": [360, 60, 560, 120], "text": "Signed by Ana Silva" } } """ val signed = NexPdfDocument.openBytes(contract).use { doc -> NexPdfJni.signPkcs12(doc.handle(), p12Bytes, "p12-password", options) } check(signed.isNotEmpty()) { NexPdfJni.lastError() } File(filesDir, "contract-signed.pdf").writeBytes(signed) ``` Options: `name`, `reason`, `location`, `contact`, `field` (an existing signature field), `tsa_url` (PAdES B-T), `ltv` (PAdES B-LT), `level` (`B-B`, `B-T`, `B-LT` or `B-LTA`, see [Long-term signatures](/docs/android/guides/long-term-signatures)), `timestamp` (the B-LTA document timestamp's `hash`, `field` and `reserved`) and `appearance` (`page`, `rect`, `ink` strokes, `text`). A wrong password fails with `incorrect password`. `NexPdfJni.pkcs12InfoJson(p12, password)` shows the certificate. For tests, `NexPdfJni.signPades(handle, signer, reason, location)` signs with a new self-signed certificate. ## Sign with an HSM, smart card or cloud key [#sign-with-an-hsm-smart-card-or-cloud-key] External signing works in three calls with no state kept between them: ```kotlin val cert = certPem // signer certificate (PEM or DER), then its chain val prepared = NexPdfDocument.openBytes(contract).use { doc -> doc.prepareExternalSignature(cert, """{"reason":"Approved"}""") } val toSign = NexPdfDocument.externalSignatureData(prepared, cert) val signature = myHsm.signSha256Rsa(toSign) // your device or KMS val signed = NexPdfDocument.completeExternalSignature(prepared, cert, signature, 0, null) check(signed.isNotEmpty()) { NexPdfJni.lastError() } ``` The same three calls are `NexPdfJni.prepareExternalSignature(handle, cert, optionsJson)`, `NexPdfJni.externalSignatureData` and `NexPdfJni.completeExternalSignature`. The algorithm is `0` for RSA PKCS#1 v1.5 with SHA-256 or `1` for ECDSA with SHA-256 (DER or raw `r||s`). Devices that take a digest sign the SHA-256 of `toSign`. The last argument takes `{"tsa_url": "...", "ltv": true}` and also `"level"`, so an external signature can be B-LTA too. ## Long-term validation [#long-term-validation] `NexPdfJni.addLtv(signedBytes)` adds the OCSP responses and CRLs (a DSS) to a signed file so the signature can be validated after the certificates expire: ```kotlin val ltv = NexPdfJni.addLtv(signed) ``` ## Verify signatures [#verify-signatures] ```kotlin val sigs = JSONArray(NexPdfJni.verifySignaturesJson(signed)) for (i in 0 until sigs.length()) { val s = sigs.getJSONObject(i) val ok = s.optBoolean("digest_ok") && s.optBoolean("signature_ok") Log.i("NexPDF", "${s.optString("signer")} ${s.optString("level")} ${if (ok) "valid" else "INVALID"}") } val report = NexPdfJni.verifySignaturesWithRootsJson(signed, rootsPem) // JSON text ``` Each entry includes `field`, `signer`, `subject`, `digest_ok`, `signature_ok`, `covers_whole_document`, `reason`, `signing_time`, `timestamp_ok`, `chain_ok`, `trusted`, `revocation`, `ltv`, `level`, `pades_level` (`B-B`, `B-T`, `B-LT` or `B-LTA`) and `document_timestamp` (`true` for a document timestamp, whose `signer` is the timestamp authority). ## Long-term archival [#long-term-archival] For PAdES B-LTA, document timestamps and archive timestamp renewal, see [Long-term signatures](/docs/android/guides/long-term-signatures). ## Handwritten signatures [#handwritten-signatures] A drawn signature without cryptography is an ink annotation: `NexPdfJni.addInkSignature(handle, page, color, width, strokes)`. See [Annotations](/docs/android/guides/annotations). The [reader](/docs/android/reader) has a signature pad. # PDF/A and PDF/UA (/docs/android/guides/standards) PDF/A, PDF/X and PDF/UA need the `standards` module (Enterprise tier). ## PDF/A for archiving [#pdfa-for-archiving] `NexPdfJni.convertPdfA(handle)` converts the document to PDF/A (ISO 19005): it writes the XMP metadata with the PDF/A identification, adds an sRGB output intent with an embedded ICC profile and a file identifier, and embeds metric-compatible Liberation fonts in place of non-embedded standard fonts. ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni NexPdfDocument.openBytes(invoiceBytes).use { doc -> check(NexPdfJni.convertPdfA(doc.handle())) { NexPdfJni.lastError() } val pdfa = doc.saveBytes() } ``` `convertPdfA` writes PDF/A-2b. To convert to another level (1a to 4f) and check the result, use `convertPdfaLevel(level)` and `validatePdfaJson(level)`; see [PDF/A and PDF/UA validation](/docs/android/guides/conformance). ## PDF/X for print [#pdfx-for-print] ```kotlin check(NexPdfJni.convertPdfX(doc.handle())) { NexPdfJni.lastError() } val printReady = doc.saveBytes() ``` ## PDF/UA accessibility tagging [#pdfua-accessibility-tagging] `NexPdfJni.autoTag(handle, lang, force)` builds a logical structure tree from the page content of an untagged document: text becomes headings (`H1`, `H2`) and paragraphs in reading order, images become `Figure` elements with placeholder alternative text, annotations become `Link`, `Form` or `Annot` elements, and vector graphics become artifacts. It also sets the language, the title, `/MarkInfo`, the tab order and the PDF/UA identification. It returns a JSON report. ```kotlin val report = JSONObject(NexPdfJni.autoTag(doc.handle(), "en-US", false)) // true re-tags a tagged file Log.i("NexPDF", "${report.getInt("headings")} ${report.getInt("paragraphs")} ${report.getInt("figures")} ${report.getJSONArray("warnings")}") val accessible = doc.saveBytes() ``` The report counts `pages`, `headings`, `paragraphs`, `figures`, `annotations` and `artifacts`, says whether the file was `already_tagged`, and lists `warnings` that need a person, such as figures that need real alternative text. `lang` is a BCP 47 tag such as `pt-PT` or `en-US` (`null` uses `en-US`). Check the result with `validatePdfuaJson()`. Conversion to PDF/UA-1 or PDF/UA-2 in one call, with a report, is the engine's `convert_pdfua_json`, reached through `NexPdfJni.invoke`; see [PDF/A and PDF/UA validation](/docs/android/guides/conformance). # Structured extraction (/docs/android/guides/structured-extraction) Structured extraction needs the `conversion` module (Startup tier and above). Everything on this page runs offline and gives the same result every time. For schema extraction and classification, NexPDF builds the prompt and checks the answer; **the engine never calls a network service**, so you choose and call the language model yourself. Each call returns JSON text, or an empty string on failure with the reason in `NexPdfJni.lastError()`. The `NexPdfDocument` methods below are also `NexPdfJni` methods that take `doc.handle()` first. ## Tables [#tables] `extractTablesJson(pageIndex, optionsJson)` finds ruled tables (from the page's lines and rectangles, with merged cells) and unruled tables (from column-aligned words). Pass `-1` for every page. ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni import org.json.JSONObject NexPdfDocument.openBytes(statement).use { doc -> val tables = JSONObject(doc.extractTablesJson(-1, null)).getJSONArray("tables") for (i in 0 until tables.length()) { val t = tables.getJSONObject(i) Log.i("NexPDF", "${t.getInt("page")} ${t.getString("kind")} ${t.getInt("n_rows")} x ${t.getInt("n_cols")}") Log.i("NexPDF", t.getString("markdown")) val firstRow = t.getJSONArray("rows").getJSONArray(0) val firstCell = firstRow.getJSONObject(0).getString("text") } } ``` Each table has `page`, `bbox`, `kind` (`ruled` or `unruled`), `n_rows`, `n_cols`, `header_rows`, `rows` (cells with `text`, `bbox`, `row`, `col`, `row_span`, `col_span`), and the table as `csv` and `markdown`. Options: `{"ruled":true,"unruled":true,"min_unruled_lines":3}`. ## Key-value pairs and entities [#key-value-pairs-and-entities] `extractKeyValuesJson(optionsJson)` reads label/value pairs from the layout (`Invoice no.: 123`, a label above its value, labelled cells) and typed entities: dates, amounts with currency, IBANs, e-mail addresses, phone numbers and VAT numbers, with normalised values. ```kotlin val kv = JSONObject(doc.extractKeyValuesJson("""{"date_order":"dmy"}""")) val pairs = kv.getJSONArray("pairs") for (i in 0 until pairs.length()) { val p = pairs.getJSONObject(i) Log.i("NexPDF", "${p.getString("key")} = ${p.opt("value")} ${p.getString("type")} ${p.opt("normalized")}") } val entities = kv.getJSONArray("entities") for (i in 0 until entities.length()) { val e = entities.getJSONObject(i) Log.i("NexPDF", "${e.getString("type")} ${e.getString("text")} ${e.opt("normalized")}") } ``` Options: `pages` (0-based indices) and `date_order` (`dmy` or `mdy`) for ambiguous dates. ## Schema extraction with your language model [#schema-extraction-with-your-language-model] 1. `extractionPromptJson(schemaJson, optionsJson)` builds a prompt from the page text in reading order, the tables as Markdown and the detected key-values. 2. Send `system` and `prompt` to the model of your choice. 3. `extractionValidateJson(schemaJson, answer)` checks and coerces the answer against the schema and finds each value on the pages. ```kotlin val schema = """{"invoice_number":"string","date":"date","total":"number", "items":[{"description":"string","amount":"number"}]}""" val p = JSONObject(doc.extractionPromptJson(schema, null)) val answer = myLlm(p.getString("system"), p.getString("prompt"), p.getJSONObject("response_schema")) // your call val result = JSONObject(doc.extractionValidateJson(schema, answer)) if (result.getBoolean("valid")) { Log.i("NexPDF", "total ${result.getJSONObject("value").opt("total")}") } val fields = result.getJSONArray("fields") for (i in 0 until fields.length()) { val f = fields.getJSONObject(i) Log.i("NexPDF", "${f.getString("path")} ${f.opt("value")} ${if (f.getBoolean("found")) "found on page ${f.opt("page")}" else "not found"}") } val errors = result.getJSONArray("errors") for (i in 0 until errors.length()) { val e = errors.getJSONObject(i) Log.w("NexPDF", "${e.getString("path")}: ${e.getString("message")}") } ``` The schema is a JSON Schema or the shorthand above (`"string"`, `"number"`, `"date"`, arrays of objects). The prompt result also has `pages`, `chars` and `truncated`. Prompt options: `max_chars` (default 60000), `pages`, `tables`, `key_values` and `instructions`. The answer may be plain JSON, fenced JSON or JSON inside prose. The report has `valid`, the coerced `value`, `errors` and `warnings`, and `fields` with `path`, `value`, `found`, `page`, `bbox` and `match` (`exact` or `normalized`). To validate an answer without a document, call `NexPdfJni.extractionValidateJson(0, schemaJson, answer)`: handle `0` skips the grounding on pages. ## Classification [#classification] `classifyJson(labelsJson)` (`NexPdfJni.classifyDocumentJson(handle, labelsJson)`) picks one of your labels from keywords. Known labels such as `invoice` and `contract` have built-in keywords; others take `keywords` and a `description`. ```kotlin val c = JSONObject(doc.classifyJson( """["invoice","contract",{"label":"payslip","keywords":["gross pay","net pay"]}]""")) Log.i("NexPDF", "label: ${if (c.isNull("label")) "none" else c.getString("label")}") // null when nothing matched val scores = c.getJSONArray("scores") for (i in 0 until scores.length()) { val s = scores.getJSONObject(i) Log.i("NexPDF", "${s.getString("label")} ${s.getDouble("score")} ${s.getDouble("confidence")} ${s.get("matched")}") } ``` The result also holds `system`, `prompt` and `response_schema`, ready for a language model when you want it to decide. # Templates (/docs/android/guides/templates) Templates need the `conversion` module (Startup tier and above). A template is a Word document, an HTML page or a PDF with placeholders such as `{{customer.name}}`. NexPDF fills it from a JSON object and gives you a PDF (or, for Word, a filled `.docx`). The three kinds share one syntax. ## Word templates [#word-templates] ```kotlin import com.nexdevit.nexpdf.NexPdfDocument import com.nexdevit.nexpdf.NexPdfJni import org.json.JSONArray import org.json.JSONObject val data = JSONObject() .put("number", "2026-114") .put("customer", JSONObject().put("name", "Ana Silva")) .put("due", "2026-12-31") .put("items", JSONArray() .put(JSONObject().put("description", "Consulting").put("qty", 4).put("price", 120)) .put(JSONObject().put("description", "Travel").put("qty", 1).put("price", 85.5))) .put("total", 565.5) .put("paid", false) val template = assets.open("invoice.docx").use { it.readBytes() } NexPdfDocument.fromDocxTemplate(template, data.toString(), """{"locale":"pt-PT"}""").use { doc -> File(filesDir, "invoice-2026-114.pdf").writeBytes(doc.saveBytes()) } val filledDocx = NexPdfDocument.fillDocxTemplate(template, data.toString()) // keep it as Word check(filledDocx.isNotEmpty()) { NexPdfJni.lastError() } ``` Placeholders work even when Word splits them over several runs. A table row that holds an `{{#each items}}` tag is repeated once per item, and a paragraph that holds only a block tag disappears from the output. Headers, footers, footnotes and endnotes are filled too. Filling a `.docx` with the `strict` and `locale` options is the engine's `template_docx_fill_with(template, data_json, options_json)`. `NexPdfJni` has no typed method for it: call it through `NexPdfJni.invoke` (`{"fn":"template_docx_fill_with","args":[