Files
pdfcraft/crates/automation
Hamza Naveedandskylar taylor-barrick 97cef90e01 Redaction: a pattern nothing paints with any more leaves the page (#3680)
* Redaction: a pattern nothing paints with any more leaves the page

A tiling pattern's cell is a content stream of its own and can draw
anything, text included. Redacting a shape filled with such a pattern
removed the fill from the page's content -- the page looked right, a
black box -- but left the pattern in /Resources /Pattern, and its cell,
with the text that was under the mark, was written into the saved file
unchanged.

The pass does not enter pattern cells, so it cannot redact inside one.
What it can do is notice that nothing paints with the pattern any more.
The graphics state now carries the fill and stroke pattern a `scn` or
`SCN` selected (and `cs`, `g`, `rg`, `k` and their stroke forms clear
it), every painting operator that survives the rewrite records the
pattern it drew with, and a pattern the page selected but no surviving
paint used leaves the page's resources.

Measured on the report's file:

    before   applied: 1, (SECRET) in the saved bytes
    after    applied: 1, no /Pattern on the page, (SECRET) gone

A pattern some surviving paint still uses is kept, and so is its cell:
with two boxes filled from one pattern and only the first marked,
patterns_removed is 0 and the resources keep the entry -- the second box
still shows the word, so it is not a leak.

Report gains patterns_removed.

Fixes #3647.

* Keep a pattern every operator that can paint with it still uses

Two defects CodeRabbit found in the first version of this change, both
of which could remove a pattern the page still draws with.

Pattern use was recorded for path painting only. Text shows with the
fill pattern too -- and with the stroke pattern in the stroking render
modes -- as do image masks and anything a form draws, and a form's
content is interpreted with a graphics state of its own, so a pattern it
inherits is never seen inside it. Content like

    /Pattern cs /P0 scn 20 140 100 30 re f BT (KEEP) Tj ET

with the box redacted therefore lost the fill of text still on the page.
Every operator that can paint with the current pattern now records it:
text (except mode 3, which paints nothing, and mode 7, which only
clips), inline images, and image or form XObjects. Only path painting
knows exactly what it drew and whether the paint survived, so the others
are recorded as they are met. That can keep a pattern whose paint was in
fact all redacted, which costs an unused resource entry, while dropping
one something still draws with takes paint off the page.

/Resources /Pattern may be an indirect object, like any value. Reading
the reference itself as a dictionary found none and pruned nothing, so
on such a file the cell -- with the text that was under the mark --
stayed in the saved bytes, which is the leak this change is for. It is
resolved now, and what is written back is a dictionary of this page's
own, so pruning never reaches through a /Pattern dictionary another page
shares.

The controls in the test: without the first fix the surviving text's
pattern is removed (left: 1, right: 0), and without the second the
indirect file prunes nothing (left: 0, right: 1).

* M8: refuse retained unsafe tiling patterns

* M8: guard shared appearances and narrow pattern scans

* M8: update TLS dependencies for new advisories

* Redaction: the comment on prune_patterns said more than the code does

`prune_patterns` drops the `/Pattern` resource entry; the `scn` that selected
it stays in the content, so the page names a pattern its resources no longer
hold. The comment claimed the selector went too (noted in review).

ISO 32000-1 8.6.6.2 makes that operand a key of the `/Pattern` subdictionary,
so the open question is whether a reader stops reading the stream at the stale
name. `a_page_whose_pruned_pattern_is_still_selected_renders` answers it with
the renderer rather than with prose: the redacted page is saved, reopened and
rasterized, and

* it renders with no error and the same 300x300 page box,
* the text written *after* the stale selector is still painted -- which is
  exactly what a reader would drop if it gave up at the bad operand,
* the redaction overlay is black over the box the pattern filled.

Control: with the drawing after the selector removed, the pixel assertion fails
("the text after the stale selector is still painted"), so it is reading that
text and not a stray pixel.

The selector is left in place rather than cut out: removing operators is a
rewrite of the content this pass does not otherwise do, and nothing surviving
paints with that colour. `pdfcraft-render` is a dev dependency of this crate
only -- layer 4 on layer 3, which the layering allows.

* WIP: pattern guard depth bound sized from the interpreter's

* Pattern tests: keep the guard's cases reaching the guard now a hit path is removed whole

* Pattern automation tests: keep the pattern in use where they test the guard, since a hit path is now removed whole

* Redaction: a form without resources keeps the page pattern it still paints

A form with no /Resources of its own paints with its caller's patterns, but
its surviving pattern paint was recorded only in the form's own output and
never reached the page. With the page's own fill under the mark removed
whole, prune_patterns then dropped /P0 from the page while the form outside
the mark still painted with it, so that fill lost its paint in the saved file.

Pass the painted names up from a form that inherits its caller's resources.
Only the painted side goes up, so this can keep a pattern, never prune one.

* Redaction: a pruned pattern does not stay named by the page tree

prune_patterns writes only the page's own /Resources, and the guard walked
only pages' effective resources. A /Pages node that still named the pruned
pattern kept its cell reachable from Root, so a full save wrote the cell,
text included, while apply returned Ok. Three shapes did it: a page with no
/Parent inheriting from the root, a /Parent that disagrees with the /Kids
tree, and a root /Resources shadowed by a nearer holder that was retired.

Patterns pruned from a page are now unlinked from page-tree holders no page
inherits from, as unlink_doomed does for XObjects, when every /Parent agrees
with the tree. Whenever a pattern was pruned (or a selected page had any),
the guard also inspects the /Resources of every /Pages node Root reaches
down /Kids and up each page's /Parent chain, so whatever stays reachable is
proven safe or the redaction is refused, leaving the document unchanged.

* Redaction: a Type 3 glyph without resources keeps the page pattern it paints

A Type 3 font with no /Resources looks the names in its glyph descriptions
up in the resources of the page or form showing it, so a glyph outside the
mark can paint with the page's pattern. Text recorded only the fill and
stroke pattern of the graphics state, so with the page's own fill under the
mark removed whole, prune_patterns dropped the pattern and the glyph lost its
paint. Showing such a font now keeps every pattern of the scope, as a form
without /Resources keeps what it paints.

* Redaction: say what text-recorded pattern use keeps

Text, inline images and XObjects record their pattern before the hit test,
so a pattern painted only by redacted text keeps its cell. The guard refuses
a cell with text or images; a vector-only cell stays in the file. The comment
said this cost only an unused resource entry. Pin the behaviour in a test.

* Redaction: the page tree is followed up every /Parent link

A full save writes every node a /Parent link reaches, but the guard followed
/Parent only from pages and stopped at the first node it had already seen,
and unlinking never followed it. A /Pages node reached only through the
/Parent of a /Kids node -- a root /Pages with a /Parent, or an intermediate
node whose /Parent leads out of the tree -- kept naming the pruned pattern,
and its cell, text included, stayed in the saved file while apply returned
Ok.

The guard now follows /Parent from every node it visits, page or /Pages, with
the same seen-set against cycles. Unlinking treats a root with a /Parent as an
inconsistent tree, like a disagreeing link, and leaves the decision to the
guard, which inspects every node those links reach and refuses an unsafe
cell.

* Redaction: a long page tree does not exhaust the pattern guard's budget

The page-tree walk counted every node, pages included, against the guard's
16,384-object budget, so redacting a pattern page of a 17,000-page document
was refused with a limit error where it had applied before. Only the holder
nodes the guard inspects count against that budget now; the walk itself is
bounded at a million nodes, as unlink_doomed bounds the same tree.

* Redaction: a Type 3 font set by an ExtGState or shown in a form keeps the page patterns

The resourceless Type 3 check covered only a font set by Tf in the scope that
paints. A Type 3 font without /Resources set through an ExtGState /Font entry
was not flagged, and a glyph shown inside a form with /Resources of its own
recorded its patterns in the form's scope, which the page never saw. In both
cases the page's own fill under the mark was removed whole, prune_patterns
dropped the pattern, and the glyph outside the mark lost its paint.

An ExtGState font is now checked the same way, and a glyph shown in any
nested form marks the page as keeping every pattern it selected. This can
only keep patterns; whatever is kept is checked by the guard.

* Redaction: a pruned pattern a full save would still write is proven safe or refused

The walks that check retained pattern cells follow the references they know
-- resource categories, the page tree, appearances -- but a full save writes
whatever the trailer reaches by any reference. A direct /Parent dictionary, a
/Kids array on a page, or a stray resource entry (/Shading naming the pattern
stream) kept a pruned cell, text included, in the saved file while apply
returned Ok.

pdfcraft_cos gains reachable_objects, which runs the same breadth-first walk
write_full uses (factored out as full_save_order, so the two cannot drift).
Before apply succeeds, every pruned pattern that walk still reaches is
inspected like a retained cell: vector-only passes, anything else refuses
with the existing pattern error. It runs only when a pattern was pruned and
costs one walk of the reachable objects.

* Redaction: a direct /Parent dictionary is part of the page tree too

A /Parent given as a dictionary rather than a reference is written inline by
a full save, but the page-tree walk followed /Parent only as a reference, and
unlinking took such a tree for consistent. A root /Pages whose direct /Parent
held /Resources naming the pruned pattern kept its cell in the saved file.

The guard now walks a direct /Parent like any node (its /Resources, /Parent
and /Kids), and unlinking counts any /Parent that is not the reference /Kids
came from as an inconsistent tree, leaving the decision to the guard.

* Redaction: page-tree walks queue each node once and borrow /Kids

On a hostile tree whose /Pages nodes share one long /Kids array, the guard's
page-tree walk and pattern unlinking pushed every /Kids entry of every node
before checking whether it had been seen, and copied the array on each
visit. Both now queue only nodes not seen yet and read /Kids in place;
unlinking also stops at the first node reached twice, since its /Parent can
agree with at most one of the nodes above it, and leaves that tree to the
guard.

* Redaction: a Type 3 font with /Resources null is resourceless too

/Resources null is the same as no /Resources, but the check counted any
entry, so such a font's glyph outside the mark lost the page pattern it
painted with. A Type 3 glyph shown by a kept annotation appearance is a known
limit, pinned as an ignored test: appearances are not interpreted for pattern
use, and under ISO 32000 the glyph resolves in the appearance's own resources.

* Redaction: a pruned pattern is recorded along its whole reference chain

A pattern name can lead to a reference-valued object whose value is the cell
(/P0 7 0 R, object 7 being 6 0 R). Pruning recorded only object 7, so the
reachability backstop checked an object nothing reached while a stray
reference kept the cell, object 6, in the saved file. Every object along the
chain is recorded now, bounded like the other walks.

* Pattern tests: pin the file identifier where two saves are compared

main now gives a redacted rewrite a new identifier from fresh entropy, so an
incremental and a full save after Apply differ in /ID alone. The test that
checks they are the same save passes fixed entropy to both.

* Redaction: replies and pop-ups removed on other pages feed the shared-appearance check

Apply checks every page for retained unsafe pattern cells when a removed
annotation's appearance is shared with one that stays on an unselected page.
Only annotations removed under a mark fed that check. Replies and pop-ups
that go with them in step 2b (removed_everywhere), often listed on another
page, did not, so a text-bearing cell in an appearance a kept annotation
shares with them escaped the all-pages check and Apply returned Ok.

Their appearance references now go into removed_appearances too, with the
same limit. Raised by FredApps' review of the rebase.

---------

Co-authored-by: skylar taylor-barrick <hi@skylar.cc>
2026-11-06 10:01:42 +01: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.

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).