Files
pdfcraft/crates/automation
Chiranjeevi U adbf1dc01f M9: signed appearances show their real validation state (#79) (#2808)
* M9: redraw named-layer signature status layers

- /N drawing one Form that holds n1 and n3: n1, n3 and n4 redrawn for the state
- copies made once per original and state; originals never edited
- Lucide icons; captions in Helvetica, embedded Inter, or craft-fonts outlines

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: draw signature states in the display copy, exports and print

- marks follow the bytes shown; a changed verdict redraws after a metadata edit
- background opens pick up the trust and captions current at commit

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: status captions in the interface language

- the three captions in all 22 catalogues
- Signatures panel colours from sign::status_rgb

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: signature badge in the widget's corner

- a quarter of the shorter side, 48pt cap; outline only under 32pt
- dropped for a drawn valid state; bottom-right where the appearance draws one
- sign_list reports verdict_shown; parity and roadmap

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: keep Arabic signature captions in logical order

Pass raw RTL catalogue text to the signature appearance shaper so UAX #9 is applied exactly once. This keeps the rendered word order and exported /ActualText consistent.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M2: read /ActualText over painted paths and pictures

- A replacement that marks no glyph reads where it paints, cut to what is visible and along the way it is drawn.
- A span the page content leaves open ends before the annotations.
- OCR and scan field detection still count such a page as having no text of its own.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M8: redaction strips /ActualText around paint it clips

- A path or shading written again under a clip counts as changed, so a partly redacted word drawn as outlines leaves no name in the file.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: recognise only layer forms that draw n1 and n3

- Settle on the one form holding both first, then read its content once per call.
- Skip an /N that is its own layer form; copies keep the layer's /OC.
- A verdict counts as drawn when any visible widget shows it.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: keep the signature badge and redraw wherever a state changes

- The badge stays for every state; its mark sits bottom-right as the widget lies on the page.
- An edit that changes a verdict redraws every page; captions apply before startup files open.
- Print, the CLI's render and the repair log follow the display copy.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: restore the attribution usage the rebase dropped

- Usage lines for the three icons, Inter and the craft-fonts input; ATTRIBUTION.md rebuilt from them.
- Roadmap and localization notes for this round.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: pin signature field names on a nested form

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: bound the signature field walk

- kids share their parent's name and type instead of each copying them
- a widget stays listed under every field that claims it, as one shared copy
- a field written in place in a shared /Kids array is walked once
- caps of 20,000 fields, 100,000 entries and 4096-byte names; no states drawn past them

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: keep a document signed when the field walk stops early

- list_cached adds a signed row of unknown validity for the fields the walk didn't read
- Save As and actions then append, and Optimize, Sanitize and full rewrites are refused, as for any signed file

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M8: removing hidden content no longer strips the names of shadings

- With no regions to clip, a shading is left alone instead of wrapped and marked clipped
- clean_replacements skips scopes already marked, so deep nesting stays linear

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M2: read a picture's /ActualText over the whole picture

- draw_image's transform maps pixels, not a unit square, so the text sat on one pixel in the corner; the test now draws a 2x2 picture
- Painted grows in place instead of being copied through an Option

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: cap the bytes of names the signature field walk keeps

- A kid's name repeats its parent's, so one long name over 20,000 kids came to 80 MB; the walk now stops at 4 MiB of names and counts the rest as unread
- Cover the widget written into a shared /Kids array and the field cap among kids, which no test caught
- sig_fields is private again, and the cap docs say what happens past each cap

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: skip status-layer work that changes nothing; fix tests that could not fail

- show_status_layers and has_status_layers return before reading the form when nothing is signed, so an unsigned form no longer walks every field on each edit
- revalidate and draw_captions leave documents with no drawn state alone, and no longer copy the signature list to update it
- Scan form detection reads the page's text once; comment and badge tips share one hover rule
- Tests: drop a table row that repeated another, stop taking an expectation from the code under test, stop comparing an Arc with itself, give bare asserts messages

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: test the signature field name cap at the engine boundary

- A 4,096-byte name is read and blocks a full rewrite; at 4,097 bytes the list holds the unread-fields row and a full rewrite is still refused

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: test signature states beside fields the viewer draws

- One display copy holds both a field's drawn appearance and the signature's state.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: draw Thai and Devanagari status captions in their own script

- script_of names Thai and Devanagari, so a craft-fonts face meant for either draws the caption as outlines; without one it stays English.
- Localization, parity and the craft-fonts usage line list the new scripts.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M2: paint left out by an exclusion mixes its /ActualText replacement

- A replacement placed by outlines or pictures, some of them excluded, fails filtered extraction as one with excluded glyphs does.
- Glyphs still place a replacement that has them.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: a long-named field that can't hold a signature leaves the walk whole

- A leaf of another type passed over for its name is no signature field and has none below it, so an unsigned form stays unsigned.
- A signature field, or any field with kids, still counts as unread.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: status captions use document faces only

- Each script takes the face PdfCraft writes it into documents with, so Chinese stays English although the pinned craft-fonts' interface-only Chinese face is meant for Hani.
- The craft-fonts usage line names Devanagari: the pinned revision has a face for it, and Hindi captions are drawn in it.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: refuse a new signature field the field walk can't read back

- Signing adds a field only when the walk reads the whole form with it: past a cap the signature would be listed as unread fields, and its name could repeat an unread field's.
- A field the walk already reads is signed as before.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: refuse a new signature field with a blank name

- The walk lists no field without a name, so signing now also requires the walk to list the new field: one named only with spaces or NULs would be a signature nothing shows.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: an unnamed signed field or an unreadable form counts as unread

- A signed field with no usable /T, or an /AcroForm or /Fields of the wrong type, cuts the field walk short: the document keeps its unread-fields row and stays signed.
- Signing refuses a blank new field name before it adds the field, so the refusal still says why.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: no display copy when no signature state is drawn

- display_bytes_for makes a copy only when it added an appearance or drew a state, as the app does.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: the verdict mark stays on the page

- A widget past the crop box takes its mark in the part on the page, or none when too little of it is there.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: typed values stay drawn while a signature redraws every page

- A form edit that changes a signature's state puts its values back in unbaked after the pages are invalidated.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: the action, Save As and shading tests check their effects

- The signed action and Save As tests reopen the output for the title and the comment; the shading test checks its clip.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: values typed earlier stay drawn while a signature redraws every page

- A form edit that changes a signature's state keeps every value still waiting on its page, not only its own.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: comment and content edits keep typed values drawn too

- An edit to one page's comments or content that changes a signature's state moves no page, so the values still waiting on their pages stay pending, as after a form edit.
- The pending-value test runs a field deletion and a comment after a fill, under a certification that allows the fill; its messages say what it checks.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: the language-change test skips without catalogs

- Like the other language tests, it returns early when the build has no craft-i18n catalogs.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

* M9: signed fields behind kids without a name count

- A kid with no /T but kids of its own is walked as a field node, so a signed field under it is listed by its full name.
- An unnamed kid claiming a signature its field doesn't have cuts the walk short, so the document stays signed and keeps its unread-fields row.

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>

---------

Signed-off-by: Chiranjeevi U <244287281+chiranjeevi-max@users.noreply.github.com>
2026-11-07 20:37:17 -06:00
..

pdfcraft-automation

Agent control for PdfCraft: a headless tool table over the engine, and an opt-in MCP server.

  • Layer: L7 (architecture §13), but headless. It depends on engine, render and organize, never on a UI toolkit.
  • Status: over a hundred tools; pdfcraft-cli tools lists the current set with their schemas (the count isn't repeated here, so it can't go stale). They cover inspection, rendering, text, page edits and organizing, page labels, bookmarks, comments and their review, form filling and authoring (fields, properties, scripts, data exchange, detection), redaction and sanitizing, password protection and signatures, calibrated 2D measurements and CSV export, adding text, images, links and stamps, optimizing, OCR, printing, export, metadata, undo/redo, save, combine, extract and split. Comment tools take geometry in the same top-left-origin points as everything else, and comment_add can mark text by searching for it (find). The MCP server also serves the open documents as resources, page images included. The running app's UI is driven separately, through the ui.* control channel in pdfcraft-ui-egui.

fill_sign_add text accepts line breaks, including blank lines. Its typewriter box grows to hold all wrapped rows, and saving/reopening preserves the contents and appearance.

API

let mut a = Automation::new().with_root("/work")?;      // optional: confine all paths
let doc = a.call("doc_open", &json!({ "path": "in.pdf" }))?;   // Vec<Content>
a.write_output("page1.png", &png)?;                      // save a result yourself, under the same root rules
tools() -> Vec<ToolDef>                                  // name, title, description, input_schema, read_only, destructive, command
mcp::McpServer::new(a).serve(stdin, stdout)?             // newline-delimited JSON-RPC 2.0

content_update.rotate rotates an added image counter-clockwise by an integer multiple of 90 degrees. Large positive and negative signed 64-bit angles are normalized before combining them with the image's current orientation. Full turns retain its appearance, rectangle, crop and flips. Angles that are not multiples of 90 are refused without changing the document or its undo/redo history.

page_add_text, content_update and text_edit take per-line aligns. An "inherit" entry follows the box-level align; legacy null entries remain accepted with the same meaning.

page_add_text and content_update take one of color (#RRGGBB or a name, painted in DeviceRGB), gray (0 black to 1 white, DeviceGray g) and cmyk ([c, m, y, k], each 0 to 1, DeviceCMYK k), so text added to a print file can be 100 K black. content_list reports gray or cmyk for such text.

Content is Json(Value) or Png { data, width, height }. Errors are UnknownTool, InvalidArgs (the call didn't match the schema) or Failed (a readable message for the agent).

Conventions

  • Tool names are snake_case (page_rotate): MCP clients reject dots. ToolDef::command links a tool to the registry id it automates (page.rotate), and command_list reports the link.
  • Pages and positions are 1-based. Rectangles are PDF points with the origin at the top-left of the displayed page.
  • Unknown arguments are rejected, so typos fail loudly.
  • Tools that change a document return its summary (doc, pages, dirty, undo, redo, …).
  • comment_image_preview returns JSON and a PNG: layer: "background" (the default) gives the page without the selected image signature/initials; layer: "image" gives its embedded image with alpha. The metadata supplies its displayed rectangle, document rotation, image_rotation (how far clockwise the image is shown turned: 0 for one placed by PdfCraft, which keeps it upright as displayed) and annotation opacity. Each result can be saved with the CLI's --out. Cache the background and transform the image for live movement/resizing; comment_edit commits the final geometry in one undo step. Previewing never changes the document.
  • For proportional image signature resizing, use the embedded image layer's width/height ratio rather than a previously stretched annotation rectangle. The GUI preserves this ratio at corners with the opposite corner anchored; edge midpoint handles change only their own axis. comment_edit accepts the resulting rectangle.
  • doc_close refuses to drop unsaved changes unless discard_changes: true. doc_save writes atomically, incrementally in place, and in full for a new path. Atomic output writes call sync_all on the staging file before replacing the destination. A write or sync error leaves the destination intact, removes staging and leaves the document dirty for retry. A filesystem that does not support syncing returns an error; there is no unsynced fallback. This flushes file contents, but does not guarantee persistence of the parent-directory rename across power loss.
  • With a root set, every read and write path must resolve inside it (symlinks and .. included). Relative paths resolve inside the root, and .. is resolved by name before the check. Every path outside the root gets the same refusal (<path> is outside the allowed directory <root>), whether or not it exists, so a confined agent can't probe the rest of the disk; on Windows another network share or device path (\\host\share, \\?\UNC\…, \\.\…) is refused without being contacted. "Not found" and other filesystem errors are reported only for paths inside the root. Tools that write several files into a folder name them after the document or input file, with separators, colons and control characters replaced by _, so a name can't lead them out of the folder. The root itself must be a folder.
  • Automation::with_automation_roots holds a read folder and a write folder (pdfcraft-cli mcp --automation-read-root DIR --automation-write-root DIR, see docs/mcp.md). Reads must lie inside the read root and writes inside the write root, links followed. A root left out grants none of its access. Refusals read automation path rejected: outside the read root <root>: <path>. As with a root set, on Windows a path on another network share or device path is refused with that refusal without being contacted (#4003). It applies on top of with_root.

Text search and cache limits

text_word_count counts the current snapshot without filling the text cache. It returns totals and per-page Unicode word/character counts, with optional tagged-table, tagged-code and image/OCR exclusions. See word count for counting rules and limits.

Extracted page text is reused in a session-wide LRU cache: at most 64 MiB of estimated owned text storage and 4,096 pages, shared by all open documents. Accounting includes glyph-vector capacity, each glyph string's capacity, line indexes and word-break flags. Cache hits share the renderer result instead of copying glyphs. Oversized pages remain usable by the current call but are not cached; evicted pages can be extracted again. A changed document version invalidates its cached text on the next text request, and closing a document removes its entries. Cache entries do not keep an old PDF byte buffer alive.

This bounds retained text-cache data, not total process memory: active extraction batches, renderers, document buffers and the requested output have separate lifetimes. Search still reads growing batches (8 to 128 pages), with one lookahead match to determine continuation.

text_find keeps matches from readable pages when another reached page fails extraction. It returns warnings with 1-based page, error and error_truncated, plus warning_count and warnings_truncated. At most 100 warnings and 1,024 UTF-8 bytes per error are returned. Failures are retried on later calls; they are not cached as empty pages. Warnings describe pages visited in search order, up to the continuation point, not failures in unvisited later pages.

complete: true means the requested search was exhausted with no page failures and no further matches. next: {start_page, skip} exists only when another match would exceed limit. A search that reaches the end with warnings therefore has complete: false without next. Callers should follow next when present and separately inspect warnings. A capped search can return both. The existing query, count, matches and rectangle semantics are unchanged.

text_extract, comment placement and redaction keep strict all-requested-pages-must-succeed semantics; they never silently act on partial text.

Shared field properties

For an individual push button, form_set_props also edits its visible normal label:

{"doc": 1, "field": "clear_button", "caption": "Clear Form", "widget": 1}

widget is a 1-based index (default 1), used only with caption; an empty caption clears the label. Neither renames the field. form_fields returns the first widget's caption and all captions as [{"widget": 1, "caption": "Clear Form"}]. Other widgets and icon-only layouts keep their settings. CLI and MCP use the same edit, including undo/redo and save/reopen. The desktop exposes it as Button Properties → Options → Label. Rollover/down labels and icon layout are not edited here; the existing caption font and unsupported-character warning policy apply.

form_set_props accepts either field (one name) or fields (1–1000 unique names):

{"doc": 1, "fields": ["first_name", "last_name"], "required": true,
 "appearance": {"width": 3, "border": "#1473E6"}}

The batch is atomic and creates one undo step. A missing or locked field, invalid option, unknown argument or malformed appearance refuses the whole edit. Set locked: false to unlock and change fields together. Only supplied properties change: each field/widget keeps its other colours, fonts, values and unknown PDF dictionary keys. "none" removes a border or fill colour. Names, rectangles, rotations and captions require the single-field form. Results keep field for single edits and return fields for batches. CLI and MCP use the same tool.

MCP server

Opt-in only. Nothing starts it automatically, and it opens no port. It runs while pdfcraft-cli mcp [--root DIR] runs, normally launched by an agent from its MCP configuration. It stops when stdin closes. The CLI's mcp Cargo feature (on by default) compiles it out entirely when disabled.

pdfcraft-cli mcp --compact (or McpServer::with_compact(true)) keeps tools/list short for agents with small context budgets. It lists only the core tools (mcp::COMPACT_CORE_TOOLS: open, info, save, close, render, text extract and find, combine, split, undo) plus the common command/inspection/preview tools and two meta tools: tool_search (optional query and category, the name prefix; or name for one tool's full input_schema) and tool_call (name and arguments, run through the same Automation::call). tools/call by name keeps working for every tool, and the server instructions mention the meta tools. Without the flag nothing changes.

Implemented: initialize (protocol 2025-06-18, 2025-03-26, 2024-11-05), ping, tools/list (with readOnlyHint/destructiveHint annotations), tools/call (JSON results also returned as structuredContent; images as image/png), and resources/list, resources/templates/list and resources/read. The resources expose the open documents read-only: pdfcraft://doc/{doc}/info (JSON), …/text, …/page/{page}/text and …/page/{page}/image{?dpi} (PNG, 1–600 dpi). Tool failures come back as isError: true results, so the agent can read and recover from them.

From an installed release

The release packages ship pdfcraft-cli alongside the desktop app, so no build is needed:

Install CLI
Windows (MSI) %LOCALAPPDATA%\Programs\ArtCraft\PdfCraft\pdfcraft-cli.exe by default (C:\Program Files\ArtCraft\PdfCraft\pdfcraft-cli.exe for an all-users install, under Program Files (x86) instead for the 32-bit build, or wherever you installed it otherwise), not on PATH
Linux (deb, rpm) /usr/bin/pdfcraft-cli
macOS the separate pdfcraft-cli-<version>-macos-<arch>.zip release asset (the .app holds only the desktop app)
# Windows (PowerShell), default install folder
claude mcp add pdfcraft -- "$env:LOCALAPPDATA\Programs\ArtCraft\PdfCraft\pdfcraft-cli.exe" mcp --root <dir>
# Linux, or macOS with the CLI unzipped onto PATH
claude mcp add pdfcraft -- pdfcraft-cli mcp --root <dir>

Adding a tool

  1. Add the engine capability first, with its tests (the tool is a thin adapter).
  2. Add a ToolDef in src/tools.rs: a precise description, the schema, ro()/destructive(), and cmd() if a registry command exists.
  3. Handle it in Automation::call, validating pages and positions with the existing helpers.
  4. Add an end-to-end test in tests/it/automation.rs. tool_table_is_well_formed checks names, schemas and command links.

Moving several page objects

object_list {doc, page} inventories recognised paragraphs, Image/Form artwork and added items with generation-scoped kind/index references. object_move {doc, page, objects, offset, generation?} moves 1–1000 references atomically in displayed points (right/down), preserving source glyph bytes and fonts. A refusal changes nothing; success is one undo step. See the selection and movement guide for limits and examples.

Accessibility review record

Open the original and edited PDFs as separate documents, then call accessibility_review_record {before, after, path}. The tool writes a JSON record atomically within --root: SHA-256 hashes of both working PDFs, rule statuses and finding counts before and after, changed rules, and rules still failed or requiring manual review. all: true also includes the colour-contrast rule. It does not change either PDF or certify accessibility. Keep the original open while making edits to the second document so the comparison has a stable baseline.

Common command tools

Following FilmCraft's MCP conventions, command_list {doc?, filter?, enabled_only?} keeps its {commands: [...]} result and adds each mapped tool's parameter schema. command_run {id, params?} runs that command through its existing headless tool: include doc and other tool arguments in params. Commands without a headless mapping return a tool error. Unknown parameter keys are ignored with a warnings array; required values and paths still go through the original validation.

command_batch {steps: [{id, params?}], stop_on_error?} returns completed, failed, and per-step {ok, result?, error?} entries. The default is to stop at the first error; earlier edits remain. MCP marks a batch with any failed steps as isError, including through compact tool_call. doc_inspect {doc?} returns one document's info, or {documents: [...]} for all open documents. render_preview {doc?, page?, max_side?} returns a PNG (page defaults to 1, maximum side defaults to 1024, allowed 1–4096). Omit doc only when exactly one document is open.

All task tools remain available; compact mode includes the five common tools. Every MCP tool has all four annotation hints. Unknown top-level argument keys return JSON-RPC -32602 with the accepted keys; failures in the invoked tool remain isError results. An escaped tool panic is reported as an internal tool error, and the server continues serving.

Exports complete synchronously. progressToken and cancellation notifications are harmlessly ignored; no background-job or cancellation behavior is added.

Session resources pdfcraft://document and pdfcraft://commands, and the refusal of unknown argument keys, are described in docs/mcp.md.

For inline editor previews, page_render accepts hide_text_block (a 1-based index from text_paragraphs). It renders the page without that paragraph’s source glyphs and leaves the working document unchanged.

page_render.hide_added_text does the same for an added text item's 1-based index from content_list or object_list. It removes only that item in a read-only preview and is mutually exclusive with hide_text_block.

When the renderer reports a warning for the page, page_render and render_preview return a JSON part after the PNG, { "page": 1, "warnings": [...] }, with the sentences pdfcraft-cli render prints: "content past the page's safety budget was skipped" and "a colour that could not be computed was painted in a fallback colour". A page without warnings returns the PNG alone.

Existing text and document fonts

text_font_files discovers eligible installed files on request (or specified confined folders), text_font_import registers a full document face, and text_fonts lists source/full resources. Use text_edit.font_resource to choose a resource, or keep source faces and let matching full faces complete absent subset glyphs. text_edit.ranges accepts disjoint UTF-8 byte ranges; text_edit_layout measures the same resource/range draft without committing. All changes are undoable and survive saving/reopening. image_hit shares the UI's curve and hole hit testing. The bounds, limits and font requirements are in existing-text editing and image editing.

Superscript and subscript normalization

text_script changes characters to their Unicode superscript or subscript forms; it does not change the font size or baseline. For characters that have such forms, uniformly plain text toggles to the requested script, and uniformly scripted text toggles back to plain text. Characters without a matching form stay unchanged and do not determine the selection's state.

A selection mixing plain and target-script characters normalizes to the requested script. For example, subscript changes H₂2 to H₂₂, then to H22 on the next call; superscript changes Q²2 to Q²², then to Q22. A second toggle does not reconstruct the original mixture. Each call is one undoable text edit: edit_undo restores the exact prior text, including its original mixture. Save/reopen preserves the resulting normalized characters.

link_open {doc, page, index, password?} follows a local PDF link using link_list numbering. Relative file specifications open normally. An absolute file specification requires allow_absolute: true, after reviewing the target reported by link_list. Omitting the argument or passing false refuses the request before checking or reading the target file. This is an intentional compatibility change for callers that previously opened absolute GoToR targets without explicit consent. Opting in does not bypass --root, symlink confinement, regular-file, PDF-extension, size, or password validation. Consent applies only to that call, including each password retry; it is never remembered for other links.

The desktop UI asks Allow/Cancel before following absolute GoToR targets and displays the complete path. Relative links retain their existing behavior. Named destinations remain unapplied with a warning.

Folder batches

doc_batch runs conversion, OCR and compression over files and optionally recursive folders. The CLI also exposes it as pdfcraft-cli batch. See the batch guide for examples, output protection, errors and limits.

Editing button export values

Use form_set_props with field, export_value and optional widget (1-based, default 1) to change a checkbox or radio button export value. form_fields returns export_values in widget order. The selected/default appearance states are preserved; the operation is undoable and survives saving. Widgets sharing an appearance state keep one export value. Bulk edits are not supported for this widget-specific property. Empty values, Off, conflicting choices and values over 4096 UTF-8 bytes return an error.

Example: form_set_props doc=1 field=agree export_value=Accepted widget=1.

Rendering a 3D model

model_render draws a page's 3D model (a 3D annotation's PRC stream, directly or through a 3D reference) to a PNG, without the viewer. model picks the page's Nth 3D model (default 1); width and height are 1 to 4096 (default 512); direction is the view direction from the eye (default [-1, 1, -1], with Z up unless the view looks along Z); perspective defaults to true. The model is framed to fill the image and shaded by a headlight on white. U3D models are refused with an error, and the annotation's own views, lighting and render modes are not applied yet.

Viewer navigation history

A running PdfCraft instance launched with --control FILE exposes its per-tab history through pdfcraft-cli ui --control FILE command id=view.previous_view and pdfcraft-cli ui --control FILE command id=view.next_view. commands reports whether each action is enabled for the active document. These are the same actions as the rail buttons, View → Page navigation, and Ctrl+[ / Ctrl+] (⌘[ / ⌘] on macOS).

Explicit page jumps, including search-result selection and Next/Previous match, enter history when the page changes. Automatic search refresh, continuous scrolling, and within-page scroll movement do not. Existing page-step commands and single-page wheel turns retain their history behavior. Back/Forward returns to page tops, does not restore zoom, does not switch documents, and is not saved across restarts. Standalone engine/MCP sessions have no viewport, so they do not have a separate navigation-history tool; use the opt-in UI control channel to navigate the displayed document.

Fill & Sign text appearance

fill_sign_add accepts font_size (4–300 pt, default 10) and color (#RRGGBB, default black) for text and date. The colour is saved in the FreeText appearance and survives reopening. Other mark/signature types reject color; their appearance controls are separate.

Reviewing OCR headlessly

ocr_words {doc, retain_review: true} reads words without editing the document and returns review, plus pages and word boxes/confidences. Page and word positions are 1-based. region can restrict recognition to one named page, using displayed-page points. Without retain_review, word inspection remains stateless.

Apply reviewed text with ocr_review_apply {doc, review, corrections: [{page: 1, word: 1, text: "Corrected"}]}. Omitted words keep their text; empty text removes a word. Geometry comes from the retained recognition, never caller input. The captured document guard rejects stale/foreign results. Successful application consumes the handle and is one undoable step. Use output_mode: "editable", out: "reviewed.pdf" to write a separate editable document, or discard: true to release the result without applying it. Failed validation preserves the review for correction or discard. A new retained recognition replaces that document's prior handle; closing the document releases it. At most eight documents may retain reviews, with 65,536-word/4-MiB input bounds and a 65,536-page cap.

ocr_dictionary {path: "ocr-dictionary-en.txt", add: ["Quartz"], remove: ["old"]} atomically updates the same one-word-per-UTF-8-line format OCR Verify uses. Omit add/remove to read it. The explicit path honors --root, including symlink confinement; choose the appropriate per-language file used by the UI. Entries are case-insensitive and duplicate-free. Invalid or oversized inputs fail before writing (65,536 words, 4 MiB, at most 1,024 bytes per word).