* feat(preflight): report image resolution and bleed without rewriting the file * feat(preflight): report image resolution and bleed without rewriting the file * feat(preflight): report image resolution and bleed without rewriting the file * feat(preflight): report image resolution and bleed without rewriting the file * feat(preflight): report image resolution and bleed without rewriting the file * feat(preflight): report image resolution and bleed without rewriting the file * feat(preflight): report image resolution and bleed without rewriting the file * feat(preflight): report image resolution and bleed without rewriting the file * feat(preflight): report image resolution and bleed without rewriting the file * feat(preflight): report image resolution and bleed without rewriting the file * feat(preflight): report image resolution and bleed without rewriting the file * feat(preflight): report image resolution and bleed without rewriting the file * test upload session tests only * Include the print-readiness module from the OCR module so the crate compiles. * Record the one-line print-readiness patch so the dispatch can be restored exactly. * Restore the print-readiness dispatch from the original sources. * M3: select an image on the page and copy it (#1363) * M3: select an image on the page and copy it Select tool: a click on a raster image selects it (also one drawn through Form artwork, or with text over it such as an OCR layer); ⌘C copies it as a file in its original format (a JPEG as stored in the PDF, otherwise a lossless PNG). Right-click ▸ Copy Image copies its pixels at full resolution, and Copy Image in Original Format the file; Edit text & images has both for the selected image. Both respect the document's copy permission. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GWUuTDPKL5wivnSJuCkC8Q * M3: translate the copy-image strings into Czech, Kazakh, Slovene and Turkish Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GWUuTDPKL5wivnSJuCkC8Q * Copy image: keep the clipboard file in a private per-user folder Copy Image in Original Format wrote into the shared temporary folder (/tmp/pdfcraft-clipboard) and deleted everything in it first, so another user on the machine could plant a link or folder there and have PdfCraft delete or overwrite their target. The file now goes in PdfCraft's per-user cache folder (or the portable data folder), which is checked to be a real folder and set to 0700 on Unix (refused when it isn't ours). Only earlier copies (regular files named '<stem> p<N> img<M>.jpg|png') are removed, links are never followed, and the new file is created with create_new so it can't be redirected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tests: escape Windows paths in synthetic GoToR file specifications canonicalize() returns \\?\C:\... on Windows; unescaped backslashes in a PDF literal string become control characters, so link_open refused the target and main's Windows CI failed. Taken from #1359's helper fix. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Brandon Thomas <echelon@gmail.com> * fix(cli): edit refuses move/insert destinations past the end (#1330) (#1400) Co-authored-by: umesh429 <3474974+umesh429@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * fix(sign): refuse to sign a field whose /V is not a signature (#1328) (#1402) Follow-up to #1374. Signing an existing field refused a field whose /V is a signature dictionary and signed one whose /V is missing or null, but a /V that is neither (an empty string, a number, a name, an array) was treated as unsigned and overwritten with the new signature. Signing such a field by name now fails with "the value of the field ... is not a signature" and leaves the document as it is. A missing or null /V, direct or indirect, still signs, and a signed field is still refused as already signed. The signature list is unchanged: it still shows such a field as unsigned, since it carries no signature. Adds a_field_whose_value_is_not_a_signature_is_refused_by_name, which fails before this change. * fix(forms): keep a whitespace-only value in a text field without a format (#1323) (#1403) The commit-time Keystroke check returned an empty value for any whitespace-only text before looking at the field's format, so setting a space, a tab or a non-breaking space in a plain text field reported success and removed the field's value. Text and XFDF imports go through the same setter and lost the value the same way. Blank input now clears only a field with a format (number, percent, date, time, special or mask), as before; a field without one stores the text as given. An empty value still clears any field. Adds tests::whitespace_only_text_is_kept_in_a_field_without_a_format and a keystroke assertion in af::tests::numbers_format_like_acrobat, both of which fail before this change. * fix(content): skip an inline image with an unreadable key to its EI (#1318) (#1404) When a key in an inline image dictionary was not a name (`BI /W 4 H 4 ID ... EI`), the parser ended the image at the end of the stream and counted nothing as skipped, so every operator after the image was lost: text_lines found no text on a page whose text follows such an image. An image whose parameters can't be read is now skipped up to the EI that ends it, the skipped bytes are counted, and parsing resumes after it. Without an EI the image still runs to the end of the stream, as before. Adds tests::an_unreadable_inline_image_is_skipped_to_its_end, which fails before this change. * fix(automation): doc_save reports a required full rewrite as not incremental (#1329) (#1405) doc_save reported "incremental": !full, from the arguments alone. When an in-place save had to be a full rewrite (after doc_protect adds or removes encryption, or after Sanitize), write_incremental fell back to write_full, but the result still said the save was incremental. The result now says whether the written file starts with the file it was saved over, read from the new Document::saved_bytes. An ordinary in-place save still reports true and an explicit full save false. Adds an_in_place_save_reports_a_required_rewrite_as_not_incremental, which fails before this change for both doc_protect and doc_remove_hidden. * fix(audit): an identity cm between re and fill no longer hides a cover (#1333) (#1410) Co-authored-by: umesh429 <3474974+umesh429@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * fix(ui): Current page prints the viewed page, not a page labelled with its number (#1308) (#1411) The Print dialog turned Current page into the range "N" for the page on screen, and ranges read numbers as page labels first. In a document labelled i, ii, iii, 1, 2, viewing the first page printed the fourth, whose label is "1". Current page is now passed as a position, the way Selected pages is, through print::select_listed. A typed range still reads labels first. Adds print_ui::tests::current_page_is_the_viewed_page_not_a_label, which fails before this change. * fix(render): draw Turkish Ğ İ Ş ğ ş in non-embedded fonts (vendored hayro-interpret patch 26) (#1409) A PDF whose fonts aren't embedded is drawn with PDFium's Foxit stand-ins for the standard 14 fonts. Those carry only the 230-odd glyphs of the Standard, WinAnsi and Mac Roman encodings, so a letter a font names beyond them in its /Differences mapped to .notdef and drew nothing. iText 2 writes Turkish exactly this way (Times New Roman left unembedded, /Gbreve /Idotaccent /Scedilla /gbreve /scedilla over Ð Ý Þ ð þ), and such letters showed blanks for Ğ, İ, Ş, ğ and ş while ı, ç, ö and ü drew. StandardKind now builds a Latin Extended-A letter the stand-in lacks from the base letter and accent it does have, as Type 1 seac composites and the standard-14 AFM composites are built: the accent is centred on the letter, raised over capitals and letters with ascenders (and moved along the slant in italics), cedillas hang below and ogoneks from the right edge. Composite glyph ids sit above any font's glyph count, one per character code; their width comes from the standard metrics of the name. Test: raster::tests::accented_letters_the_standard_stand_ins_lack_are_built_from_their_parts (fails without the patch: Gbreve drew no pixel). Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * M10: edit OCR text on scanned pages so the change shows (#1397) * M10: edit OCR text on scanned pages so the change shows Editing a recognised word on a scan rewrote it as invisible OCR text, so the page still showed the old word, and the whole OCR layer grouped into one paragraph that rewrapped when one word changed. - An edited invisible paragraph is drawn visibly, over a cover in the paper colour sampled around it, in the scan's sampled ink colour (or the chosen colour). - OCR words group into phrases: a table cell or a tab stop splits them and each scanned line stays apart; a phrase grows rightwards. - Styled rewrites measure with the text matrix's horizontal scale, so stretched OCR words keep their widths instead of overlapping. - The inline editor covers the scanned word and grows like the result. * M10: size OCR text from each word's letters A word box from recognition is tight around the ink, but the text layer assumed every box spans Helvetica's ascender-descender height. A capitals-only word such as "DT" spans only the cap height, so its text was set about 23% too small and its baseline floated up; editing it then drew the new word visibly smaller than the scanned one. The em and baseline now come from the word's letters: cap height or x-height on top, descender or baseline at the bottom. On a real scanned form, a rewritten "DT" -> "DSI" now matches the scanned word's height and baseline. The engine OCR-edit tests build their words the way a scan would box them. * Edit OCR text: sample colours only for invisible blocks, from the current bytes Session::apply looked up every edited block with a fresh text_blocks pass and re-serialized the whole document to render the sampling tile. Text blocks are now cached per page on the editor (keyed on the unmodified document's source identity, so any edit, undo or save invalidates them), visible blocks skip sampling entirely, and the tile renders from the document's current bytes. Adds a visible stretched-text regression test and documents that editing any invisible text makes it visible over a painted cover. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Edit OCR text: name the cached text-blocks tuple (clippy), rustfmt Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Brandon Thomas <echelon@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * Edit text: support per-font visual-order Indic text and nukta reordering (#1380) * Edit text: support per-font visual-order Indic text and nukta reordering - Detect legacy visual-order Indic fonts via Metrics.visual_order (fonts with Indic codepoints without OpenType GSUB tables, or legacy visual font names). - Implement Indic visual-to-logical and logical-to-visual pre-base vowel reordering in crates/edit/src/indic.rs, with support for decomposed/precomposed nuktas and conjuncts. - Apply reordering during extraction and source font reuse only when visual_order is set, leaving modern logical-order text untouched. - Add unit tests for nuktas, conjuncts, and round-trips in crates/edit/src/indic.rs and font visual_order tests in crates/edit/src/tests.rs. * Visual-order Indic: positive evidence only, ActualText kept logical, no font decoding - A font is visual order only when it is a known legacy Indic family (subset tag allowed; aps-/dv- as prefixes) with an Indic Unicode mapping. A missing GSUB is no evidence (bare CFF and subset fonts drop it), so Metrics::from_dict no longer decodes every embedded font program on every call. - Lines with /ActualText text are already logical: skip indic::to_logical, so "बढ़िया" no longer becomes "बढ़यिा". - reading_lines no longer runs bidi recovery on every line (it changed RTL reading_blocks output for all documents); only the Indic recovery remains. - indic.rs indexes through get(). - Tests use a ToUnicode fixture (not visual-order ActualText), cover an edit round-trip, logical ActualText in a legacy font, and a subset Noto font. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Brandon Thomas <echelon@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * M12: preview text structure proposals for auto-tagging (#1383) * M12: preview text structure proposals for auto-tagging * Auto-tag preview: no unregistered command, allowed on copy-restricted files like a11y.check The preview is read-only with no UI command yet, like render_preview, so it no longer names the Planned a11y.autotag catalog id (tool_table_is_well_formed). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * M12: preview text structure proposals for auto-tagging * Keep read-only auto-tag preview separate from unavailable command --------- Co-authored-by: Brandon Thomas <echelon@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * M10: Test current-page print previews and saved output (#1415) Extend the coverage of #1411 with preview raster selection and a dialog-driven PDF save test. Reopen and render the saved PDF to verify the viewed physical page when labels restart. Cover duplicate labels and selection guards without changing production code. Refs #1308, #1411 Co-authored-by: LabDennis <341377186+LabDennis@users.noreply.github.com> * fix(content): count an unreadable inline image with no EI as skipped (#1318) (#1418) Follow-up to #1404. An inline image whose parameters can't be read and that has no EI after them ran to the end of the stream as a BI op with no data, and those bytes were not counted. It is now skipped like one with an EI, its bytes counted in Parsed::skipped. A stream that ends inside the parameters (BI /W 1) still keeps its BI op. * feat(ui): add command palette arrow-key navigation (#1419) * M4: Compare and cache actual Combine file duplicates (#1420) Different equal-sized PDFs with the same name no longer receive duplicate warnings. Share exact-content detection between Grid and List, and cache the result using the existing list revision to remove the per-redraw all-pairs scan. Cover distinct contents, actual duplicates, source parts, cache reuse, removal, undo, redo and closing the tab. Both UI regressions fail before the fix. Fixes #1303 Co-authored-by: LabDennis <341377186+LabDennis@users.noreply.github.com> * feat(preflight): verify image resolution and bleed without rewriting the file (#1408) Squashed from the PR branch (its history added and removed a workflow file; the final tree has no .github changes). * printcheck: proper engine module, one TrimBox note, count unmeasurable images Declares printcheck in engine/src/lib.rs instead of a #[path] module inside ocr.rs. Pages without a TrimBox get one informational document-level finding instead of a bleed warning per page; bleed is only measured against a real TrimBox. Placements with a non-finite or degenerate matrix are counted as resolution unknown (info finding, text line and JSON field) rather than passing every check. Adds a print_readiness test through Automation::call. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Francesco Clemeno <checcomeno@gmail.com> Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Brandon Thomas <echelon@gmail.com> Co-authored-by: umesh429 <umesh.ghanti@gmail.com> Co-authored-by: umesh429 <3474974+umesh429@users.noreply.github.com> Co-authored-by: Marco Arnulfo <103679419+marcoarnulfo@users.noreply.github.com> Co-authored-by: TheLastRoadRunner <99679216+TheLastRoadRunner@users.noreply.github.com> Co-authored-by: Tangu Achilis <43493154+TanguAchilis@users.noreply.github.com> Co-authored-by: krinry <121806532+krinry@users.noreply.github.com> Co-authored-by: Earl Co <earlvanze@gmail.com> Co-authored-by: LabDennis <dennis@leistenschneider.pro> Co-authored-by: LabDennis <341377186+LabDennis@users.noreply.github.com> Co-authored-by: Pratham Bhanushali <134723366+Morpheus004@users.noreply.github.com> |
||
|---|---|---|
| .. | ||
| src | ||
| tests | ||
| Cargo.toml | ||
| README.md | ||
README.md
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,renderandorganize, never on a UI toolkit. - Status: over a hundred tools;
pdfcraft-cli toolslists 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, andcomment_addcan 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 theui.*control channel inpdfcraft-ui-egui.
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 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::commandlinks a tool to the registry id it automates (page.rotate), andcommand_listreports 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_previewreturns 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_editcommits 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_editaccepts the resulting rectangle. doc_closerefuses to drop unsaved changes unlessdiscard_changes: true.doc_savewrites atomically, incrementally in place, and in full for a new path.- 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.
Shared field properties
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 and rotations 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) | C:\Program Files\PdfCraft\pdfcraft-cli.exe by default (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, default install folder
claude mcp add pdfcraft -- "C:\Program Files\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
- Add the engine capability first, with its tests (the tool is a thin adapter).
- Add a
ToolDefinsrc/tools.rs: a precise description, the schema,ro()/destructive(), andcmd()if a registry command exists. - Handle it in
Automation::call, validating pages and positions with the existing helpers. - Add an end-to-end test in
tests/automation.rs.tool_table_is_well_formedchecks 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.
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.