THPDFHeadlessDocument
HPDFHeadlessDocument supplies a console document API for native Linux and Windows using the existing HotPDF object parser, Direct File helpers, font decoders, content interpreter, filter decoders, and xref writer
The document loader accepts classic cross-reference tables, xref streams, hybrid xref sections, incremental Prev chains, direct and compressed objects, inherited page resources, content arrays, Form XObjects, and AcroForm field trees
Hybrid side streams take precedence over the accompanying table, while newer revisions take precedence over older ones; object-stream members are decoded and parsed lazily through the shared object parser
Lifecycle and ownership
Create uses THPDFHeadlessDocumentOptions.Default, while the options overload accepts explicit budgets and a caller-owned cancellation token
LoadFromFile closes the previous document, opens the source read-only, loads the current object graph, and closes partial state on failure; Close releases the source and all loaded objects
LoadFromFile(FileName, Password) authenticates Standard AES-256 R5 or R6 documents through THPDFHeadlessAES256Security; the original single-argument overload uses an empty password
User passwords must grant text extraction or form filling before those operations execute, while owner passwords bypass user permission restrictions; wrong passwords, authenticated Perms mismatches, denied operations, and malformed cipher payloads have distinct document diagnostics
Direct strings and streams are decrypted through the shared cryptographic code, compressed members are decrypted with their container only, and encrypted incremental replacements remain encrypted under the original keys and permission policy
Passwords use UTF-8 bytes truncated at 127 bytes with no SASLprep normalization; unsupported handlers, explicit Crypt filters, and PDF MAC policies are diagnosed rather than ignored
Encoded dictionary keys and resource names are decoded before use, case remains significant, and duplicate decoded keys are rejected; field flags and MaxLen must fit the supported nonnegative 32-bit range
Instances are not thread-safe; use one instance per worker and keep its cancellation token alive until the instance is destroyed
Pages and text
PageCount reports the number of page-tree leaves; ExtractPageText(PageIndex) accepts a zero-based index and returns Unicode text assembled from the shared glyph interpreter
ExtractPageTextBounded applies temporary glyph and stream limits before text preparation and restores all original resource options after success, failure or cancellation
GetObjectAccess exposes read-only borrowed catalog, information and object access with bounded index allocation for native structural and full comparison
Text decoding follows font encodings, encoding differences, embedded ToUnicode CMaps, explicit widths, and the standard-font metric provider; nested Form XObjects apply their matrices and use their own or inherited resource dictionaries
The Linux standard-font fallback requires Fontconfig and installed TrueType fonts; complex document fonts must provide a supported decoding strategy, and missing font resources produce a diagnostic
AppendPageText adds visible or fitted invisible Unicode text while retaining original page content and encrypted security policies
AppendImportedPages clones selected page resource graphs, inherited geometry and visible normal appearances while preserving existing destination revisions and authenticated encryption policy
AcroForm text values
FormFieldCount, GetFormField(FieldIndex), and FindFormField(Name) enumerate terminal fields using fully qualified names and inherited field types, flags, maximum lengths, and values; indices are zero-based, and a missing name returns -1
SetTextFieldValue(FieldIndex, Text) accepts writable Tx fields, writes a UTF-16BE PDF string, and sets NeedAppearances=true on the AcroForm dictionary
This value-only method relies on viewer regeneration; viewers that do not regenerate appearances may continue displaying an old appearance or an empty widget
SetTextFieldValueWithAppearance generates explicit Unicode appearances for every existing widget using a caller-supplied TrueType font, actual glyph metrics, Identity-H encoding, ToUnicode, and full FontFile2 embedding
The appearance profile supports single-line and multiline text, wrapping, comb cells, quarter-turn rotations, fixed size or auto-fit, alignment, and optional native HarfBuzz/FriBidi complex shaping
SetChoiceFieldValuesWithAppearance handles multiple-selection list boxes, inherited options, sorted export arrays, and every visible selected row; the single-value helper also supports combo export/display labels
GetChoiceFieldValues reads the complete selected export array; SetButtonFieldValueWithAppearance and SetPushButtonAppearance generate actual button states and captions
New appearance objects and streams are bounded before field changes and remain encrypted under the original AES security policy when saved; native Linux Cairo and independent readers consume the same generated objects
Text-field methods enforce read-only flags, MaxLen in UTF-16 code units and the field type; choice and button fields use their separate appearance methods, while XFA forms remain outside this document loader's AcroForm profile
Signed documents use authenticated DocMDP and FieldMDP policies: permitted form updates preserve existing signed revisions, while locked fields, P1 restrictions and attempts to overwrite signed signature fields are rejected
Validated DSS/VRI evidence adds authenticated certificate and revocation data to an incremental revision without changing existing ByteRange signatures
Signature verification
SignatureCount enumerates signed AcroForm signature fields and VerifySignature(SignatureIndex, Options) validates zero-based signatures using the shared parser and streaming OpenSSL 3 CMS provider
The PDF profile accepts adbe.pkcs7.detached and automatically recognized ETSI.CAdES.detached with hexadecimal or standard literal Contents; CAdES always authenticates the ESS signing-certificate binding, while explicit CA settings evaluate trust separately
DocTimeStamp with ETSI.RFC3161 automatically authenticates genuine encapsulated TSTInfo, ESS, TSA purpose and signer name, and the exact PDF imprint; configured timestamp roots and CRLs separately evaluate TSA trust
Verification validates the exact unsigned gap including its delimiters and binds its decoded bytes to the current signature dictionary before cryptographic verification
The result distinguishes integrity, explicitly evaluated CA trust, and unsigned bytes after the authenticated revision; unsupported PDF signature profiles produce a typed diagnostic
See HPDFVerifyHeadlessCMS for runtime requirements and THPDFHeadlessCMSOptions for budgets and trust settings
Incremental approval signatures
SignToFile signs an existing writable, unsigned Sig field and publishes an independent incrementally updated PDF using a caller-provided PEM certificate and unencrypted PEM private key
AddSignatureField creates a page widget and its AcroForm links, including a new AcroForm on a plain imported PDF; SetSignatureFieldAppearance generates its visible caption, and SignPFXToFile loads a PKCS12 certificate/key identity with its chain
CertificationPermission creates the first DocMDP certification signature; P2 and P3 allow subsequent approval signatures in existing fields, while P1 rejects further signatures
The original source bytes and loaded object graph remain unchanged; later approval signatures preserve earlier signature bytes and their authenticated revision boundaries
Standard AES-256 R5 and R6 encryption, passwords, IDs, and permissions remain in effect, including encrypted object-stream sources; the signature Contents string follows the PDF exemption from encryption
Existing signature values, read-only fields, certified-document policies, denied form-fill permissions, divergent cancellation tokens, and exhausted output budgets are rejected without publishing an output
Document timestamps
TimestampToFile creates a genuine RFC 3161 document timestamp in an existing unsigned signature field without an application signing key, using a caller-owned TSA transport and explicit TSA trust
The writer preserves original revisions and AES security, declares the ESIC extension for pre-PDF 2.0 input, and atomically publishes only after nonce, imprint, signature, certificate, configured revocation, and seed checks pass
Necessary authenticated document timestamp changes are permitted under DocMDP and FieldMDP; ordinary form edits and approval signatures retain their original restrictions
FDF and XFDF form interchange
ExportAnnotationsFDF exports bounded annotation object graphs and their shared appearance resources; SaveAnnotationsFDFToFile prepares named replacements and appends in an independent atomic PDF revision
The binary FDF annotation profile preserves the authenticated document's encryption and signature policy, context-sensitive local GoTo page references and exact unchanged publication; it leaves the loaded document unchanged after saving
SaveAnnotationsXFDFToFile appends bounded mapped annotations to an independent incremental revision; HPDFExportHeadlessAnnotationsXFDF returns their XFDF bytes
ExportFormData returns bounded Unicode field data, including actual choice arrays and checkbox or radio export states
ImportFormDataToFile regenerates genuine appearances on a private authenticated revision graph and atomically publishes an incremental PDF while preserving the loaded source state
ImportRichFormDataToFile imports the bounded XHTML profile from FDF RV or XFDF value-richtext with actual regular, bold, italic and bold-italic font programs
SaveRichTextFieldUpdatesToFile applies scalar fields and original typed rich runs in one independent atomic revision, preserving actual font programs and PDF numeric precision; unchanged protected fields require matching decoded appearances and resolved resources for every widget
Existing encryption, read-only flags, authenticated DocMDP and FieldMDP, original signatures, cancellation and resource budgets remain enforced; see Native FDF and XFDF form data for supported syntax and scalar interchange boundaries
Borrowed rendering access
GetRenderAccess(PageIndex) provides the existing page dictionary, inherited resources, font resolver, object resolution, permission check, cancellation token, and bounded decoded-stream callbacks through THPDFHeadlessRenderAccess
This is a serial read-only borrowed view; the document must remain loaded and unchanged until the renderer finishes, and callers must not mutate its exposed object graph
The view's RequireOutputPath callback checks a prospective output against the source's canonical path and physical file identity without creating or modifying a file
Independent output
ExtractPageGlyphs returns positioned glyphs through the bounded nested-content walker; AnalyzePageSemanticText provides semantic text and source geometry for native contract comparison
SaveToFile(FileName) copies the original bytes and appends replacement object values, a classic xref table, and a trailer linked through Prev; compressed object members are materialized as direct objects in the appended revision, and original stream bytes are preserved
The output must not alias the source path or file identity; writing uses an exclusively created staging file in the destination directory, flushes it, and publishes it by atomic rename
Budget, cancellation, or serialization failures preserve an existing destination and delete the unpublished staging file; the source remains read-only
Native annotated review PDF exports actual Unicode highlights and visible appearances with authenticated annotation permissions, retaining the original loaded document and signature revisions
Format boundaries
The current profile supports Standard AES-256 R5 and R6 encryption, explicitly diagnoses unsupported security handlers and stream filters, and rejects retired free-object generations that cannot be represented by its writer
Bootstrap xref streams require direct dictionary values and a direct bounded Length; malformed widths, subsection overlaps, unsigned offsets above Int64, compressed-member mismatches, reference cycles, and configured limits produce typed diagnostics
Decoded content supports Flate, ASCIIHex, ASCII85, and LZW filters with supported predictors and indirect stream lengths; image payloads are not decoded for text extraction
Native signing workflows cover signature fields, visible appearances and certification; authenticated signed-form policies, timestamp and long-term validation APIs retain their explicit integrity and trust options
Acceptance
Named rich font families add multiple actual supplied families through SetRichTextFieldValueWithFamilies and ImportRichFormDataWithFamiliesToFile, with the existing field, security and transaction policies
Native rich-text fields provide typed styled runs, actual embedded style-font appearances, synchronized V and RV values, encrypted incremental output and bounded transactional edits; GetRichTextFieldValue reads stored or inherited XHTML
Tests/Linux/Run-HeadlessDocumentTests.sh builds a native ELF executable with desktop variables cleared and checks for GUI library dependencies; Run-HeadlessDocumentTests-Windows.cmd Win32 and Win64 exercise the same shared document API
See THPDFHeadlessFormField, EHPDFHeadlessDocumentError, and THPDFHeadlessDiagnosticCode for returned values and typed diagnostics
Annotation removal
Remove page annotations by exact page and Unicode NM identity through SaveAnnotationRemovalsToFile, with popup and reply cascades, bounded preparation and atomic separate output
The loaded document remains unchanged; an unchanged selection copies the exact current revision, and incremental removal retains historical bytes