Implementation Status and Audit
Last updated: 2026-10-25 (substitute fonts: WPF glyph fitting and Dingbats, hyphenated family names) · 2026-10-17 (M9: native rendering, no PDFium pixels in Auto or Vector mode) · 2026-09-26 (Direct2D backend and page host, blend modes, soft masks, tiling patterns, vertical writing, glyph clips, two-circle radials, predefined CJK CMaps, JPEG 2000, mesh shadings, CCITT, JBIG2, knockout and non-isolated groups, encryption, certificate encryption, permissions)
Where: main (the work started on branch feat/vector-migration-gaps, PR ramanacr/pdf-viewer#1, and continued in later pull requests).
Scope of this document: what the first implementation pass (commits b0ab63c … 2e2fdd7, 2026-09-21) delivered against this bundle, what it got wrong, what the second pass fixed, and what remains — with evidence, not claims.
1. Audit of the first pass
What it did well
- The seams are right.
PdfEngine.VectorandPdfEngine.Vector.Windowsexist, are inPdfViewer.slnx, andPdfEngine.Vectorhas no reference toPdfEngine.Pdfium(ADR-007). PDFium is referenced only by the test project, as an oracle. - Canonical IR exists. An immutable
PdfDisplayListwith a typed command hierarchy, a stablePdfFallbackReasonenum and aPdfFallbackTokencarrying no PDFium types (04, 06). - Engine selection is centralized in
PdfDocumentServiceFactorywithPDF_ENGINE_MODE, and the UI exposes Auto / Vector / PDFium plus a per-page engine badge. - Parser foundations: lexer, parser, classic xref + xref streams + object streams,
/Prevchains with cycle guard, page-tree inheritance, Flate/ASCIIHex/ASCII85/RunLength with predictors, aPdfSecurityLimitsclass, outline extraction. - Non-rendering features left on PDFium as ADR-008 requires; existing viewer tests were kept green.
What it got wrong (severity-ordered)
| # | Gap | Why it matters | Plan reference |
|---|---|---|---|
| 1 | Silent wrong output in the default mode. Auto rendered through the vector path whenever the display list had no fallback tokens, but many constructs were silently dropped or approximated without a token: Form XObjects were a stub (// Execute nested form stream — never executed), inline images were tokenized as garbage, text render mode 3 (invisible OCR text) was painted, soft masks and blend modes only set a feature flag, unknown colour spaces defaulted to DeviceRGB, unsupported filters returned raw bytes, annotation appearances were never drawn (PDFium renders them). |
“vector mode produces silent wrong output” is a stop condition. | 13 stop conditions; 06; 11 “Error policy” |
| 2 | Text was re-laid-out Unicode. Glyphs were drawn with FormattedText in a guessed system font, ignoring embedded font programs and glyph IDs. |
Violates ADR-006 directly. | 04 “Text rule”, ADR-006 |
| 3 | “Direct2D / DirectWrite” was claimed but not built. The renderer is WPF DrawingVisual + RenderTargetBitmap (software rasterizer). Tooltips and the showcase PDF advertised DirectX/Direct2D/GPU tessellation. |
Misleading product claims. | 12 “Product claims”, ADR-005 |
| 4 | Rendering bugs: image drawn with the CTM applied twice and vertically flipped; only raw RGB24 images handled (gray, CMYK, indexed, 1–16 bpc, /Decode, masks, SMask ignored); page /Rotate ignored (only viewer rotation applied); axial Extend false and radial focal semantics wrong; hairlines and dash patterns wrong under scaled CTMs; one new thread per page render. |
Visible corruption on ordinary files. | 04, 05 |
| 5 | Fallback was page-only and artificial. Any token ⇒ whole page to PDFium; the showcase “demonstrated” fallback using ri, a valid standard operator. No region compositing existed; IPdfFallbackProvider was declared but never implemented. |
Area coverage metric meaningless; “full-page fallback hides lack of progress”. | 06 “Fallback granularity”, 13 |
| 6 | Security/robustness holes: Flate decompression allocated the whole output before the size check (bomb not bounded); MaxObjectsCount, recursion, per-page budgets not enforced; no encryption detection (encrypted files with an empty user password parsed ciphertext); vector renders bypassed PdfSecurityPolicy.EnsureRenderDimensionsAllowed; resolver shared a positional byte source across threads without locking; xref offsets were trusted without checking the object header. |
“memory limit can be bypassed” is a stop condition. | 09, 08 |
| 7 | Semantics bugs: font cache keyed by resource name (/F1 on two pages ⇒ same font), composite fonts read as fixed 2-byte codes regardless of CMap, Tw not scaled by Tz, standard-14 widths approximated, /Differences and encodings ignored, ToUnicode parser line-based, command bounds in mixed coordinate spaces (unusable for culling), selection boxes ignored the CTM and crop origin. |
Wrong text positions, wrong selection/search boxes. | 04, 05 “Fonts roadmap” |
| 8 | Verification gaps: 13 vector tests, no differential tests despite the oracle reference, no fuzzing, no corpus tooling, no benchmarks of the vector path, CI did not run the vector test project at all. Commits for M6/M7/M9 were titled as delivered with a single happy-path test each. | “A feature is not supported merely because one sample renders.” | 07, 11 “Definition of done” |
| 9 | Diagnostics unused: PdfEngineMetrics never recorded; TotalPagesParsed never incremented; no report format. |
Backlog A5/J4/J5 not met. | 06 “Telemetry” |
2. What the second pass changed
Every item below has tests in tests/PdfEngine.Vector.Tests or tests/PdfViewer.Tests.
Core (PdfEngine.Vector)
- Interpreter rewrite (
Content/PdfContentInterpreter.cs): Form XObjects (matrix, BBox clip, recursion + self-reference guard, transparency groups with correct alpha reset), Type3 fonts (glyph procedures executed,d1uncoloured), inline images (BI/ID/EI, abbreviations, exact-length and scan recovery), image XObjects, optional content (/OCProperties /D,BDC /OC, OCMD policies, XObject/OC), annotation normal appearances (12.5.5 algorithm, hidden/NoView flags), shading patterns andshwith function-sampled stops, text render modes (3/7 kept invisible for selection, 1/2/5/6 stroked, 4–7 classified),TJas one run,Tw/Tzper spec, operand stack taken from the end,BX/EX. - Classified fallback everywhere with conservative page-space bounds: soft masks, non-Normal blend modes, knockout groups, tiling patterns, pattern strokes, mesh/function shadings, unsupported colour spaces, JPX/JBIG2/CCITT, text clipping, resource limits, unknown operators (outside
BX/EXonly). - Budgets: q-depth, operators, path segments, glyphs, image pixels (per image, per page), Type3 depth, wall-clock per page, cancellation every 256 operators — all produce typed
PdfResourceLimitException→ classifiedResourceLimitfallback. - Typed errors (
Diagnostics/PdfVectorExceptions.cs): syntax, object resolution, unsupported feature, resource limit, encryption; every document-open data error surfaces asPdfSyntaxException. - Document: encryption gate (
PdfEncryptedDocumentException), xref reconstruction by scanning (damaged/missingstartxref, xref-stream-only files, catalog in object streams), hybrid/XRefStm, object-header validation with one rebuild, object-count limit, cached object-stream index, serialized resolver, indirect/Length, off-thread single-flight display-list builds, bounded LRU display-list cache (MaxCachedDisplayListCommands), crop box clipped to media box,/Rotatesnapped to 90°. - Images (
Images/PdfImageSource.cs): lazy decode (display lists don’t pin pixels), any colour space, 1/2/4/8/16 bpc,/Decode, stencil masks with fill colour,/SMask, stencil and colour-key/Mask, JPEG passthrough with Adobe-CMYK handling. - JPEG 2000 reliability: CoreJ2K 2.3 decoded lossy colour codestreams differently from run to run, so they went to the fallback renderer for a while. The root cause: its inverse wavelet transform rented the reconstruction buffers from the process-wide
ArrayPooland did not clear them, and code-blocks with no coded passes (most chroma subbands of a lossy image) never write their area, which therefore kept whatever the pool last held. Clearing on return did not help, because other pool users return dirty buffers. CoreJ2K 2.4.1 clears the buffers on rent; the same codestream now decodes bit-identically, repeatedly and in parallel (tested with a deliberately dirtied pool). All JPEG 2000 images are drawn on the vector path again, decodes run on the calling thread and observe cancellation, and undecodable streams still fail as a typedImageDecoderegion. Corpus:ImageDecoderegions on the JPEG 2000 files 28 → 0 (GovDocs1 001307, 001658, 001659, 001967, 001977 and veraPDF 6-2-8-3-t03); page mean pixel diffs against PDFium 3.99–7.89 before (with those regions drawn by PDFium) and 5.00–7.66 after. Decode time on the largest corpus images is the same or lower than with 2.3 (1275×1650 CMYK 741 → 636 ms, 1026×1293 RGB 306 → 228 ms). The corpus “JPEG 2000 noise” in the edit and redraw smokes was this bug. - JPEG soft masks (/SMask with /DCTDecode): the core has no JPEG codec, so it hands the mask to the backend (
PdfDecodedImage.JpegMask), which decodes it with WIC or WPF and applies it as alpha. With the Symbol fix, no GovDocs file falls back to PDFium for fonts or images any more. - Streams, functions, colour (merged from a parallel workstream): bounded streaming Flate, LZW with
/EarlyChange, typed unknown-filter errors, image-filter stop (DecodeImageStream); PDF functions types 0/2/3/4 with bounds; CalGray/CalRGB/Lab/ICCBased (colour managed since the colour management work below; before it, via/Nor/Alternate), Indexed over any base, Separation/DeviceN tint transforms, Pattern spaces, flagged unknowns. - Fonts (merged from a parallel workstream): identity-keyed font cache, Standard/WinAnsi/MacRoman/Differences + AGL, token-based ToUnicode (arrays, surrogates, caps), real Standard-14 widths, code→CID CMaps (Identity, embedded, variable-length), CIDToGIDMap, sfnt
cmap0/4/6/12 lookup for embedded TrueType, Type3 model, descriptor metrics.
Windows backend (PdfEngine.Vector.Windows)
WpfDisplayListCompiler→ frozen, resolution-independentDrawingGroup;WindowsVectorRendererrasterizes it and composites fallback regions last from anIPdfFallbackProvider(hybrid) or outlines them (strict).- Glyph runs from the embedded TrueType/OpenType program by glyph ID (ADR-006). Without a loadable program: a metric-compatible system substitute placed at the PDF-computed positions; if the substitute lacks a glyph, or the program is bare Type1/CFF, the run becomes a backend fallback region instead of
.notdefboxes. - Fonts that are not embedded are drawn with the installed font chosen by
SystemFontCatalog.Match, the one routine editing, PDF/A conversion, annotations and both renderers share:- the exact PostScript name, if its weight and slant fit;
- the family name as written, then without MT/PSMT/PS, then without the style words written into it (weight from Thin to Black, Italic/Oblique, Narrow/Condensed). A ‘-‘ followed by words that are not style joins the words of the family: “MS-Gothic,Bold” and “MS-PGothic” are MS Gothic and MS PGothic, while “Arial-BoldMT” is still Arial Bold. Before, such a name in any style but its own fell to Arial (
FontSubstitutionTests); - aliases for PostScript and Adobe families (Helvetica to Arial, Palatino to Palatino Linotype, AvantGarde to Century Gothic, and so on), limited to the metric-compatible regular and bold weights;
- the class of font: fixed pitch, script, serif, else sans. A name that plainly says sans overrides a wrong serif flag.
- A Symbol font re-encoded with codes of its own is drawn with the installed Symbol font by what each glyph is, and Adobe’s private-use forms (the serif registered and copyright signs, pieces of tall brackets) by their standard characters (
Fonts/SymbolFontCodes). - Over the 284 GovDocs files, 21 render closer to PDFium and 2 differ more: one is image noise, and one is Optima, which PDFium draws as a serif. Substitute glyphs are fitted to the document’s /Widths, as Acrobat’s substitutes are: a glyph wider than its width is narrowed so it does not run into the next, and a narrower one is widened by up to a tenth and centred in the rest. (PDFium leaves them as they are, so wide substitutes overlap there.) The Direct2D, WPF and Skia backends and the shaped-word fit share the rule (
SubstituteShaper.FitToWidth). Before, the WPF backend fitted only shaped words: a “W” at 40 % of its Arial width was 132 px of ink against 53 px in Direct2D at 144 pt, 72 dpi; now both are 53 px. A Latin line with widths 25 % narrower and 20 % wider than Arial’s is at mean 1.08, 0.48 % of pixels off by more than 64, against Direct2D (11.5 and 5.3 % before; 1.03 and 0.46 % for the same line at Arial’s own widths, the two rasterizers’ edges) (Direct2DSubstituteShapingTests.Wpf_Fits*). - ZapfDingbats (any font named like Dingbats) is drawn with Segoe UI Symbol by the Unicode of its built-in encoding (U+2700 block and a few shapes), in the Direct2D and now the WPF backend; before, the WPF backend had no substitute and drew none of the text. Both draw the same glyphs; the WPF render is at mean 0.32 against Direct2D (
WpfCharacterFallbackTests.ZapfDingbats_DrawsTheGlyphsDirect2DDraws).
- A Symbol font re-encoded with codes of its own is drawn with the installed Symbol font by what each glyph is, and Adobe’s private-use forms (the serif registered and copyright signs, pieces of tall brackets) by their standard characters (
- Correct image orientation,
/Rotate+ viewer rotation, shading extend bands and radial clip, hairline and dash handling in page units, byte-bounded image cache, one long-lived STA render thread,AnalyzeAsyncandBuildPageDrawingAsyncfor hosts.
Composition root (PdfViewer)
- (M9) The PDFium region provider is gone: no page, tile or region is drawn by PDFium in Auto or Vector mode (see “M9: native rendering” under the PDFium-free release gate).
HybridVectorDocumentService: vector path honoursEnsureRenderDimensionsAllowed; engine badgeVector/Vector (N approximated)/Vector (N unsupported)(strict) /Unreadable page; per-pagePdfEngineMetrics(once per page, no document text) withToJsonReport(); selection boxes fromTextToPagenormalized to the unrotated crop box (matches PDFium); lazy vector open after an engine switch.- Showcase PDF and its test: a damaged JPEG the engine cannot decode is left out (PDFium leaves out what it cannot decode too), and everything else on the page, the knockout transparency group included, is drawn natively. (The showcase used a Multiply blend, then the knockout group, until each became native.)
- A race where a late text-extraction result overwrote already-populated segments is fixed (
PageViewModel).
Vector page host (E8) — decided: keep Auto default, build the host
WindowsVectorRenderer.BuildPageSurfaceAsyncbuilds a frozenDrawingImage: white page and vector content (regions the WPF renderer cannot draw show what it draws of them; strict mode outlines them), sized in points after/Rotate+ viewer rotation.IPdfDocumentService.GetVectorPageSurfaceAsync(default: none).HybridVectorDocumentServicereturns a surface unless the page has more than 40 000 commands (live drawings re-render every frame; such pages are Direct2D bitmaps with detail tiles, as in the default host); surfaces are cached per page and rotation (LRU 24), cleared on open/close/engine switch.PageViewModel.VectorSurface/PageSurface/HasSurface: the page view bindsPageSurface. A zoom change does not rebuild a surface and no page bitmap is held; very dense pages (native Direct2D bitmaps) and PDFium-mode pages (developer builds) stay on the bitmap path.- Night mode is live too: the WPF surface is compiled with every paint, gradient stop and image colour-inverted on a black page (inversion commutes with source-over compositing; test: ≤ 1/255 mean difference). In the default Direct2D host the page bitmap and the detail tiles are drawn as by day and inverted on the GPU by a Direct2D Invert effect (M9).
- Scroll cost:
Views/PageSurfaceCachegives a page image aBitmapCacheat scale 1 while it fits 4096 device pixels, so scrolling composes a GPU texture and the vectors re-render only when the size changes (zoom). Larger (high-zoom) pages draw live. - Tests:
VectorPageHostTests(surface reuse across zoom, rotation, night surface = inverted day surface, bitmap path for PDFium/dense pages, hybrid region page stays live, hard edge at 16× zoom, cache rule). Smoke: the real viewer opened EngineShowcase and a path-heavy file on the live path, stayed responsive, badge⚡ Vector.
Corpus and embedded font programs
- Corpus:
eng/vectorpdf/corpus/fetch-corpus.ps1fetches the veraPDF corpus (CC BY 4.0) and the PDF Association PDF 2.0 examples (CC BY-SA 4.0) at pinned commits into a git-ignored cache and writesmanifest.json(SHA-256, source, licence per file; 2 913 files). PDFs are never committed. -
Corpus runner reports the hybrid-beta gate inputs ( --summary), per-detail fallback counts and worst pixel differences;vectorpdf diffpagewrites vectorPDFium difference images and dumps commands, content and per-font load status. - Font programs (
Fonts/Programs/): every embedded kind is normalized into an sfnt the backend loads — TrueType subsets getname/OS/2/post/cmap(andhhea/hmtxwhen inconsistent); bare CFF (Type1C, CIDFontType0C) is wrapped in OpenType; Type 1 (FontFile) is converted to CFF (eexec/charstring decryption, subrs inlined, flex, hint replacement, seac, FontMatrix baked into outlines). Glyph indices come from the CFF charset / built-in encoding / sfnt cmap per kind. Any invertible CFF FontMatrix is drawn: a Top DICT matrix that is not a uniform 1/unitsPerEm scale (narrow, skewed, rotated, mirrored, 1/2048 rounded) is rewritten in place to the standard scale and the rest becomes the face’s glyph matrix (when the entry is too short to hold a standard scale, the program keeps its matrix, which DirectWrite applies). CID-keyed fonts whose FDArray Font DICTs carry a FontMatrix keep their program as it is: DirectWrite concatenates FD × Top as FreeType does (the FD matrix alone when the Top DICT has none), which one glyph matrix per face could not express for several FDs; the em inheadfollows the first glyph’s FD × Top. Only a singular matrix is refused. Glyph advances stay on /W, /DW and /Widths in 1/1000 text space whatever the matrix; a simple font with an embedded Type1C or Type 1 (FontFile) program, no /Widths and a non-standard-14 name advances by the program’s own widths (CFF charstring widths; Type 1 hsbw/sbw, a seac composite keeping its own) mapped through its FontMatrix and chosen through the font’s encoding, as PDFium does. Codes past a /Widths array that is too short get /MissingWidth, else 0, as in PDFium. Drawing, text extraction and selection, and the editing encoder all read these advances throughPdfFont.GetGlyphWidth. A program the backend still rejects becomes a classified fallback region — never a silent substitute. - Root cause found in the first pass’s renderer: WPF’s font cache throws for a second font file loaded from a folder it has already read, and for a folder that is deleted and recreated. All embedded fonts were written to one folder, so only the first embedded font per process ever rendered with its own glyphs; the rest silently used system substitutes. Fonts now get one folder each under a per-renderer root.
- Page boxes: only an explicitly specified
/CropBoxis inherited, and it is clipped to the media box at the leaf (two corpus files rendered at the wrong size).
Direct2D / DirectWrite backend (ADR-005; ADR-011 decided)
PdfEngine.Vector.Direct2D(Vortice.Windows 3.8.3, MIT): D3D11 device (hardware, WARP fallback), Direct2D 1.1 device context, DirectWrite fonts from memory (custom font-file loader, no temp files), WIC JPEG decode. Clips are geometric-mask layers; hairlines useStrokeTransformType.Hairline; output larger than 2 048 px is tiled, and geometry realizations are shared across tiles; device loss recreates the device without reparsing (SimulateDeviceLosstest).- Default page host: the page bitmap comes from Direct2D, and when the page is zoomed past that bitmap a viewport detail tile (visible area plus a margin, ≤ 4 096 px a side) is rendered at exact device resolution and laid over it; scrolling inside the margin reuses the tile. Zoom range 25–1 600 %.
PDF_VECTOR_HOST=wpfselects the earlier WPF drawing host; the WPF renderer also stands in when no Direct3D device exists. - Host tuning (
vectorpdf tiles,eng/vectorpdf/baseline-tiles.txt): rectangular clips (re W n) are axis-aligned clips instead of offscreen layers, and other clip layers are bounded to their mask (a 58-command text page with 13 nested clips: 516 → 44 ms at 300 dpi). GPU tiles are 4 096 px (one replay per viewport tile instead of four). Replayers, with their tessellations, are cached per page and scale (day and night share them since M9), so scrolling at a fixed zoom reuses them (path-heavy fixture at 1 600 %: next tile 136 ms, versus 1.2 s before). The detail tile shows the visible area first, then the margin tile replaces it.forceSoftwaremeasures the WARP tier (RDP, VMs). - Zero-copy detail tiles: on a hardware tier in a local session, a detail tile is rendered into a shared Direct3D 11 texture and shown by a WPF
D3DImagethrough a Direct3D 9Ex surface (D3D9ExInterop, four COM calls, no extra package): the pixels never leave the GPU. Next tile on light corpus pages p50 ≈ 30–40 ms against 130–175 ms for readback plus WPF bitmap (before WPF’s upload). Software tier, RDP andPDF_GPU_PRESENT=0keep bitmaps; a lost display device drops the tile and the page bitmap shows until the next one. - In developer builds, PDFium-mode pages get the same detail tiles (
RenderPageRegion: FPDF_RenderPageBitmap with a negative origin). No other page or region is drawn by PDFium (M9).
Portable Skia backend (web and Android, step 1)
PdfEngine.Vector.Skia(net9.0, SkiaSharp 3.116.1, MIT) replays the display list on Skia’s CPU raster canvas with the Direct2D backend’s semantics: every command type, the 16 blend modes, soft masks, non-isolated and knockout groups, tiling patterns, mesh and function shadings, night mode and fallback regions. It is not used by the WPF app. Design, coverage, gaps and measurements:src/PdfEngine.Vector.Skia/README.md.tests/PdfEngine.Vector.Skia.Testsrenders each fixture with Skia and Direct2D: 211 of 219 renders differ by a mean of at most 1.0 (0–255). A 200-page corpus sample at 96 dpi (measured again after the CMYK decoder): mean per page 0.23 on average, median 0.01, largest 4.75, no page with content the backend classifies (before: 4 pages, worst 14.28, a blank CMYK JPEG). Four-component (CMYK, YCCK) JPEG data is decoded by a managed decoder (JpegComponentDecoder: Huffman baseline, extended and progressive 8-bit) and takes the Direct2D path for WIC’s CMYK samples (CmykJpegTests: against WIC and Direct2D, JPEGs written in code). Remaining gaps: arithmetic-coded and 12-bit JPEG, and small text is lighter than Direct2D’s. The renderer keeps its analysis per display list, so a page rendered in tiles decodes its images once.- Text in a font that is not embedded is shaped when it is drawn with a substitute (the web demo’s Noto faces, or installed fonts): Arabic joining forms, lam-alef and other ligatures, GPOS marks, Indic pre-base vowel signs, reph and conjuncts, with the editing shaper (
TextShaper,IndicShaper) and the substitute’s GSUB and GPOS; no HarfBuzz. Arabic is taken as seen (left to right) and put back in reading order once; a word whose glyphs go right to left is read as it is. A pre-base vowel sign written before its consonant is moved after it before shaping. Each shaped word is fitted to the space its/Widthsgive it (narrowed, or widened by up to a tenth and centred). Embedded fonts and Latin text are drawn as before. The Skia, Direct2D and WPF backends share this code (Text/SubstituteShaper): each reads the substitute’s font file once (SkiaResources,D2DResourcesandWpfFontCache.GetShapingFont) and draws the shaped glyphs, so the desktop app and the web demo shape alike; a word the substitute cannot shape (a glyph missing) is drawn glyph by glyph as before. The WPF backend, used only without a Direct3D device, draws a fitted word under its horizontal scale as Direct2D does. Shaping changes drawing only: the text page, selection and search read the characters. The shaper now keeps a glyph that a substitution split off (Noto Sans Arabic’s dots) with its letter when right-to-left text is reversed; before, the dots of a word’s first letter landed to its left, in the web demo and in text added with such a font. Tests:SubstituteShapingTests(Skia, 15: Segoe UI, Arial and Nirmala UI stand in for Noto; one more with the real Noto files whenNOTO_FONTS_DIRis set) andShapingTests.ArabicGlyphsSplitOff_StayWithTheirLetter_WhenReversed(engine, Noto only);Direct2DSubstituteShapingTests(engine, 16: the same cases by glyph id in the Direct2D backend, the fitted width, a font without the glyphs, the text page, the WPF backend against Direct2D by pixels, mean 0.1 to 0.3, and a word narrowed to its/Widthsas wide in WPF as in Direct2D, within 1 px at 72 pt, and the same for a single Latin glyph and a Latin line);SubstituteShapingParityTests(Skia, 2: a shaped Arabic and a shaped Devanagari page against Direct2D, mean channel difference 0.1 to 0.35). - Characters a substitute lacks, on the desktop too: when no face of the Direct2D backend’s substitute chain has every character of a run (Hebrew and Devanagari under Arial, Devanagari and Han), the face with most of them draws its own and each other character comes from an installed face that has it (
D2DResources.GetCharacterFace), as the Skia backend’s per-character faces draw it in the web demo. The face is chosen by script first (Fonts/CharacterFaces: Segoe UI or Arial for Arabic and Hebrew, Nirmala UI for Indic, Segoe UI Symbol or Segoe UI Emoji for symbols, and for Han Microsoft YaHei, Microsoft JhengHei, Yu Gothic or Malgun Gothic by the font’s CID ordering, else by kana or hangul in the text or the font’s name: the rule the web demo’sBundledFontIndexnow shares), then by DirectWrite’s system font fallback (IDWriteFactory2.SystemFontFallback, with the language’s locale for CJK). Each face’s words are shaped with its own tables (SubstituteShaper, the words of that face only). Before, the characters the substitute lacked were left out. A run one face has whole is drawn as before (one face), and so are embedded fonts; text extraction, selection and search are unchanged. A run drawn from several faces is printed without its text description (the parts hold its glyphs out of order).D2DResources.GetShapingFontnow also reads a face held in memory, through its loader’sIDWriteFontFileStream; installed faces are still read from disk. The WPF backend (used only without a Direct3D device) now does the same: it tries its substitute, then the same Unicode faces as the Direct2D chain, and composes a run no face has whole from installedGlyphTypefacefaces (WpfFontCache.GetCharacterFace). WPF has no system font fallback, so after the script rule it scans a fixed list of broad installed faces (Segoe UI, Segoe UI Symbol, Segoe UI Emoji, Nirmala UI, Ebrima, Gadugi, Leelawadee UI, Microsoft Himalaya, Mongolian Baiti, Microsoft Yi Baiti, Javanese Text, Myanmar Text, Sylfaen) for one with the glyph, cached per code point. Each part is drawn as its ownGlyphRunat the run’s positions, with its shaped glyphs and fitted scales. Before, the WPF backend classified such a run (its substitute lacked a glyph) and drew none of it. The choice of faces per glyph, the word kept whole and the order of the parts are engine code both backends share (Text/CharacterComposition). A CJK run that one face has whole now takes the face of its language by the same rule (CharacterFaces.WindowsCjkFamilies: CID ordering, then kana or hangul in the run, then the font’s name, else Simplified Chinese), tried after the installed font of the font’s name and the class family and before the generic Unicode faces, in the Direct2D, WPF and Skia backends. So all-Han text in a Japan1 font is drawn in Yu Gothic, in CNS1 in Microsoft JhengHei, in Korea1 in Malgun Gothic, with that language’s glyph forms (直 and 骨 differ from the Simplified Chinese forms). Before, Microsoft YaHei, the first CJK face of the chain, drew such text in every language. An installed font of the font’s name (SimSun, MS Gothic, Malgun Gothic) still wins; Latin runs and embedded fonts are unchanged. The web demo already chose the Noto slice by the same rule (Liberation has no Han, so its per-character faces draw the run); on Android the Windows names map to the Noto CJK stand-ins. Tests:CjkRunFaceTests(engine, 20: all-Han runs in Japan1, GB1, CNS1 and Korea1 fonts by family and glyph id in Direct2D and WPF; Japanese against Chinese glyphs and pixels for 直骨; the language from the font’s name, kana or hangul; an installed font of the name; a Latin run; an embedded font; the text page),CjkRunFaceTests(Skia, 8: the same with the installed fonts), andNotoFontTests.AllHanRun_TakesTheSliceOfItsLanguage(web, 5). Tests:Direct2DCharacterFallbackTests(engine, 10: the Hebrew and Devanagari run by face and glyph id, with the pre-base i sign and the ksha conjunct; its ink; Han by Japan1, GB1 and Korea1 ordering; Han ink; runs one face has; the system fallback for Ethiopic and Cherokee; a face in memory; the text page), andSubstituteShapingParityTests.MixedRun_TakesCharactersTheSubstituteLacksFromTheSameFaces(Skia with installed faces named by the same rule against Direct2D: mean 0.46 at 72 dpi, 0.20 at 144 dpi, no pixel off by more than 64);WpfCharacterFallbackTests(engine, 10: ZapfDingbats, the same faces and glyph ids in the WPF backend, Ethiopic and Cherokee from the broad faces, an Arabic word kept whole, the text page, and a mixed Hebrew, Devanagari and Han page against Direct2D with the same faces and glyphs part after part: mean 0.73, 0.28 % of pixels off by more than 64, where a WPF render of the Hebrew alone is at mean 8.2, 3.5 %).
Android reader (phase 1)
src/PdfViewer.Android(net9.0-android, no MAUI, no AndroidX, no permissions) onPdfViewer.Web.Engine: tiles for deep zoom (a whole-page bitmap of at most 2.4 megapixels, then 512-pixel tiles at the view’s scale,PageTilesandTileCache; 8x is sharp), outline list (ViewerOutline), page grid (ThumbnailGridLayout), touch text selection with the desktop’s rules ported without WPF types (ViewerTextLayout,ViewerTextSelection) and the document’s copy permission (ViewerDocument.CanCopy), sharing through the document’s own URI, recent files (persisted URI grants,RecentDocuments), restore after process death (ContinuousPageLayout.Restore). Tests:AndroidAppTests(10).- Fonts on Android: the catalog also names
.otffiles and CFF faces of.ttccollections (218 faces on the Android 13 emulator, 41.otf, 14 Noto CJK); the Windows catalog does too (see below). New text can use a CFF face (TrueTypeFontFile.TryLoad(..., openTypeCff: true)): it is embedded as a CID-keyed CFF subset (CIDFontType0,FontFile3 /CIDFontType0C, CID = glyph id of the system font, the charset maps it to the subset glyph) with only the glyphs used and the subroutines they call;Fallbacksputs TrueType faces first, CFF faces after them. CFF2 is not used for new text. Roboto’s bold comes from Android’s font manager as the variable font’s real instance (SkiaFontSource.LoadInstance; SkiaSharp 3.116 has no variation-axis API), not an emboldened regular. - Fonts on Windows:
SystemFontCatalog.InstalledreadsC:\Windows\Fontsand the user’s own font folder (%LOCALAPPDATA%\Microsoft\Windows\Fonts, fonts installed “for me only”),.otffiles and CFF faces of collections included (ForDirectoryand the newForDirectoriesscan them on every platform; names only, from each face’s table directory). Text typed into text boxes, form fields, page text and signature appearances can use an installed CFF font (Source Han Sans, Noto Sans CJK OTF, Adobe fonts):Fallbacksgives the TrueType faces first, then the CFF faces of the same families, then one face of every other CFF family by name. Those last families are fallbacks for text characters only (SystemFontCatalog.MayHaveAsFallback): never for Private Use Area characters (U+E000 to U+F8FF, planes 15 and 16: icon fonts and text converted from Symbol or Wingdings), not with a symbol-only (3,0) character map, not with a glyph that has no outline (Adobe Blank), and families named as icon, symbol, dingbat, emoji or blank fonts are left out. Fonts with CFF2 (variable) outlines only are not catalogued (new text cannot load them). A document that names a user-installed font without embedding it is now drawn with that font, not a substitute; a font file the renderer opened stays open while the app runs, so it cannot be uninstalled during use.PdfTextDocumentand signature appearances now check a face’s character map before loading it, as annotations and page text editing already did. The renderers draw an installed CFF face as it is (DirectWriteFontFaceType.Cff, WPFGlyphTypeface, Skia) and shape with its tables (openTypeCff: true). Catalog build on the development machine: about 115 ms before, 155 ms after (median of 15 runs; 423 files before, 537 with the user folder’s 114). The header/footer, Bates and watermark dialogs list CFF families too. Files over 64 MB (for example the Source Han Sans super OTC) are still skipped. - Verified on the Android 13 x86_64 emulator with adb; not yet on a phone, Android 14/15, or with pinch (adb has no two-finger gesture). Details:
src/PdfViewer.Android/README.md.
Transparency and patterns (M7)
- IR:
BeginCompositingGroup(bounds, alpha, blend, softMask, isolated, knockout)/EndCompositingGroup,PdfSoftMask(luminosity or alpha, the mask group as its own display list, backdrop colour, sampled/TR),DrawTilingPattern+PdfTilingPattern(one cell as its own display list),PushStrokeClip(pattern-painted strokes). - Interpreter: an object painted under a non-Normal blend mode or a soft mask is wrapped in a group of its own (the specified single-object result); transparency-group XObjects painted with a blend mode or soft mask become one compositing group; the soft-mask group is recorded when the ExtGState is set, with the CTM of that moment (cached per mask and CTM, depth-limited). Tiling cells are recorded once in pattern space (cached per pattern and, for uncoloured patterns, per colour; self-reference and depth are guarded); uncoloured patterns take their colour from
scn. A mask or cell that itself needs fallback keeps the whole object on the fallback path. - Direct2D: a group renders into an offscreen bitmap on its own device context; soft masks are rendered over their backdrop colour, turned into alpha with a luminosity colour matrix and
/TRvia a table transfer, and applied with an alpha-mask effect; blend modes use the Blend effect against a backdrop copied from the surface after its layers are popped (enclosing clips are re-applied to the group content), written back with a clipped source-copy. Opacity groups that contain a blend group are composited offscreen as a whole. Night mode draws the tile in true colours and inverts it with a Direct2D Invert effect (M9), because blend modes do not commute with inverting each paint. Tiling patterns rasterize one period at device resolution (every overlapping tile contributes) and fill with a wrapping bitmap brush, so the period is exact at any zoom. - WPF backend: compositing groups, tiling patterns, glyph-outline clips and two-circle radials are classified as backend regions — WPF has no blend modes. Since M9 they show what the WPF renderer draws of them (no PDFium pixels); the WPF renderer only stands in where no Direct3D device exists.
- Knockout groups (exact): each element is composited as G·(1 − f) + E − C0·(1 − f), where E is the element rendered with the current clips over C0, the initial backdrop of a non-isolated group (over nothing in an isolated group), f its shape from a shape-mode render (every paint opaque, images as their parallelogram, pattern fills as their area). An element with a blend mode therefore blends with the initial backdrop, as 11.4.6.2 specifies, and a non-isolated group inside sees it as its backdrop. Knockouts of opaque, Normal-blend elements are downgraded to ordinary groups. A knockout group with more than 256 elements (each costs two offscreen renders of the group) is drawn as an ordinary group (M9; before, a
TransparencyGroupfallback region). - Non-isolated groups (exact, at any depth): a group whose content blends (or knocks out) starts from a copy of the backdrop, and the backdrop is removed again before the group’s alpha, soft mask and blend mode apply: C = Cn + (Cn − C0)·(α0/αg − α0) (11.4.8), which premultiplied is R = Cn − C0·(1 − αg) for any backdrop alpha α0 (αg from an isolated render of the same content). The backdrop is whatever lies under the group: the page, or the partly transparent content of an enclosing isolated group, knockout element or soft-mask group. An opacity group that contains such a group is composited offscreen, so the inner group sees the enclosing group’s pixels rather than the page under an opacity layer. PDFium composites non-isolated groups as isolated and ignores knockout, so these are verified against hand-computed values from 11.4 (
CompositingTests,TransparencyGroupTests); where the features make no difference the renders agree with PDFium. - Glyph-outline clips: text rendering modes 4–7 and pattern-filled text become
PushTextClip; Direct2D unions the DirectWrite outlines of the runs into a layer mask. Type 3 glyphs add nothing to the clip and modes 3/7 draw nothing, as ISO 32000-2 9.3.6 specifies (PDFium agrees). - Radial shadings between arbitrary circles (and holed concentric ones): Direct2D evaluates the largest t per pixel (sampled at pixel centres; PDFium samples at pixel corners, a half-pixel phase difference of ≤ 3/255).
- Mesh and function shadings: types 4–7 are decoded by
PdfMeshDecoder(bit widths,/Decode, shared-edge flags, Coons interior points) and rasterized by Direct2D as Gouraud triangles, with patches subdivided at device resolution in the specified fold order; parametric meshes interpolate t and then map it through the function. Type 1 shadings sample f(x, y) at device pixels. Gradient stops are sampled at 257 points. - Still classified: nothing in these areas for valid files.
Bilevel image codecs
- CCITTFaxDecode: T.4 Modified Huffman (K = 0), mixed MR (K > 0) and T.6 MMR (K < 0) with EOL/RTC/EOFB,
/EncodedByteAlign,/BlackIs1,/Rowsand damaged-row recovery; bit-exact on Windows-encoded G3/G4 streams and a hand-coded MR stream. - JBIG2Decode: MQ arithmetic decoder, IAx/IAID, the standard Huffman tables B.1–B.15 (canonical codes checked against Annex B) and custom tables; generic regions (templates 0–3, TPGDON, AT, MMR, unknown length), refinement regions (TPGRON), symbol dictionaries (arithmetic, Huffman, refinement/aggregation, context reuse), text regions (all corners, transposition, strips, refinement, symbol-ID run codes), pattern dictionaries, halftone regions and
/JBIG2Globals. A test-side T.88 encoder produces streams that PDFium must decode identically (all cases bit-exact). - JPEG: bytes before the SOI marker are skipped, as libjpeg does.
- Text extraction: CJK fonts without
/ToUnicodemap CIDs of the Adobe collections to Unicode through the invertedUni*-UTF16-HCMaps.
Predefined CJK CMaps and JPEG 2000
- CMaps: the 59 predefined CMaps of ISO 32000-2 Table 116 come from Adobe cmap-resources (BSD-3-Clause) at a pinned commit, fetched by
eng/vectorpdf/cmaps/build-cmaps.ps1(SHA-256 per file incmaps-manifest.json) and embedded deflated (843 KB). Named encodings andusecmapchains resolve throughPredefinedCMaps; only names outside Table 116 (e.g. a collection name such asAdobe-Korea1-2, which veraPDF uses in its “fail” files) are still classified. - JPEG 2000:
JPXDecodeimages decode in the core with CoreJ2K 2.4.1 (managed, BSD-3-Clause), lossless and lossy alike: codestream dimensions and bit depths win,/ColorSpaceis optional (component count selects Gray/RGB/CMYK),/SMaskInDatatakes opacity from the extra channel,/Decodeis ignored. The SIZ marker is checked against the pixel limits before the decoder allocates; decoder failures are classifiedImageDecode(200-mutation fuzz test).
Colour management
- ICC profiles (
Color/IccProfile.cs,Color/ColorTransform.cs): a managed reader for ICC v2 and v4 profiles, with no native code or new packages. It reads the header and tag table, gray TRC (kTRC), RGB matrix/TRC (rXYZ/gXYZ/bXYZwithcurvorparacurves), andA2B0..A2B2pipelines of type lut8 (mft1), lut16 (mft2) and lutAtoB (mAB: A curves, CLUT, M curves, matrix, B curves), for 1 to 8 input channels into a Lab or XYZ PCS. PCS colours go to sRGB with Bradford D50 to D65 adaptation. CLUTs interpolate as lcms2 does (tetrahedral over the last three inputs, linear over the others), so results match PDFium’s lcms2.- The intent picks the A2B tag (absolute colorimetric uses A2B1; a missing tag falls back to another). ICCBased spaces use perceptual unless the content sets
/RI, therioperator or an image/Intent, because PDFium uses perceptual whatever the content says. - Parsing is defensive: profiles over 32 MB, more than 1024 tags, CLUTs over 4 M values, curves over 64 K entries, and any read outside a tag are rejected. A missing, broken or wrong-sized profile falls back to
/Alternateor the device space for/N(mutation test with 3 000 profiles). A profile equivalent to sRGB (within one level on a 5-point cube) passes DeviceRGB values through unchanged. - Profiles are parsed once per stream, and shared by content hash across documents (64 entries).
- The intent picks the A2B tag (absolute colorimetric uses A2B1; a missing tag falls back to another). ICCBased spaces use perceptual unless the content sets
- DeviceCMYK goes through a CMYK conversion instead of
(1 - c)(1 - k), with relative colorimetric by default, as Acrobat shows it. The conversion is Adobe’s own U.S. Web Coated (SWOP) profile when an Adobe application installed it, else a built-in model (Color/SwopApproximation.cs): a Yule-Nielsen modified Neugebauer model with dot gain, fitted to PDFium’s Adobe-like conversion (2.4 levels mean error on a 9-point grid). K 100 % is 33/30/30 (Acrobat 35/31/32), cyan 0/176/239 (Acrobat 0/174/239).SwopApproximationFit(skipped test) refits it.- The Windows RSWOP.icm profile is read correctly (within 3 levels of Windows’ own colour system) but is not used for display. It is a different characterization: cyan is 0/159/215, it is 12.7 levels from PDFium on the grid, and on the corpus it was slightly further from PDFium than the built-in model (mean 0.7491 against 0.7461). The PDF/A converter still embeds it as the CMYK output intent (shared helper
SystemColorProfiles).
- The Windows RSWOP.icm profile is read correctly (within 3 levels of Windows’ own colour system) but is not used for display. It is a different characterization: cyan is 0/159/215, it is 12.7 levels from PDFium on the grid, and on the corpus it was slightly further from PDFium than the built-in model (mean 0.7491 against 0.7461). The PDF/A converter still embeds it as the CMYK output intent (shared helper
- Default colour spaces:
/DefaultGray,/DefaultRGBand/DefaultCMYKreplace the device spaces forcs/CS, theg/rg/koperators, images and shadings (ISO 32000-2 8.6.5.6), but not inside a default space or an ICC/Alternate. PDFium ignores them for the operators, so a few veraPDF files with a/DefaultCMYKprofile now differ from PDFium by up to 0.8/255 while matching the specification and Acrobat. - Images: CMYK and colour-managed ICC images convert through a sampled grid (33-point cube for 3 channels, 17-point CMY cubes along K for 4, in linear light, then the sRGB curve); large images split across threads. The grid is within 2 levels of the exact conversion. CMYK JPEGs (Adobe-inverted or with
/Decode) are now mapped by the core for both backends, so WPF and Direct2D give identical pixels (PdfColorConversioncovers the backends’ own CMYK path). A 3-megapixel CMYK JPEG decodes in 66 ms against 76 ms with the naive formula (Release). Word export still embeds such JPEGs as they are (JpegIsSelfContained). - Separation and DeviceN alternates, Indexed bases, shadings and soft-mask backdrops convert through the same spaces, so a Separation into DeviceCMYK gets the managed CMYK. Blending is unchanged (in RGB after conversion).
- Not yet: the PDF/A output intent is not used as the CMYK default; blending in a CMYK group colour space; absolute colorimetric media-white scaling; ICC spaces with Lab or XYZ data; black point compensation.
Encryption (Standard and public-key security handlers)
PdfStandardSecurityHandler(ISO 32000-2 7.6.4): revisions 2–4 (RC4 40–128 bit; crypt filtersV2/AESV2with/StmF,/StrFand per-stream/Cryptfilters) and 5–6 (AES-256,AESV3, Algorithm 2.B hashing, SASLprep via NFKC). User and owner passwords (Algorithms 2, 4–7, 2.A); the empty user password opens owner-only protected files without a prompt.- The resolver decrypts each object read from the file (strings recursively, stream data once) with its object key (Algorithm 1); objects inside object streams are covered by their stream; cross-reference streams, the
/Encryptdictionary and — with/EncryptMetadata false— metadata streams stay plain. A missing or wrong password is a typedPdfEncryptedDocumentException { PasswordRequired }. PdfSecurityHandleris the shared base (crypt filters, Algorithm 1 object keys, RC4, AES-CBC);PdfSecurityHandler.Createdispatches/Standardand/Adobe.PubSec.- Certificate (public-key) encryption — which PDFium cannot open at all — is handled by
PdfPublicKeySecurityHandler(ISO 32000-2 7.6.5): sub-filtersadbe.pkcs7.s3,s4ands5(recipients in/Recipientsor in the crypt filter).CmsEnvelopedDatadecrypts each PKCS#7 envelope with in-box .NET only: key transport RSA PKCS#1 v1.5 or OAEP (hash from the parameters), recipient by issuer+serial or subject key identifier, content cipher AES-CBC, 3DES, RC2 or RC4. The file key is SHA-1 (SHA-256 for AES-256) of the 20-byte seed, every recipient blob andFFFFFFFFwhen metadata is plain; the recipient’s permissions are bytes 21–24. Certificates come from the CurrentUser and LocalMachineMystores (with a private key); no match is a typedPdfEncryptedDocumentException { CertificateRequired }. - Decrypted copy for PDFium:
PdfDecryptedCopyWriterserializes every in-use object of a decrypted document into an in-memory unencrypted PDF (no/Encrypt,/Cryptfilters removed, lengths recomputed, classic xref), so text search, selection, printing and annotations keep working through PDFium on certificate-encrypted files. The copy never touches disk: Save is disabled for it, file-path operations explain why they are unavailable, and Save As warns that the result is not encrypted. The writer round-trips all 2 913 corpus files (same page count, first page equal under PDFium). - Permissions enforcement (Table 22):
PdfDocumentPermissions(Abstractions) decodes/Pper revision (R2: bits 9–12 follow bits 5/6) or the recipient’s permissions; the owner password or an unrestricted recipient lifts everything. The view model refuses print, copy, export text/images, OCR text, annotate, form fill, edit/redact, organize/merge/split/extract and read aloud (accessibility bit) with an explanation; the status bar shows a lock with the restriction summary; printing without the high-quality bit is limited to 150 dpi. - The viewer passes the password PDFium accepted to the vector document, including the lazy open after an engine switch; it is held for the open document only.
- Tests: a test-side encryptor (independent writer implementation) produces RC4-40/R2, RC4-128/R3, RC4-128/R4, AES-128/R4, AES-256/R5 and AES-256/R6 files; each opens with user and owner passwords, is refused without one, renders identically to the unencrypted document and like PDFium opened with the same password, and survives mutation fuzzing. The same encryptor builds public-key files (s4 RC4, s5 AES-128/256, several recipients, SKI and OAEP recipients, restricted and unrestricted); each opens only with a recipient certificate, renders identically to the unencrypted document, and its decrypted copy opens in PDFium.
SecuredDocumentTestscover the viewer rules end to end.
Vertical writing
- Identity-V and
/WMode 1CMaps (named or embedded): each glyph’s position vector (/W2,/DW2) is placed on the current point, the point advances by W1y (TJ adjustments apply vertically), glyph Y offsets reach both backends, and selection boxes follow the column. - Sideways text in columns (UAX #50): Latin letters, digits, Greek, Cyrillic and other characters whose Vertical_Orientation is R are drawn turned 90° clockwise, reading top to bottom; U and Tu characters (ideographs, kana, Hangul, full-width forms) stay upright; Tr characters (brackets, the long vowel mark) use the font’s vertical form (GSUB
vert/vrt2) where it has one, else turn. The property comes from a compact range table compiled from UAX #50 (Editing/VerticalOrientation.cs, no data loaded at run time).
Interactive forms and digital signatures
- Forms (
Forms/): AcroForm fields read with inheritance; appearances regenerated for text, comb, multi-line, password, combo and list fields, and/ASfor buttons. Each commit is an incremental revision (Document/PdfIncrementalWriter, classic or xref-stream sections) that both engines reload. PDFium draws widgets again through a form-fill environment andFPDF_FFLDraw. The viewer puts native, accessible editors over each widget. - Signing (
Signatures/PdfSigner,PdfCmsSigner): PAdES (ETSI.CAdES.detached) as an incremental update; a new or existing field with a visible appearance; certification (DocMDP 1-3); an optional RFC 3161 timestamp through a client the caller supplies (the only network request, opt-in, sending only a hash). - Validation (
Signatures/PdfSignatureValidator), with no network: integrity over the byte ranges; the chain at the signing (or timestamp) time; timestamps; later revisions classified (signatures, form fields, annotations, metadata or other) and weighed against the certification level. The viewer shows a verdict banner and a Signatures panel. - Saving annotations on a signed document is incremental, so its signatures stay valid.
- Long-term validation:
- PAdES-B-LT adds a DSS with the certificates, OCSP responses and CRLs each signature needs.
- PAdES-B-LTA adds RFC 3161 document timestamps (
Signatures/PdfDocumentTimestamp), each covering the validation data before it. A timestamp is accepted only when it was granted, its imprint and nonce match the request, and its signature verifies. Renewal is another timestamp over the last. - Validation reports each signature’s level (B-B, B-T, B-LT, B-LTA) and when its archive timestamp needs renewing.
- A document timestamp is a permitted change at every certification level. A “timestamp” with a visible appearance is not treated as one.
- Signature appearances (
Signatures/PdfSignatureAppearance): text only, name and details, picture and details, or picture only, with a choice of details. A picture is chosen from a file or drawn in the signing dialog, kept with transparency, and remembered on the computer only if asked. Names Helvetica cannot show are set in an embedded installed font.
Password protection
Security/PdfEncryptorencrypts a document with the Standard security handler:- AES-256 (V5, R6, with /Perms) by default, or AES-128 (V4, R4); never RC4;
- an open password and a permissions password, SASLprep’d (RFC 4013) and truncated to 127 bytes of UTF-8;
- the permissions Acrobat offers: printing (none, low or high resolution), changing, copying, copying for accessibility, commenting, filling forms and page assembly;
- metadata optionally left in the clear.
- The result is a full rewrite with a fresh /ID, which PDFium opens with the password and renders the same as the original.
- Remove Security writes an unencrypted copy, but only when the owner password is known or proven. Signed documents are changed only after confirmation, because their signatures break.
- Viewer: Tools > Protect with Password… and Remove Security…, each saving a copy. Document Properties shows the security method and permissions.
Accessibility check (PDF/UA-1)
Accessibility/PdfUaValidatorchecks a document against PDF/UA-1 (ISO 14289-1), reporting each issue with its Matterhorn checkpoint, ISO clause, category, severity, how to fix it, and where (page, object, structure path such asDocument > Table > TR[2] > TD, and bounds).- Checks: tagging and the structure tree, title, the PDF/UA identifier, language, untagged content and artifacts, role maps, alternate text for figures and formulas, tables, lists, headings, fonts (the PDF/A-2u font rules under PDF/UA’s clauses, plus Type 1 CharSets), annotations, links, form fields, tab order, optional content, embedded files, deprecated structure types, encryption permissions and XFA.
- Messages never quote document text.
vectorpdf pdfuaover veraPDF’s PDF/UA-1 files: 141/141 valid files accepted, 156/156 invalid files rejected, each in the clause its name gives. The PDF/A scores are unchanged.- Viewer: Tools > Accessibility > Accessibility Check lists issues by category. Selecting an issue goes to its page and highlights the element. The window is itself accessible: automation names, keyboard use and a live summary.
- Not checked: what needs a person (reading order, contrast, whether alternate text is meaningful), annotation appearance streams, and tagging inside patterns and Type 3 glyphs.
Make Accessible (auto-tagging)
Accessibility/PdfAutoTaggertags an untagged document for assistive technology, as Acrobat Pro’s Make Accessible does. It writes a complete copy (PdfFullWriter), never over the original.- Page content: every text-showing operator, image and form XObject is put in a marked-content sequence with an MCID, and furniture is put in an
/Artifactsequence. Furniture is headers and footers that repeat at the same height on other pages, page numbers, rules, other vector graphics, full-page background images and drop shadows. The original bytes are kept: the sequences are inserted between operators. Sequences never cross the document’s own marked content, a text object’s bounds or aQthat ends their state. An/ActualTextspan is wrapped whole, because a reader takes the innermost property list. Existing artifacts are kept. Old MCIDs (when re-tagging) are taken out, in forms too. - Structure:
Document, thenH1–H6,P,L/LI/Lbl/LBody,Table/TR/TH/TD,Figure,Link,AnnotandForm, in reading order. Lines and paragraphs come fromTextBlocks, with the invisible text of OCR layers included. Reading order is a recursive XY cut on the page as displayed, so/Rotateis honoured. Bands that share a gutter that no item crosses stay one column region. Note markers, indented first lines and hanging indents join their paragraph. - Headings: by size class relative to the body text (the size most characters use), and bold where the body is not. Levels never skip, and the first heading is H1.
- Lists: two or more items that start with the same kind of label (bullets,
1.,a),(iv)), numbers in sequence, and not across columns. A label drawn by its own operator, or set apart as its own line, isLbl. - Tables (conservative): ruled grids whose every row and column line runs the whole grid, and three or more rows of single-line cells that align by column (short cells; prose is refused). Each line must sit in one cell, and no operator may draw two cells. Anything uncertain stays
P. A bold first row over a regular body becomesTHwith/Scope /Column. - Figures:
/Altis a placeholder (“Image: alternate text needs review”), or none when the option is off. A/Layout /BBoxattribute is written, and the result lists the figures for review. - Links: a
Linkelement in its paragraph, with the text it covers where the operators that draw that text draw nothing else, and anOBJR. A link without/Contentsgets its text or its URI. Annotations get/StructParentand pages get/Tabs /S. - Catalog:
/MarkInfo /Marked true,/StructTreeRootwith a/ParentTree,/Lang(an option, by default the document’s oren) and/ViewerPreferences /DisplayDocTitle true. The XMPdc:titlecomes from the document information, else from the first heading. A role map is not needed, because only standard types are written.pdfuaid:partis written only on request (ClaimPdfUa): the claim is a person’s to make. - Refusals, as a typed
PdfAutoTagStatus: already tagged (unlessRetag), encrypted without permission to change (an encrypted document that may be changed stays encrypted with its own key), a page whose content cannot be read, and no pages. As a safety check, the tagged copy’s text is compared page by page with the original’s, and a difference refuses the result (TextWouldChange).
- Page content: every text-showing operator, image and form XObject is put in a marked-content sequence with an MCID, and furniture is put in an
- Quality gate: the copy is checked with
PdfUaValidator. Each failing checkpoint is classified as human review (the PDF/UA claim, a missing title, descriptions of links, annotations and form fields, alternate text when no placeholder is written), outside tagging (fonts, encryption, XFA, optional content, embedded files) or not fixed (a gap in the tagger). The result lists them per document, with what a person should review. - Tests:
PdfAutoTaggerTests(21) on generated documents: headings, three kinds of lists, two columns drawn row by row, a title over two columns, a turned page, a ruled table, an aligned table, prose that is not a table, an image, a full-page background, a link, repeated headers and footers, re-tagging, refusals,/ActualTextand existing artifacts. Every fixture must extract the same text and draw the same pixels (WPF and Direct2D renderers, byte for byte), and leave no not fixed checkpoint. With embedded fonts and the claim, the copy passes every machine check.MakeAccessibleTests(5) cover the dialog. - Corpus (
vectorpdf autotag <dir>, one process, nothing leaves the machine, no document text printed):- GovDocs1 batch 001, the first 150 untagged files (4,726 pages): 144 tagged, 6 refused (encrypted without permission to change), 0 crashes. Text equal 144/144. Pixels equal on the first three pages 144/144. In an earlier run, one file differed once; it did not differ again in isolation (three runs) or in the next full run. The smoke now re-draws the original to tell renderer variation from a tagging change.
- Left after tagging, by documents: 06-002 (no PDF/UA claim) 144, 06-003 (no title found) 5, 28-004/28-005/28-012 (descriptions) 5. Outside tagging: unembedded or inconsistent fonts (31-008 88, 10-001 38, 31-004 21, 31-010 3, 31-030 3) and 21-001 (1). No not fixed checkpoint. 31 of 144 copies pass every machine check except the claim.
- Re-tagging the 96 tagged GovDocs files: 92 tagged, 4 refused (permissions), 0 crashes, text and pixels equal 92/92. veraPDF and Isartor, 150 untagged files: 149 tagged, 1 refused, 0 crashes, text and pixels equal 149/149.
- Found in the 144: 4,605 headings, 50,112 paragraphs, 1,308 lists, 232 tables, 6,603 figures, 1,517 links, 9,951 headers and footers, and 1,269 pages read as columns. Spot checks of table and column pages, drawn with
vectorpdf autotag-show, were right after the fixes listed above. The counts are not a measured accuracy.
- Viewer: Tools > Accessibility > Make Accessible. The dialog takes the language and the option to replace existing tags, saves the copy under a new name, and lists what was tagged, what to review and the checks that still fail. Open and Check opens the copy in its own tab and runs the accessibility check. The dialog has labelled access keys, automation names and live regions.
- Gaps (honest):
- Marked content cannot split an operator: a text operator that draws two elements goes to the first, and a form XObject is one element (that of its first text).
- Vector charts are artifacts, not figures. Captions are not linked to their figures or tables.
- Tables: no merged cells, no row headers, no
THead/TBody; a header row is found only from bold type. - Lists are flat: nesting is not found.
- Headings come from type alone: a bold one-line paragraph that ends with a full stop stays
P. - Reading order is geometric: vertical (CJK) columns, sidebars and text that wraps around pictures need review. Form fields and annotations other than links are placed at the end of their page.
- No
TOC,Note,Formulaor language spans. - Fonts are not embedded or repaired: use PDF/A conversion first.
- There is no editor for tags, reading order or alternate text yet: the copy is reviewed and finished in another tool.
Print production (separations, Output Preview, preflight)
- Separations (
PrintProduction/): the interpreter builds a plate display list (PdfVectorDocument.GetPlateDisplayListAsync). In this list, every colour is the ink it puts on one to three plates, drawn as gray or as the R, G and B channels. Any renderer then draws the plates; the engine usesDirect2DDisplayListRasterizer. Because the colour spaces are swapped, not the painting, images (JPEG and JPEG 2000 included), shadings, meshes, tiling patterns, Type 3 glyphs, form XObjects and printing annotations all separate. Soft mask groups keep their own colours, because they shape the paint and print no ink.- Ink model (
PdfInkModel): DeviceCMYK and four-component ICCBased go on C, M, Y and K as they are. DeviceGray and one-component ICCBased go on K = 1 − gray only. Separation and DeviceN colorants named Cyan, Magenta, Yellow or Black go on that process plate. A spot goes on its own plate. When the spot plate is turned off (a model without it), the spot goes through its tint transform and alternate./Allpaints every plate and/Nonepaints nothing. Indexed spaces separate through their base. - RGB, Lab and the Cal spaces: the colour is shown in sRGB first, then separated by
CmykSeparation. This is a numerical inverse of the DeviceCMYK conversion (the built-in SWOP model, or Adobe’s profile when it is installed), sampled on a 17³ grid, with a medium-GCR black and a 300 % ink limit. On a 54-colour in-gamut grid the round trip is ΔE76 0.65 on average and 2.5 at worst. It is approximate: it is not Adobe’s B2A table, there is no ICC device link and no output-intent conversion, and an ICCBased CMYK profile is assumed to be the output condition. For example, 50 % RGB gray becomes 33/26/27/33 and RGB black becomes 68/68/68/95. - Overprint:
/OP,/op(which defaults to/OP) and/OPMare tracked in the graphics state. With overprint simulation on, each plate is drawn on its own, and an overprinting object is left out of the plates its colour does not paint. In mode 1, the plates of zero DeviceCMYK (or ICCBased CMYK) components of the current colour are also left out; images and shadings are excluded, as 8.6.7 specifies. Gray and RGB paint every process plate. With simulation off, every object knocks out. Without overprint, three plates share one render, except when the page uses a non-separable blend mode. - Transparency: separable blend modes and opacity composite exactly per plate, because the plate value is the subtractive complement that 11.3.4 blends. Non-separable modes (Hue, Saturation, Color, Luminosity) are per plate, which is an approximation.
PdfSeparation: 8-bit ink planes; the ink and total ink at a pixel; coverage against a limit (maximum, pixels and fraction over, their bounds); a single plate as gray or tinted; and a composite of the visible plates (the process plates through the DeviceCMYK conversion, spots multiplied in their appearance colour, an approximation).PdfColorantInventory: the colorants the pages actually paint, found from paint events in content, forms, patterns, shadings, images and annotations. A spot defined in the resources but never used is not listed. Each spot has its pages and its appearance colour.
- Ink model (
- Preflight (
PdfPreflight, reportPdfPreflightReportin the style of the PDF/A report): pages are interpreted as they print, and every painting operation is reported (IPdfPaintObserver) with its colour space, bounds, opacity, blend, soft mask, overprint, stroke width in page points, and the image’s placed resolution and object number.- Digital printing (basic): fonts not embedded (PP-1.1, error; fonts used only for invisible text are PP-1.2, information); images under 150 ppi (PP-2.1, error) or under 300 ppi (PP-2.2, warning); RGB content (PP-3.1); total ink over 300 % (PP-4.1), measured on plates rendered at 36 dpi with overprint simulated, or per painted colour when no rasterizer is given; strokes thinner than 0.25 pt (PP-5.1, zero-width lines included); transparency (PP-6.1/6.2, information); spot colours (PP-3.3); missing TrimBox (PP-7.1) and BleedBox (PP-7.2).
- PDF/X-1a readiness: RGB (PP-3.1) and device-independent colour (PP-3.2), transparency (PP-6.1), fonts (PP-1.1), the GTS_PDFX output intent (PP-8.1), TrimBox or ArtBox (PP-7.3) and encryption (PP-8.2), all as errors. These are checks only: the report says so, nothing is converted, and passing is not a PDF/X claim.
- Findings have a page, bounds in page space and normalised bounds for the viewer, an object number (images) and a measure. There are at most 25 per rule and page; the rest are counted. The text and JSON exports carry no page text. Font and spot names (resource names) are included.
- Viewer: Tools > Print Production > Output Preview opens a window of its own, so the main view is unchanged. It has a plate checklist with swatches, Simulate overprinting, Total ink over with a limit (300 % by default) that highlights the pixels over it, and the ink of every plate and the total under the mouse. It follows the main window’s page. Hiding a plate recomposes without a new render; overprint and page changes render again. Tools > Print Production > Preflight has a profile choice and results by severity. Selecting a result goes to its page and highlights the object, and the report exports as text or JSON. Both windows have access keys, automation names and live regions.
- Tests:
PrintProductionTests(16) on generated PDFs, with exact plate values drawn by Direct2D: a spot on its plate and through its alternate, overprint in mode 1 and mode 0 and simulation off, an overprinting spot over cyan with a non-overprinting stroke, rich black (240 % and 400 %, with coverage bounds), DeviceN with a process and a spot colorant, gray as K only, RGB through the model, a Separation image, colorants inside a form, a pattern, a shading and an Indexed image (and not an unused one), the composite against the normal render (at most 1 level apart for CMYK content), the normal display list unchanged, and preflight for both profiles, with and without a rasterizer, on a clean file and with no page text in the exports.PrintProductionViewerTests(4) cover both windows and their view models. - Corpus (
vectorpdf printprod <dir> --limit 150, one process, nothing leaves the machine, no document text printed). The first 150 GovDocs1 files, 3 pages each separated twice at 36 dpi, and both profiles on up to 20 pages:- 0 crashes, 0 unreadable, 426 pages separated, 184 s in all. Separation (inventory, two separations and a reference render of up to 3 pages) took a median of 182 ms per file (p90 1.1 s, max 4.8 s). Preflight took a median of 63 ms per profile and file (p90 1.1 s, max 9.7 s).
- Sanity check: the plates mixed back (overprint off) against the normal render at the same size, with the mean and 99th percentile of the largest channel difference (0–255). CMYK-only pages (16): mean 1.2 median, 2.3 max; p99 11 median. These are the same SWOP conversion, so the difference is antialiased edges composited per plate and the 8-bit lookup table. All 426 pages: mean 2.8 median, p90 5.8, max 41.2. Gray content (264 pages) differs by design, because K 100 % shows as the dark gray of black ink (33/30/30) where the screen shows DeviceGray black as 0/0/0. RGB pages differ by the inverse’s gamut mapping. The worst file, at a mean of 41, is RGB.
- Files with spot colours: 6 (7 within 20 pages). Total ink over 300 % on the first pages: 28 files (max 400 %, per-file median 285 %).
- Findings (files / occurrences), Digital printing: fonts not embedded 98/452; images under 150 ppi 52/816 and under 300 ppi 49/2,124; RGB 108/199,130; ink over 300 % 48/111; hairlines 37/2,712; transparency 3/31; no TrimBox 138; no BleedBox 139. PDF/X-1a: no output intent 149, no TrimBox or ArtBox 138, encrypted 6, device-independent colour 2.
- Gaps (honest):
- The RGB to CMYK conversion is an approximation of SWOP only. There is no choice of output profile or simulation profile (Acrobat’s “Simulation Profile”), no device link, and no output-intent conversion. ICC CMYK goes through as it is, whatever its profile.
- The spot composite in the preview is a multiply of appearance colours, not a Lab mix. Spot plates can be turned off, which converts them to process in the engine; the viewer hides plates but has no Ink Manager.
- Pages with fallback regions are drawn by the engine’s best effort on the plates (
PdfSeparation.HasFallback). - Non-separable blend modes and soft masks are approximate per plate. Soft masks take their luminosity from the screen colours.
- The preview window renders at 1,100 pixels on the long side, and the readout is of that preview, not of the main view. There is no zoom in the preview yet.
- Preflight has no fixups, no custom profiles, no 1-bit image resolution check and no PDF/X version or validation checks. Rich black text, small text and registration colour are not checked. Total ink is rasterized at 36 dpi, so features thinner than about 2 pt are averaged.
- Overprint inside tiling pattern cells starts from the cell’s own state. A JPEG 2000 image without
/ColorSpaceseparates from its codestream components.
Printing
- Pages print through Direct2D’s print control, drawn by the same renderer as the screen, as vectors: text stays text in the spool and in Print to PDF output.
- Each page is replayed into a command list at 300 dpi. What Direct2D must rasterise (transparency groups, soft masks, pattern cells) comes out at print resolution; since M9 nothing is drawn by PDFium, and annotations print by their Print flag (NoView ones included, ones without Print left out).
- A command list has no pixels to read back, so page-level groups that composite with the page under them (blend modes other than Normal, non-isolated groups that blend or knock out) print as images of their area only. Their device rectangles are merged until none touch; each becomes a 300 dpi image of the page composited up to the group’s end, rendered by the screen path. The page is replayed in passes around the images: content before an image is clipped out of its area (the image holds it composited, so semi-transparent content is not applied twice), and content after it draws over it as vectors. Groups nested in other groups composite on their parent’s bitmap and need nothing extra. The page prints as one 300 dpi image when the areas cover more than 60 % of it or there are more than 16 of them (
PrintedPageKindVector, Mixed or Raster). A page that fails to print as vectors prints as an image of the screen rendering in the same job. - Feeding the backdrop to the Blend effect as a nested command list was rejected: XPS has no blend modes, so the print control rasterises the effect over its inputs’ full extent (the whole page so far, text included), and knockout and non-isolated groups read pixels back with copies and arithmetic composites that would all need rewriting. Images of only the areas give the same output with the screen’s verified compositing.
- The image path stays for documents that allow only low-quality printing (150 dpi), for “Print as image” (Advanced, in the print preview), and when the print control cannot be created or a vector job fails.
- Print jobs run off the UI thread, with progress and cancellation in the status bar. The preview offers fit, actual size or a custom scale, page lists (1-5, 8, 11-13), and says whether the job prints as vectors or images, and why.
Redaction
Redaction/PdfRedactorremoves content rather than covering it:- text: glyphs under a mark go, and the rest keep their exact positions through
TJadjustments; invisible text goes too; - vector fills and strokes are cut to the area outside the marks;
- image pixels under a mark are blanked in new image objects (JPEG through WIC; CCITT and JBIG2 stencils);
- form XObjects and annotation appearances are rewritten recursively;
- shadings are clipped away from the marks;
/ActualTextand/Altabout removed text are dropped;- form fields touched by a mark are removed.
- text: glyphs under a mark go, and the rest keep their exact positions through
- The output is a full rewrite: only reachable objects, no earlier revisions, and the original encryption kept.
vectorpdf redactover the 3,197-file corpus: 3,167 of 3,181 openable files clean, 0 with text left under the band, 2 malformed files refused. The viewer marks selected text, dragged areas or every search match, and applies them into a new copy.
Searchable scans
Ocr/PdfTextLayerWriteradds recognized words as invisible text (render mode 3) in a glyphless Type0 font whose ToUnicode map gives back any Unicode. Each word is placed on and stretched to its box, and follows/Rotate; it is written as an incremental update. The viewer recognizes only the pages without text (Windows OCR), shows progress and can be stopped, and makes the result searchable at once.
Editing page text and images
Editing/PdfContentEditorfinds each page’s paragraphs and images and edits them.- Paragraphs: lines are grouped with their width, line spacing and alignment (left, centred, right, justified), and line ends that are real line breaks are kept. A drop shadow (the same text drawn twice, a hair apart) is edited as one paragraph.
- Edited text:
- reflows within the paragraph’s width and alignment; a single line grows along its baseline, and a word longer than the line overflows rather than being cut;
- every character keeps the font, size, colour and spacing of the character it replaces (new characters take those of the one before them);
- lines before the first change are untouched, unchanged glyphs keep their own codes, and once the text matches the old text again the rest keeps its exact glyphs, only moved if the paragraph grew or shrank.
- Characters the document’s font lacks (subsets embed only the glyphs they used) are written in the installed version of the same font, else a font of the same kind, embedded as a TrueType subset (Type0, Identity-H, with widths and ToUnicode). Whole words switch font, never single letters.
- Kerning: glyphs that were side by side keep the spacing they had (the document’s own kerning and tracking), even when their line is laid out again. New glyphs are kerned by their font’s pair kerning (GPOS ‘kern’ pair adjustments, formats 1 and 2, also through extension lookups; else the legacy kern table): an embedded installed font by its glyphs, and a document font the way its installed original kerns (same PostScript name, or same family and style; a stand-in’s kerning is never used).
- Vertical writing (Identity-V and other vertical CMaps): columns are paragraphs, read top to bottom and right to left, and edited down the column with the font’s vertical advances. Characters the font lacks come from an installed font, set upright in the column, in their vertical forms (GSUB vert/vrt2) where the font has them; the installed font is embedded for vertical writing (Identity-V), so the column reads back as one paragraph. A column that grows continues in the next column to the left.
- Sideways runs: characters UAX #50 turns (Latin, digits and the like) typed into a column are drawn turned 90° clockwise, centred across the column and advancing down it by their horizontal widths: in the column’s own font under its horizontal CMap (Identity-H for Identity-V, a predefined CMap’s -H for its -V: same codes, same glyphs), else an installed font. Ideographs stay upright, so “PDF 2026年” sets “PDF 2026” sideways and “年” upright. A letter replacing one the document set upright (Latin in a vertical font) stays upright like it.
- Reading: horizontal glyphs drawn with a text matrix turned a quarter clockwise in the frame of a column (in the same font’s horizontal form or any other font) are read as part of that column, in reading order, when they lie on its centre line; a turned run with no column glyphs on its line stays rotated horizontal text. Edits keep an existing sideways run’s exact glyphs and baseline, and new letters next to it take that baseline. Content is written in reading order, so plain text extraction (PDFium) reads the column logically.
- Tate-chu-yoko (horizontal in vertical, JIS X 4051 and W3C JLREQ): a run of one or two half-width digits (or “!!”, “!?”, “?!”, “??”) typed between characters that are not Latin is set upright, its glyphs side by side on one baseline, centred across the column and in one em of it, so “平成12年” sets “12” in one slot. The run is in the column’s font under its horizontal CMap, the font of the unit it replaces, or an installed font (in its half-width or third-width forms, GSUB
hwid/twid, where it has them); wider than an em, it is compressed to one withTz. A single digit takes the column font’s full-width digit where it has one (marked with/ActualTextso it reads as typed), else it stands upright and centred. Longer runs, and runs next to Latin letters or spaces, stay sideways.PdfContentEditOptions.TateChuYokosets the rule:Off,TwoDigits(the default) orUpToThree. - Reading tate-chu-yoko: up to four horizontal glyphs drawn upright side by side, no wider than about an em, centred on a column’s centre line in the slot right after or before one of its upright glyphs, are read as part of the column in their own order (the slot is one em). Edits that leave the unit’s characters alone draw it again exactly as it was (moved with the column if text before it changed); a changed unit is set again as one. Plain text extraction reads it in the column’s order (“令和06年” reads 令和, 06, 年). Not done: units of letters typed in a column (they turn sideways), and producers that centre a unit far off the font’s ascent and descent middle are read only when within a third of an em of the slot.
- New characters in a composite font’s own glyphs: a one-byte code is no longer taken for a CMap that reads two, which had sent every new character in such fonts to an installed font.
- Right-to-left and cursive scripts:
- text is shaped before it is drawn: bidirectional levels and reordering (UAX #9, without explicit embeddings), mirrored brackets, Arabic joining forms, and the font’s substitutions (GSUB single, multiple and ligature lookups, and contextual and chained contextual lookups in all three formats, including extension lookups, for ccmp, isol/init/medi/fina, rlig, calt and liga);
- marks are placed on their letters’ anchors and do not advance (GPOS mark-to-base, mark-to-ligature and mark-to-mark), so vowel marks sit over and under the letters they belong to;
- cursive attachment (GPOS 3, also through extension lookups, honouring the lookup flags such as IgnoreMarks): each letter’s entry anchor is put on the exit anchor of the letter before it, along the line (advances and x offsets, for left-to-right and right-to-left runs) and across it (y offsets down the joined chain; with the RightToLeft flag the last letter of a word sits on the baseline and the earlier ones hang off it, as in Nastaliq). Marks follow their letters up and down the chain, and raised glyphs are drawn at their own height. Anchors of formats 2 and 3 are read as format 1 (contour points and device tables are not used);
- a line of right-to-left text read from a page is put in reading order, glyph by glyph, so Arabic and Hebrew paragraphs are edited as they are read and drawn again in drawing order;
- a cursive word that changed is shaped again as a whole in an installed font, because the document’s glyphs for its letters are in the forms their old neighbours needed;
- Indic scripts in new text (
Editing/IndicShaper: Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada, Malayalam), as the OpenType Indic specification and HarfBuzz shape them:- syllables, base consonants, reph and pre-base matra reordering, and the basic features with their per-glyph masks;
- final reordering, then the presentation features and GPOS (abvm, blwm, dist, kern);
- v2 script tags fall back to v1 tags.
- About 150 words across the nine scripts match Windows’ own shaping in glyph ids, and in positions to within 1.5/1000 em (Nirmala UI).
- Reordered syllables carry /ActualText, so they extract as typed.
- Indic text in existing paragraphs: a changed Indic word is shaped again as a whole in an installed font, and glyphs drawn in a short /ActualText span (a syllable or ligature, within one line) read as that text and move together when their line is laid out again, so Hindi on a page is edited in reading order.
- Moved, edited and redrawn text is drawn right after the text-showing operator it replaces, even inside a text object (the text object is split, and the text position and line start restored), so stacking and clipping stay as they were.
- Text and images inside form XObjects (to any depth up to 8) are found where each drawing of the form puts them, and edited like the page’s own. The drawing that has an edit gets its own copy of the form (a new object, with the names it inherits from where it is drawn, the fonts and images the edit added, and copies of the forms it draws), so other drawings of a shared form stay as they are. Paragraphs never span two drawings, since each uses its own resources. Content moved outside the form’s bounding box is clipped by it, as the form’s own content would be.
- Images are deleted, moved, resized, turned or replaced where they are drawn. A replacement keeps its own proportions within the old box. New text and new images (JPEG embedded unchanged; other formats lossless, with transparency) are added over the page. Results are written as an incremental update.
vectorpdf editover the 3,197-file corpus:- page 1’s longest paragraph is redrawn unchanged, then one of its words is replaced;
- 578 files edited cleanly: PDFium reads the new word back, and nothing changes outside the paragraph (575 before text inside form XObjects could be edited);
- redrawing unchanged differs on 2 files, both from JPEG 2000 logos that decode differently from run to run;
- 2 files with corrupt content streams are refused;
- the other files have no paragraph on page 1 (conformance test files, and scans whose text is an invisible OCR layer).
- The viewer’s Edit Text & Images mode (Ctrl+E):
- outlines paragraphs and images; double-click edits text in place, in its font, size, colour and alignment;
- drag moves, a drag on an image’s corners resizes it (proportionally, unless Shift is held), and the context menu replaces or turns images;
- Delete removes the selection, Add Text and Add Image place new content, and Ctrl+Z / Ctrl+Y undo and redo;
- edits are in-memory revisions saved incrementally, and editing a signed document is confirmed first.
Headers, footers, watermarks, backgrounds and Bates numbers
Editing/PdfPageMarksadds, updates and removes them, as Acrobat’s Edit PDF tools do:- headers and footers in six positions, with page number, page count, date, file name and Bates tokens;
- watermarks of text, a picture or a page of another PDF, with opacity, rotation, alignment and scale, drawn on top of the page or behind it;
- backgrounds of a colour, a picture or a PDF page;
- page ranges (all, odd, even, from–to).
- Marks read upright on rotated and cropped pages.
- Each mark is a pagination artifact in its own marked content, and each design is stored once as a form XObject with Acrobat’s PieceInfo. Update and Remove find our marks and Acrobat’s own and leave everything else as it was. The document’s own content streams are never rewritten unless they hold an Acrobat mark, and then only that sequence goes.
- The viewer’s Edit > Page Marks dialogs preview the current page, and the result is a new revision with undo.
Export to Word
Export/DocxExporter.ExportAsyncwrites a .docx package by hand (System.IO.Compression and XmlWriter, no new packages); a file export goes through a.partialfile, so a cancelled or failed export leaves nothing.- Text: paragraphs from
TextBlocks, column by column, with each run’s font, size, colour, bold and italic; subset names map to the Word family, and missing fonts get analtNameso Word substitutes a similar face. - Layout: alignment, indents, exact line spacing and space before from page positions; underline, strike and superscript from the rules and offsets around the text; headings 1-3 from tags or from larger bold lines; bullets and numbers as real Word numbering.
- Tables from tags (with spans), from ruling lines (merged cells, borders, shading) and from text aligned in columns; images inline or anchored at their page position; repeated headers and footers with PAGE and NUMPAGES fields; hyperlinks, section columns, right-to-left paragraphs and East Asian font slots.
- Page fidelity: each PDF page stays one Word page as far as Word lets it.
- Lines fit: where the font Word will use (the installed one, or the stand-in of its kind) sets a line wider than the room the page gave it, the paragraph is condensed (character spacing, then horizontal scale). Lines that start at very different places keep the page’s line breaks.
- Heights: one-line paragraphs set closer than their line height take the distance to the next line; table rows tighter than their text close the space above it, then the line height. What Word still makes taller (rows that grow, items that overlap on the page) comes out of the space after it. A page whose estimated height is over 95 % of its text area has its gaps, then its line heights, closed up.
- Headers and footers: text repeated on 20 % of the pages (at least 3) at the same place is a header or footer, and pages can differ (odd and even pages, parts, front matter). Each combination is written once, and each section uses its own, so pages without one show none. Page numbers are PAGE fields, and where printed numbers start again (A-1, chapter numbers such as 2-14, roman then arabic) a section starts with that number and format. Where body text runs into a header’s or footer’s band, that one is set in text boxes, so it takes no room from the body.
- The last paragraph of a page does not keep with the next page; tables one after another are kept apart; tables side by side become one row of a layout table.
- Contents lines: dot leaders (also a title block beside a column of page numbers) become a right tab stop with a dot leader at the number’s right edge.
- Drawings: rectangles and straight lines become Word shapes at their places (behind the text); rules and fills that are already table borders, underlines or shading are not drawn twice. Other drawings (curves, charts, maps, gradients, patterns) are grouped by what touches, and each group becomes a picture of only those drawings, made by the vector renderer at 150 dpi (
DocxExportOptions.Renderer, white left see-through), anchored behind the text in drawing order. Without a renderer they are left out. - Turned text: a text box at its place, turned as the text is, with the page’s lines and fitted to the text’s length. Pictures beside other content are anchored at their place instead of the flow.
- Text: paragraphs from
- Viewer: File > Export > Word Document (.docx), with per-page progress and cancel; drawings are rendered with Direct2D. Tool:
vectorpdf docx [--word](counts and coverage only, no document text). With--word, Word (when installed) opens each .docx read-only, lays it out and counts its pages; Word’s settings are not changed. - GovDocs (284 files): 274 exported with 0 errors (10 encrypted or empty), and Word opens all 274 without repair.
- Exact-word coverage against PDFium 98.48 % overall, in-order coverage median 99.97 % (unchanged by the fidelity work).
- Pages in Word (Word 16 on Windows, fonts installed there): 8,267 for 7,740 PDF pages (1.07 times, was 10,802, 1.40 times). Per file the median ratio is 1.000 (was 1.370); 175 of 274 files keep their page count exactly (63.9 %, was 44), 196 are within 5 % (was 57), and 11 run over 1.5 times (was 101).
- 1,663 text boxes, 52,572 shapes and 3,361 pictures of drawings, in 223 files.
- Not yet: Type 3 fonts without Unicode export no text. Fonts that are not installed are measured as their stand-in (Word may choose another). Tables cannot shrink, so a page of tall rows can still run over. Rectangles and lines inside a table are left to the table’s borders and shading.
Export to Excel and PowerPoint
- Shared with the Word export: the page reader (text runs, tables from tags, ruling lines and aligned text, images, shapes, drawings as pictures, turned text) and the package writer.
Export/OpcPackagewrites any Office Open XML package by hand (zip, content types, each part’s relationships, core and app properties);DocxPackageis now a thin layer over it. The reader puts pictures throughIExportMedia, so each format names them its own way, and an export with no use for them (Excel) does not decode them.ExportSourceopens the reader (with the structure tree when its pages match) and writes files whole or not at all through a.partialfile. Export/XlsxExporter.ExportAsyncwrites SpreadsheetML by hand (workbook, worksheets, shared strings, styles):- Layout (
XlsxExportOptions.Layout): a sheet per table (the default, “Page 3 Table 1”), a sheet per page (“Page 3”), or one sheet with every table. WithIncludeText(the default) the text outside the tables comes as rows, a paragraph a row, above and below the tables it is above and below on the page; a page with no table gets a sheet of its own. A workbook always has at least one sheet. - Cells: each table cell at its place in the grid, merged where it spans (areas that would overlap another are kept to one square, since overlapping merges make Excel repair the file). Column widths and row heights come from the PDF’s geometry, widened or heightened where the text in Excel’s font needs it, so numbers never show as ####.
- Values (
CellValues): numbers with thousands separators, decimals, a minus or parentheses for negatives, currency ($, €, £, ¥, kr) and percent become numbers with a number format that shows them as the page did ("$"#,##0.00,0.0%,#,##0;\(#,##0\)). Dates become dates when their reading is certain: ISO dates, dates with month names, and numeric dates where a day over 12 in the same column says which part is the day; 03/04/2024 alone stays text. Codes stay text: leading zeros (ZIP codes), more than 15 digits, phone numbers. - Look: font, size, bold, italic, underline, strike and colour of each cell’s main run, with rich text where a cell mixes looks; shading from fills; borders (thin, medium, thick, in their colour) from ruling lines, on the merged area’s edges; horizontal alignment from where the text sits in the cell, vertical alignment, and wrapping for cells of several lines.
- Layout (
Export/PptxExporter.ExportAsyncwrites PresentationML by hand (presentation, one master, one blank layout, theme, slides, properties, table styles):- A slide a page. The slides take the first page’s size (landscape or portrait; pages over 56 inches are scaled down to PowerPoint’s limit); pages of another size are fitted to the slide, centred.
- Text: a text box per paragraph where the page has it, its runs with their fonts, sizes, colours, bold, italic, underline, strike and superscript, the page’s line breaks and exact line spacing, alignment from its lines, right-to-left and East Asian vertical writing. Turned text is a turned text box. Links are hyperlinks.
- Tables are PowerPoint tables at their place, with merged cells (gridSpan, rowSpan, hMerge, vMerge), column widths, row heights, borders and shading. Images are pictures (turned, mirrored and cropped as on the page); rectangles and lines are shapes; other drawings are pictures drawn by the vector renderer (
PptxExportOptions.Renderer, as for Word). Shapes and pictures are behind the text. PageAsBackground: each slide’s background is a picture of its page drawn without its text, with the text over it as editable text boxes; recognized text over a scan stays see-through, as it is in the PDF.
- Viewer: File > Export > Excel Workbook (.xlsx) and PowerPoint Presentation (.pptx), with progress and cancel as for Word (one shared view-model routine runs all three exports). Tool:
vectorpdf xlsx <dir>andvectorpdf pptx <dir> [--background](counts only, no document text); with--office, Excel or PowerPoint (when installed) opens each output read-only in its own hidden instance and reports any it cannot open without repair or that has fewer sheets or slides than were written.vectorpdf officecheck <dir>does the same for files already written. No Office settings are changed, and a PowerPoint the user already has open is left alone. - GovDocs (284 files, 7,740 pages): 274 exported to each format with 0 errors (10 encrypted or empty), and Excel 16 and PowerPoint 16 open all 274 of each without repair.
- Excel (a sheet per table, with text): 8,170 sheets, 2,453 tables, 233,255 cells, of which 153,247 are numbers and 757 dates; 7,307 merged cells; 152,122 rows of text. About 16 minutes for the corpus, Excel’s checks included.
- PowerPoint: 7,740 slides with 152,122 text boxes, 18,117 pictures (images and drawings), 52,572 shapes and 2,453 tables. With the page as background (
--background), 418,533 text boxes over 7,740 page pictures, all opened without repair. - One file first needed repair in Excel: a rich-text run made only of a control character became an empty run once cleaned, and Excel rejects those; text is now cleaned before runs are made, and line breaks within a cell are kept.
- Not yet: charts are pictures, not Excel or PowerPoint charts. A table’s text that Excel cannot hold in one cell (over 32,767 characters) is cut. Lists, headers and footers are plain text boxes on slides. Character spacing and horizontal scale are not carried to slides.
Reduce File Size
Optimize/PdfOptimizersaves a smaller copy that looks the same:- a complete rewrite of what the catalog reaches, so unused objects go;
- identical fonts, images and other shared resources are stored once. Pages, annotations, fields, outline items, structure elements and layers keep their identity;
- general-purpose filters are replaced by the strongest Flate where that is smaller, and image codecs are kept;
- objects are packed into object streams with a cross-reference stream. PDF/A-1 documents keep a classic table, a 1.4 header and readable metadata;
- page thumbnails and applications’ private data are dropped;
- optionally, images shown above a resolution are downsampled to it by averaging, soft masks with them. JPEG images go through the host’s codec, and CMYK, indexed and colour-keyed images are left alone.
- Encrypted documents are reduced and stay encrypted the same way:
- objects are read through the open document’s security handler, and the copy is encrypted again with the same file key. Loose objects and object streams are encrypted; the cross-reference stream and the encryption dictionary are not;
- the original encryption dictionary is carried over unchanged: revision (R2 to R6), cipher (RC4 40 and 128-bit, AES-128, AES-256), /P, /EncryptMetadata, and /O, /U, /OE, /UE and /Perms. The first /ID string is kept, because the key of R2 to R4 derives from it;
- both passwords therefore keep working, even when the document was opened with the open password only. No password is stored or written, and messages never contain one;
- the rewrite is a change: it needs the permissions password (used to open, or given as
PdfOptimizeOptions.OwnerPassword), or /P bit 4 (changing the document). Otherwise it is refused with a clear message; - certificate-encrypted (public-key) documents are reduced the same way by the engine when the recipient may change them. The viewer only holds a decrypted copy of them, so it does not offer Reduce File Size for them;
- tests build R2, R3, R4 (RC4 and AES-128), R5 and R6 documents in-test. The copies are smaller, open with the same passwords, keep the permissions and dictionary entries, and render the same as the original in our engine and in PDFium.
- Signed documents are saved only after confirmation, because their signatures break.
vectorpdf optimizeover the 3,197-file corpus, lossless settings:- 3,176 files are rewritten, and 21 are skipped (encrypted or repaired);
- 311 MB become 266 MB (86 %), and the GovDocs files lose about a third of their size;
- PDFium reads the same text on the first pages of every file, and they render as before (checked after the JPEG 2000 fix).
- Viewer: Tools > Reduce File Size… offers the image presets and saves a copy. An encrypted document is reduced with the password it was opened with. When its permissions forbid changes, the viewer asks for the permissions password.
PDF/A
- Validator (
PdfA/PdfAValidator) for PDF/A-1b, -2b, -2u, -3b and -3u. It checks:- file syntax, including the raw header, trailers, cross-reference sections, streams, strings and names;
- implementation limits;
- output intents and ICC profiles, and device colour;
- graphics state, images (with JPEG 2000 boxes), XObjects and transparency;
- fonts: embedding, subsets, metrics, encodings, .notdef and Unicode;
- annotations, forms, actions, optional content, embedded and associated files, and permissions;
- XMP metadata against the XMP 2004 and 2005 schema tables and the PDF/A extension schema containers.
- Only resources a content stream actually uses are checked (ISO 19005-1 Cor.2). Issues are numbered by clause and test as veraPDF numbers them.
-
Scoring with
vectorpdf pdfaagainst the labelled veraPDF, Isartor and TWG files in the corpus:Flavour Valid files accepted Invalid files rejected PDF/A-1b 279/279 521/527 PDF/A-2b 399/399 605/627 PDF/A-2u 11/12 9/10 PDF/A-3b 7/7 5/5 - Converter (
PdfA/PdfAConverter) to PDF/A-1b, -2b or -3b: a full, unencrypted rewrite.- Missing widget appearances are generated from the field values, and missing annotation appearances are generated as Acrobat draws them (
Annotations/PdfAnnotationAppearances). - Fonts that are not embedded are embedded from the installed fonts. A matching family is preferred, with PostScript aliases such as Palatino to Palatino Linotype and AvantGarde to Century Gothic.
- The document’s widths are written into each embedded program’s metrics. Layout never moves, and inconsistent widths in fonts that were already embedded are repaired the same way.
- An output intent is added: a generated sRGB v2 profile, or the Windows CMYK profile for CMYK documents so their CMYK stays device colour. Default colour spaces and ICC alternates are added where needed.
- XMP is rebuilt from the valid existing properties plus the document information.
- Scripts, forbidden actions and annotations, transfer functions, OPI, PostScript and external stream data are removed, along with filters PDF/A does not allow.
- Optional content is named and ordered.
- PDF/A-3 keeps embedded files as associated files; PDF/A-2 removes them.
- Codes whose glyph the font program lacks (they draw .notdef) are taken out of the text operators of pages, forms and appearances (
PdfA/NotdefGlyphRemover). Each is replaced by a TJ adjustment, so every other glyph stays exactly where it was, and the rest of each stream is kept byte for byte. - A glyph two codes share with different /Widths is copied for one of them (
PdfA/TrueTypeGlyphCopies), and that code is remapped through the font’s cmap, private-use names or CIDToGIDMap. Both widths then hold. - PDF/A-1b:
- Transparency is flattened (
PdfA/TransparencyFlattener) when the converter is given a rasterizer (IPdfPageRasterizer; the viewer and the tool passDirect2DPageRasterizer, which since M9 draws every page itself, regions it cannot reproduce exactly by best effort;vectorpdf pdfa-convert --pdfium-fallbackstill has PDFium draw them). Without one, such documents are refused as before. Hidden layers are still refused: they would show.- Transparent objects are found by walking the content (forms included): anything drawn with a soft mask, alpha below 1, a blend mode other than Normal or Compatible, a soft-masked image, a transparent pattern or Type 3 glyphs that use transparency, and transparency groups drawn with alpha, a blend mode or a soft mask. The display list’s own transparency bounds are a check on the walker: an area it misses is added.
- Their bounds are merged into regions on the page’s pixel grid; when the regions cover 60 % of the page or more, the whole page is one region.
- Each region is drawn from a copy of the page with everything up to the last transparent object: 300 dpi, 600 dpi where text is drawn into it, at most 30 million pixels each. The image is lossless (Flate with PNG predictors, DeviceGray when grey; run-length when a blank area would compress past the 500:1 decompression guard).
- The content is written three times in one stream: what is under the images, the images, and what is drawn after the last transparent object, over them. Operators that belong to another copy keep only their effect on the state (paths end with
n, text keeps its advance in aTJ), so clipping and text positions are unchanged. Everything outside the regions stays vector, and text above transparency stays real text over the image. - Text that was itself transparent stays in its operator as invisible text (rendering mode 3), so search and copy still find it in place; opaque text under an image keeps its operator, covered by the image.
- Groups, soft masks, blend modes and alpha are removed from what remains; forms are copied per drawing when their drawing changes. Images, forms, patterns and graphics states that are no longer drawn leave the page’s resources, and so the file.
- Annotations: a translucent annotation (/CA), or one whose appearance draws transparency (a Multiply highlight), gets an image of how it looked over the page as its appearance; its comment and other entries stay. Appearances with only opaque groups or unused alpha are cleaned without an image, form field widgets included.
- The result reports the pages, regions, resolutions and renderer (
PdfAConversionResult.Flattening). Tools > PDF/A shows it in the summary and the list of changes.
- Otherwise the converter writes a 1.4 header, re-encodes JPEG 2000 as Flate, and removes optional content, embedded files and the annotation types PDF/A-1 forbids.
- It keeps or writes /CharSet and /CIDSet, and writes XMP 2004 with the preferred prefixes.
- Transparency is flattened (
- The result is validated, and anything that could not be fixed is reported.
- Missing widget appearances are generated from the field values, and missing annotation appearances are generated as Acrobat draws them (
vectorpdf pdfa-convertover the 284 GovDocs files:- 266 convert to fully valid PDF/A-2b (248 before .notdef removal and glyph copies), with no errors.
- PDF/A-1b: 256 convert to fully valid PDF/A-1b, and none are refused; 9 of them were flattened (69 pages, 84 regions, 5 annotation appearances). Without flattening, the same run gives 246 valid and 10 refused (251 were recorded earlier).
- The veraPDF and Isartor transparency files (6.4 for PDF/A-1b, 6.2.10 for PDF/A-2b; 67 files) all convert to valid PDF/A-1b. Compared through PDFium, 8 of the 6.2.10 tiling-pattern files differ: the engine and PDFium start the pattern’s tiles at different offsets, which a fine pattern shows on every pixel; the engine’s own drawing before and after flattening is identical.
- The rest are left with issues the converter cannot fix without changing the page: ZapfDingbats with no installed equivalent, symbolic TrueType fonts with an /Encoding, /C colours without an RGB intent, and damaged ICC profiles.
- Compared through PDFium, 7 converted pages differ from the original. All use fonts the original did not embed, where each reader picks its own stand-in.
- For PDF/A-1b, 3 flattened files also differ through PDFium. The flattened areas carry the engine’s drawing, and there the engine and PDFium disagree: the engine converted DeviceCMYK and ICCBased colour without colour management, so CMYK photos and K-only black differed from PDFium (001989, 001257; on 001257 the engine’s render is the same at 72, 150 and 300 dpi, whole page or windowed, so no resolution-dependent loss was found). With PDFium as the rasterizer, the same files match within about 2 %. Colour management (above) lowers the engine’s difference on these files (001257 12.9 to 8.2/255, 001989 7.6 to 4.9/255 on the corpus run).
- Viewer:
- Tools > PDF/A checks against a chosen part and level, listing each rule broken, and saves a converted copy with the changes made and anything left over; the copy can be opened.
- The status bar shows the PDF/A claim of an opened document.
Create PDF
Acrobat’s Create PDF, done on the machine: no cloud conversion, no telemetry, nothing installed.
- Writer (
Create/PdfDocumentWriter): a new document is written to the output stream an object at a time. Each page is finished before the next is given, and deflated data goes out as it is compressed, with its /Length in an object of its own, so a thousand-page scan never holds more than one picture in memory.Finishwrites the page tree, the catalog (with DisplayDocTitle when there is a title), the information dictionary (Title, Creator, Producer, dates), a classic cross-reference table and an /ID hashed from the file. Pages have a /MediaBox and nothing they do not use. - Images (
Create/PdfCreateImage,PdfImagePageLayout,PngPredictor; WIC sidePdfEngine.Vector.Windows/Create/WicImageReader,ImagesToPdf):- a JPEG that needs no change is never decoded:
JpegHeaderreads its markers (frame, components, Adobe APP14, ICC profile in APP2 chunks, EXIF orientation and resolution, JFIF density), and its bytes become a DCTDecode image. Baseline, extended and progressive 8-bit frames pass through; lossless, arithmetic-coded and 12-bit JPEGs are decoded. Adobe CMYK JPEGs get /Decode [1 0 …] for their inverted samples; - other pictures are decoded with Windows Imaging Component a frame at a time (every page of a TIFF; WebP, HEIF and the rest when their decoders are installed) and written losslessly with Flate and a PNG predictor chosen per row. 1-bit stays 1-bit, 2- and 4-bit grey stay as they are, 16-bit grey and RGB stay 16-bit, palette images without transparency keep an /Indexed palette, CMYK stays CMYK, and transparency becomes an /SMask;
- an ICC profile from the picture becomes an /ICCBased colour space when its colour space matches (written once however many pages use it); otherwise device colour;
- EXIF orientation (all eight) is applied by the image matrix, not by turning pixels, so a turned JPEG still passes through;
- options: the page fits the picture at its resolution (up to 200 inches), or goes on paper (A4, Letter, Legal; landscape for a landscape picture) inside margins, fitted or filling and cropped; greyscale; JPEG recompression at a chosen quality.
- a JPEG that needs no change is never decoded:
- Plain text (
Create/PdfTextDocument): our own layout. The bytes are read by their byte-order mark, as UTF-8 when valid, else as Windows-1252. Lines wrap at the last space that fits, tabs go to the next stop, and a form feed starts a page. The text is in Consolas (or another installed face) embedded as a subset with widths and a ToUnicode map, and characters it lacks come from the system’s fallback faces. The text is extractable by the native text service. - Combine (
PdfPageAssembler.MergewithSourceTitlesand the newPdfAssemblyOptions.Info): one outline item per source named after its file, holding the source’s own outline. Pictures and Office files become PDFs first; protected PDFs ask for their password. - Viewer (
Services/CreatePdfService,ViewModels/CreatePdfViewModel,ScanViewModel,MainViewModel.CreatePdf):- File > Create PDF > From Images, From Scanner, From File and Combine Files. The result is written beside its target and moved into place when complete, so a stopped or failed run leaves no file. It opens in a new tab;
- the From Images and Combine Files window has a file list (add, drop files from Explorer, drag to reorder, Alt+Up/Down, Delete), the options, a progress bar and Stop;
- Make Searchable runs the same path as Tools > Make Scanned Pages Searchable on every page without text (Windows OCR,
PdfTextLayerWriter), and the update is then folded into a compact file. PDF/A-2b runsPdfAConverteron the result. With neither, images stream straight to the file.
- Scanner (
Services/Scanning):IScannerService, withWiaScannerServiceover Windows Image Acquisition 2.0 through its scripting interface (WIA.DeviceManager, late bound, on an STA thread of its own). It lists scanners without connecting to them, because a network scanner that is off can take minutes to answer. Their flatbed, feeder and duplex are then read in the background. It sets intent, data type, depth and resolution, selects the flatbed, feeder or duplex feeder (or the driver’s child item for each), and transfers pages as PNG when the driver can, else in its own format, until the feeder is empty. Driver errors (empty feeder, jam, busy, offline, cover open, service stopped) become plain messages, and with no scanner it says so. Pages wait in a private temporary folder until the PDF is made. Stop does not wait for a driver stuck in a call. Tests use a fake scanner with a duplex feeder. - Office (
Services/OfficeConverter): Word, Excel and PowerPoint through COM (late bound), with each application’s own ExportAsFixedFormat (PowerPoint falls back to SaveCopyAs as PDF). The file is opened read-only, not added to recent files, links not updated, without repair, and with macros disabled (AutomationSecurityforce-disable, an instance setting). The instance is hidden, and only its own alerts are turned off. It is quit only if this conversion started it: a PowerPoint the user already has open is used and left open. Without Office, a text file uses our layout, and other types say clearly which Office application they need. - Tests:
CreatePdfTests(engine) encode pictures in-test with WIC and check page counts, sizes and turns, byte-identical JPEG passthrough (with EXIF orientation 6 and with an APP2 ICC profile), lossless PNG pixels and alpha, multi-frame TIFF with grey and 1-bit frames, palettes, greyscale, JPEG recompression, paper layout, a damaged image named in the error, PDF/A-2b conversion that validates, text layout and extraction, and combining with outline items.CreatePdfViewerTestscheck the menu and commands, a new tab, recognition (a fake recognizer, and real Windows OCR on a rendered phrase when a language is installed), PDF/A, Stop, a source never overwritten, a fake duplex feeder (7 pages over three scans), no scanner and the service stopped, text without Office, Word without Office, combining, and password-protected sources. - Office smoke test (
PDFVIEWER_OFFICE_SMOKE=1, because it starts Office): a .docx, .xlsx and .pptx made by our own exporters from a synthetic PDF convert through Word, Excel and PowerPoint 16 on the development machine. Each PDF has the text, and no Office process is left behind. - Not yet: no TWAIN (WIA only), and no scanner preview or crop. The scanner path was tested with the fake scanner and the device listing only, not with a physical feeder. Office files with an open password fail with a message; Word and Excel do not prompt, but PowerPoint may. Plain text is not shaped (Arabic joining, Indic reordering), although it copies correctly. With Make Searchable or PDF/A, and when combining, the document is held in memory while it is finished. Printing to PDF for file types Office does not open is left to “Microsoft Print to PDF”.
Measuring and stamps
Acrobat’s Measure tools and Stamp tool, written as the annotations Acrobat reads.
- Measure dictionaries (
Annotations/PdfMeasure): a rectilinear/Measure(ISO 32000-2 12.9, Table 266) with its number format arrays (Table 268:/U,/C,/FD, F, R or T,/D,/FD,/RT,/RD,/PS,/SS,/O) is read and written. A chain of formats shows a value in several units (“5 ft 3 in”), carrying a rest that rounds up to a whole unit. Distances use/Xfor x, and/Ywith/CYXfor y when given, then/Dfrom the x unit; areas use the same factors squared and/A; angles/T.PdfMeasure.FromScalemakes the measure for a scale such as 1 in = 10 ft: one point is (1/72 in) × real/paper in the real unit, in pt, in, mm, cm, m, ft, yd, km or mi. - Viewports (
PdfViewports): a page’s/VParray; a point is measured in the last viewport that contains it (12.9.2). Geospatial measures (/GEO) are flagged and not modelled. - Measurement annotations (
PdfMeasurements): a distance is a Line with/IT /LineDimension,/L,/LE [/OpenArrow /OpenArrow]and/Cap true; a perimeter a PolyLine with/IT /PolyLineDimension; an area a Polygon with/IT /PolygonDimension. Each has/Measure, the result as/Contents,/Subj(Distance, Perimeter or Area Measurement) and a/Rectthat holds the points, arrow heads and label.PdfAnnotationReaderreads/Measureand/Capback;PdfAnnotationEditorwrites them, and keeps a measure it could not model. - Appearances: the generator (
PdfAnnotationAppearances) draws the line’s caption as before, and a perimeter’s or area’s result on a white tab at the last segment’s middle or the polygon’s centroid. - Snapping (
Annotations/PdfSnapIndex): every filled and stroked path of the page’s display list, in page space (transforms applied), as segments in a uniform 24 pt grid. Curves are followed as 12 chords. A query returns the nearest end point, else the nearest middle of a straight line, else the nearest point on a path, within the tolerance (7 screen pixels in the viewer). - Stamps (
Annotations/PdfStamps,PdfStampAppearance):- the catalogue uses the names of ISO 32000-2 Table 184 (Approved, Confidential, Draft, Final, ForComment, NotApproved, ForPublicRelease, NotForPublicRelease, Expired, TopSecret, AsIs) and of Acrobat’s Standard Business set (SBCompleted, SBInformationOnly, SBPreliminaryResults, SBReviewed, SBRevised, SBVoid), plus Received. Dynamic stamps are Approved, Confidential, Received, Reviewed and Revised with a second line “By name at HH:mm, d MMM yyyy”;
- the design is our own: a rounded band in the stamp’s colour (red for refusals, green for approvals, blue otherwise) on a 12 % wash of it, an inner hairline, the label in bold capitals fitted to the box, and for a dynamic stamp a rule and the second line. Text is in the installed fonts, embedded as subsets;
- custom stamps are a picture (an image XObject with its soft mask) or a page of another PDF (its content and resources copied into the document, upright as the page is seen);
- a turned stamp is drawn upright at its own size and turned by the form’s
/Matrix; its/Rectis the turned box, so 12.5.5 fits it without distortion.PdfAnnotation.AppearanceRotationreads the turn back; - a stamp that is changed (moved, resized, its comment edited) keeps its appearance; only its rectangle changes;
PdfStamps.Previewputs a stamp on a page of its own size, on white or on black, so the viewer shows the engine’s own drawing (alpha from the two renders).
- Viewer (
ViewModels/MainViewModel.Measure,MainViewModel.Stamps,Views/MainWindow.Measure,Services/MeasureScaleStore,Services/StampLibrary):- Tools > Measure > Distance, Perimeter, Area, Set Scale and Units, Snap to Content. A click places a point; a distance ends at its second point, a perimeter or area on a double-click or Enter. Backspace takes back a point, Esc drops the measurement (again: stops the tool), Shift places a point without snapping. The canvas shows the points, a rubber band and a snap marker (square: end point, triangle: middle, circle: on a line);
- the info panel shows each segment’s length (and an area’s closing side), the total, the area, the angle of the last segment, the pointer’s x and y from the page’s top-left in the measure’s units, what it snapped to, and the scale and where it came from;
- the scale is the page’s viewport where one covers the first point, else the one set for the document, else 1 in = 1 in. A set scale is remembered per document in
%LOCALAPPDATA%\PdfViewerNative\measure-scales.json, keyed by a SHA-256 of the file’s path, so the file is not named; the last 200 are kept; - Comment > Stamp: Dynamic, Standard Business, Custom (the library), Create Custom Stamp from Picture or from a PDF Page, Remove Custom Stamp, Rotate New Stamps (0, 45, 90, 180, 270, 315 degrees) and Name on Dynamic Stamps. The name is asked for the first time a dynamic stamp is chosen and kept in
stamps.json; nothing is sent anywhere; - the stamp library is
%LOCALAPPDATA%\PdfViewerNative\Stamps: a picture is kept as the PNG or JPEG it is (after decoding it), and a PDF page as a one-page PDF of that page alone (PdfPageAssembler.Extract, without outline or form). Encrypted PDFs and files over 20 MB are refused; - a click places a stamp at its usual size (wider for a longer label), a drag gives its box (a picture keeps its shape inside it);
- measurements and stamps are
AnnotationModels (types Measurement and Stamp), so adding, deleting and changing them go throughCommandHistorylike every comment.NativeDocumentServices.IsManageddecides what the viewer reads and writes, in loading and saving alike: the earlier types, every stamp, and lines, polylines and polygons with a rectilinear/Measure. Other lines and polygons stay the document’s own; - the XFDF export writes line (
start,end), polyline and polygon (vertices) and stamp (icon) elements. PDFium mode (developer builds) does not save measurements or stamps; - one key behaviour, no new shortcut: Enter, Backspace, Esc and Shift while measuring, Esc while placing a stamp.
MenuShortcutTestsstill passes (no menu gesture added).
- Tests:
MeasurementTests(engine, 11): scales and units against hand-worked values (1 in = 10 ft, 1:1000 in mm to m, 2 cm = 5 km, 1 in = 1 mi, 1 pt = 1 pt), perimeter, area, angle,/Ywith/CYX, decimal, fraction, round, truncate, separators and label position, feet-and-inches chains, viewports (the later one wins, geospatial flagged), the measure dictionary through save and read with Acrobat’s keys, change and delete, flattening, and snapping (end points, middles, paths, transforms, closed paths, curves).StampTests(engine, 10): the catalogue, a dynamic stamp’s dictionary and two-line appearance and its pixels, a turned stamp’s matrix and pixels, a picture stamp with its soft mask, a PDF-page stamp drawn from its own resources, a moved stamp keeping its appearance, flattening, PDF/A-2b conversion (compliant, stamps kept), printing, and the preview page.StampParityTests(Skia, 2): designed and turned stamps, a picture stamp and an area measurement drawn by Skia against Direct2D (budgets: mean 2.5 and 1.5 % bad pixels for the small dynamic line, asTextParityTests.SmallBodyText; mean 1.5 and 2 % otherwise).MeasureAndStampViewerTests(viewer, 12): the measuring flow with the info panel, undo and redo, perimeter and area, snapping on a page, a viewport’s scale, the scale remembered per document (and the file not named), save and reopen of measurements and stamps (standard, dynamic, a custom picture and a custom PDF page), a reopened document saved untouched keeping its stamps, and the tools excluding each other. - Placed measurements and stamps are edited with the annotation edit layer (see “Annotation edit handles” below).
- Not yet: geospatial (
/GEO) measures,/Pathmeasurements, slope (/S) and the Acrobat comment-panel measurement details are not supported; the feet-and-inches display is read from documents but the scale dialog offers one unit; Acrobat’s own stamp artwork is not reproduced (by design).
Annotation edit handles
A placed annotation is selected and changed on the page, as in Acrobat.
- Selecting: a click on an annotation selects it (a drag over it still selects text); a double-click or Enter opens its comment; Tab and Shift+Tab go through the page’s annotations in drawing order, and past the last one Tab moves on through the window. Esc lets go.
- Handles (
Views/AnnotationEditLayer): the outline (drag to move), eight corner and edge handles, a rotation handle above a stamp as the page is seen, and a handle on each point of a measurement or of a drawing with up to 24 points. The look is the content edit layer’s. The layer is in unrotated page space at screen scale, so handles are 9 px at any zoom and turn with the page; resize cursors follow the page’s rotation. A pane automation peer lists the handles as named thumbs (“Resize handle, top left”, “Rotate handle”, “Point 1 handle”). - Geometry (
ViewModels/MainViewModel.AnnotationEditing), in the page’s points: a move keeps a box on the page; a resize keeps the opposite corner or edge (Shift keeps the proportions; stamps keep them by default, a picture always, and a stamp turned at an angle always); a drawing’s points and a markup’s line boxes scale with the box. A turn is about the stamp’s centre, counter-clockwise in default user space, snapped to 15 degrees with Shift; the box becomesPdfStamps.RotatedBoundsof the stamp’s own size. A measurement’s point snaps throughPdfSnapIndex(Shift: no snapping) and the measurement is made again withPdfMeasurements.Create, so its result (/Contents), its box and its label follow the points. Arrow keys nudge by 1 pt (Shift: 10 pt), turned back through the page’s rotation so Right moves it right on screen at 0, 90, 180 and 270 degrees. - Undo: a drag changes the model as it goes and is one
CommandHistorystep when it ends (“Move Stamp”, “Resize Ellipse”, “Rotate Stamp”, “Move Measurement Point”); Esc during a drag puts it back with nothing recorded. Each nudge and a Delete are one step. - Saving goes through
NativeDocumentServicesandPdfAnnotationEditoras before. Changed measurements, shapes, ink and markup get new appearances fromPdfAnnotationAppearances. A loaded stamp keeps its own appearance: moving or sizing it changes only/Rect(#94’s rule); turning it setsPdfAnnotation.AppearanceTurn, and the editor writes a copy of its form with the turn added to/Matrix.PdfAnnotation.AppearanceSizereads a turned appearance’s upright size back, so a loaded turned stamp keeps its own width and height. - The page while it is edited: the page renders annotations from the file, so a loaded annotation that is changed or deleted would still show where it was.
PdfVectorDocument.SetHiddenAnnotationsleaves such annotations (by object number) out of the screen display lists, not out of printing; the viewer hides every loaded annotation that differs from the file, draws the pages it touches again, and the overlay draws the changed one. A loaded stamp’s overlay isPdfStamps.PreviewOfAppearance: its own appearance on a page of its own, turned as it will be saved. Undoing back to the file’s state gives it back to the page. - Tests:
AnnotationEditEngineTests(engine, 4): a kept stamp turned through a new form with the turn in/Matrixand its pixels, the upright size of a turned appearance, hidden annotations left off the screen but printed, and the preview of a kept appearance.AnnotationEditingViewerTests(viewer, 20): move, resize (free, proportional, to the smallest size), Esc during a drag, saved and reopened shapes; a stamp resized in proportion and turned (with Shift snapping), a new turned stamp saved, a loaded stamp kept when moved and given a new/Matrixwhen turned; undo giving a loaded annotation back to the page; a measurement’s point moved, snapped and unsnapped with its result measured again, an area’s point saved and reopened with a new appearance; point handles on a small drawing and scaling of a freehand one; arrow-key nudging at 0, 90, 180 and 270 degrees; a measurement and a stamp dragged on pages turned 90 and 270 and saved; Delete and Tab; a document that forbids comments; and the layer’s handles, their size at two zooms and their automation peers. - Not yet: handles sit on the box that a turned stamp covers (its own outline is drawn dashed inside); a multi-line highlight, a note and a measurement move but do not resize; a freehand drawing’s points are not edited one by one; several annotations cannot be selected at once.
Native document services (M9)
The document-level services no longer need PDFium (PdfEngine.Vector/Services). In Auto and Vector modes the viewer uses them for properties, bookmarks, permissions, annotations, page organisation, merging, splitting and embedded files; PDFium mode keeps the PDFium path.
- Reading: document properties as FPDF_GetMetaText gives them (PDFDocEncoding, UTF-16 and UTF-8 text strings, dates), the header version, the security revision and /P as FPDF_GetDocPermissions reports it, and every page box. The outline and links resolve explicit, named (name tree and catalog /Dests) and go-to destinations, URI actions with /URI /Base, and remote and launch file names, with PDFium’s rules for malformed entries. Embedded files are listed from the name tree and from file attachment annotations; a file shown both ways is one file.
- Annotations: every type is read with its properties: subtype, rectangle, colours, opacity, contents, author, subject, unique name, dates, flags, border, ink, quadrilaterals, line, vertices, line endings, icon, free text appearance, pop-up, and replies. They are created, changed, deleted (with their pop-ups and, optionally, replies) and flattened (FPDFPage_Flatten: the normal appearance drawn into the page, links and hidden annotations kept) as incremental updates. Encrypted documents get encrypted updates. New and changed annotations get appearance streams from
PdfAnnotationAppearances. - Viewer saving: annotations the user did not touch are kept as they are, with their appearance, pop-up, replies and rich text. Changed ones keep what the viewer does not model. A signed document gets an incremental update; any other is written whole, so deleted comments do not stay in an earlier revision. Password-protected documents now save their annotations (the PDFium path reopened the copy without the password). PDFium mode now reads /CA when PDFium reports no colour (any annotation with an appearance stream).
- Pages: rotate, delete and insert blank pages in place as incremental updates; insert pages of another document (FPDF_ImportPages); extract, arrange (reorder, repeat, rotate), split and merge into new files (FPDF_CreateNewDocument). Each page takes its inherited attributes and what it uses, copied once per source. Fonts, images and other resources identical across sources are written once. Links and outline items keep working when their page is in the result: named destinations become explicit there, so no name tree is carried. Those that lead to pages left out are dropped. Merges get one outline item per source. Form fields are kept with only the widgets on the pages taken. The structure tree, document JavaScript, the open action and signature values are not carried.
- Save as copy: incremental (the current revision as it is) or a full rewrite that drops unreachable objects and keeps the document’s encryption.
Verification & tooling
InterpreterCoverageTests(fail-first fixtures per gap),DifferentialRenderingTests(PDFium oracle, perceptual budget),FuzzRegressionTests(mutation fuzzing, typed-errors-only; found and fixed two untyped escapes),HybridVectorServiceTests, plus the parallel workstreams’ stream/function/colour/font suites.eng/vectorpdf/tools/VectorPdf.Tool:bench(vector vs PDFium) andcorpus(JSONL report);docservicescompares the native document services with PDFium file by file (texts by hash only) and round-trips page edits and annotations. It sharestests/PdfEngine.Vector.Tests/Oracle/PdfiumOracle.cswith the tests.- CI runs the vector suite (2 000 fuzz iterations per PR, 100 000 nightly), the corpus report and the benchmark.
Performance
Off-screen rendering (thumbnails, printing, export, cold open) was about twice PDFium’s time. A profile of the corpus (vectorpdf perf: build, analysis, fonts, images, replay by command, Direct2D flush, readback) showed where: images decoded up to three times per render and converted pixel by pixel (CalRGB JPEGs, sRGB ICC images, CCITT fax), every glyph of every run tessellated again by Direct2D’s outline text rendering, antialiased rectangular clips composited through GPU intermediates (a table with a clip per cell), and a page buffer of megabytes on the managed heap per render (a full garbage collection every few renders). What changed:
- Text comes from a device-wide glyph atlas for body sizes (≤ 64 device pixels, plain fill): each glyph rasterized once per size and quarter-pixel position by exact area, baselines on whole pixels as PDFium places glyphs, runs drawn as sprite batches. Larger, stroked, clipping and translucent text keeps Direct2D’s outline rendering; printing keeps glyph runs as text.
- Rectangular clips take every pixel they touch, unantialiased (PDFium’s outer pixel rectangle).
- Reuse: a display list’s analysis, each image’s decode outcome (the pixels the analysis decoded go to the paint), glyph run resolution, one recoloured brush per replayer, tile surfaces across page sizes; page pixels in native memory, as PDFium’s are.
- Core (also used by the Skia backend): exact table-driven CalRGB/Lab conversion, row-wise and parallel 8-bit gray/RGB/indexed images, one decode of a soft mask, table-driven CCITT runs, a lexer without per-token builders, operands made from the token lexed, decoded forms and Type 3 procedures reused per page, the installed-font scan in parallel. Inline images are keyed by content stream as well as offset (two Type 3 glyphs with an inline image at the same offset showed the same image).
Measured on one machine (Iris Xe GPU), one process, 189 pages of a corpus sample (41 GovDocs files at up to 4 pages, 40 veraPDF files), each page from a newly opened document (vectorpdf sample), three runs each, current main against this branch:
| Per page | main median / p95 | branch median / p95 |
|---|---|---|
| Interpret (display-list build) | 2.20–2.25 / 12.7–15.7 ms | 2.50–2.72 / 13.4–14.6 ms |
| Draw, whole page at 100 % | 8.7–9.5 / 123–129 ms | 7.1–7.4 / 57–60 ms |
| Draw, 1024 × 1024 tile at 1600 % | 4.3–4.5 / 54–63 ms | 4.5–4.6 / 31–38 ms |
| Sample totals (draw 100 % / 1600 %) | 4.3–4.6 s / 2.8–3.0 s | 2.8–2.9 s / 1.6–1.7 s |
On 600 GovDocs pages the build is 15–20 % faster (median 1.71 against 1.96–2.06 ms, p95 15–17 against 20–21 ms, total 2.6–2.8 against 3.3–3.5 s); on the small sample its median is a few tenths of a millisecond slower, within the run-to-run spread of the totals. Against PDFium on the same 889-page sample (vectorpdf corpus --diff-all, 72 dpi, every page): render time 7.3 s against 7.2 s (main: 12.7 s against 7.4 s, 1.70×), and the mean difference from PDFium fell from 5.69 to 3.33/255 (worst page 15.8 to 12.9), mostly from the atlas text, whose exact-area coverage and whole-pixel baselines are what PDFium draws. A full-corpus profile before the merge with main gave a mean difference of 2.43 against 4.03/255 over 8 561 pages; its times were taken on a shared, fully loaded machine and are not quoted. The GPU round trip (about 2 ms flush, wait and copy per page at 72 dpi) remains the floor for small pages, where PDFium’s whole render takes 1–3 ms; first-page latency of small documents stays above PDFium’s for that reason.
3. Evidence
| Measure | Value | Source |
|---|---|---|
| Vector engine tests | 422 passing (13 before the second pass) | dotnet test tests/PdfEngine.Vector.Tests |
| Viewer regression tests | 371 passing (300 before; none weakened — the showcase test’s ri expectation was corrected, see §1 #5) |
dotnet test tests/PdfViewer.Tests |
| Differential vs PDFium, geometry fixtures (paths, curves, clip, dash, alpha, inline image) | mean channel diff ≤ 0.37/255, 0 % pixels off by > 64 (72 and 144 dpi) | DifferentialRenderingTests; budgets: mean ≤ 1.5, ≤ 1 % |
| Differential, axial shading | mean 1.17–1.43/255, 0 % | budget: mean ≤ 3.0, ≤ 1 % |
| Differential, Helvetica text (substituted) | mean 1.08/255, 0.49 % | budget: mean ≤ 3.0, ≤ 2 % |
| Fuzzing | 30 000 mutations clean locally; 2 escapes found and fixed | FuzzRegressionTests |
| Samples corpus | 2/2 files open in both engines; 10/11 pages fully vector; 1 page hybrid (by design); mean pixel diff 1.38 and 2.11 | eng/vectorpdf/baseline-corpus-samples.jsonl |
| First render, 450-command page, 100 % | vector 98.7 ms vs PDFium 41.0 ms (2.4× slower) | eng/vectorpdf/baseline-bench.txt |
| Render at 1600 % | vector 2 353 ms vs PDFium 1 103 ms | same |
| Where vector time goes | compile 2–14 ms; rasterization 77 ms (100 %) / 2 569 ms (1 600 %) | same |
| Cancellation observed | 8–32 ms (budget 50 ms) | same |
| Time to on-screen page (live surface) | 15.9 ms per page vs PDFium 68 ms raster at 100 % in the same run; zoom afterwards costs no re-render | vector.surface.build in baseline-bench.txt |
| Viewer tests after the Direct2D host | 320 passing | dotnet test tests/PdfViewer.Tests |
| Corpus: documents open (2 913 files) | PDFium 2 913; vector 2 913 (the 4 encrypted files now open with the Standard security handler and render fully vector, mean diff ≤ 0.29/255); 0 untyped errors | eng/vectorpdf/baseline-corpus-summary.json |
| Encryption vs PDFium | RC4 40/128, AES-128, AES-256 (R5, R6), user/owner/empty passwords: decrypted renders equal the unencrypted document and match PDFium | EncryptionTests (33), HybridVectorServiceTests |
| Certificate encryption and permissions | s4 RC4, s5 AES-128/256, multiple recipients, SKI/OAEP: only recipients open, renders equal the unencrypted document, decrypted copy opens in PDFium; Table 22 rules enforced in the viewer | EncryptionTests, SecuredDocumentTests (8) |
| Native document services vs PDFium (3 197 corpus files, all open in both) | page count, sizes and rotation 100 % (21 158 pages); outline 100 % (18 329 items); links 100 % (3 719); annotations 100 % (4 105: subtype, rectangle, contents); metadata 99.97 % (1 file, whose /Title is a stream); embedded files 99.56 % (14 files differ, each where the file’s own /CheckSum confirms our decoded data and PDFium reports raw bytes or fails) | vectorpdf docservices, NativeDocumentServicesTests (25) |
| Native round trip: rotate + delete + insert (639 sampled files) | 639 / 639 open in both engines with the expected pages; every checked page renders as its source page (PDFium mean diff 0, vector engine ≤ 1/255) | vectorpdf docservices --roundtrip 5 |
| Native annotations on corpus files (639 files) | a highlight and a square added to page 1: PDFium lists both with their rectangles and contents after the page’s own; after flattening, neither remains an annotation | same |
| Viewer annotation saves through the native services | every existing annotation round-trip test, now written natively and read back by the PDFium service; PDFium-written annotations load identically; unchanged foreign annotations keep pop-up, unique name and rich text | AnnotationFidelityTests, NativeDocumentServicesViewerTests (13) |
| Decrypted-copy writer round trip | 2 913 / 2 913 corpus files: same page count, first page mean diff ≤ 1/255 under PDFium | one-off corpus run |
| Corpus: pages with a display list or classified fallback | 100 % (3 003 pages sampled, ≤ 50 per file) | same |
| Corpus: pages fully vector / vector page area | 95.0 % / 98.67 % (before the font work: 89.2 % / 98.65 %, with embedded fonts silently substituted) | same |
| Corpus: fidelity of fully-vector pages vs PDFium (72 dpi) | median mean-channel diff 0.009/255; 12 files > 5/255 — inspected: text antialiasing on text-dense pages, no missing content | vectorpdf corpus --diff |
| Corpus: remaining fallback reasons | BlendMode 76, Pattern 53, UnsupportedCMap 37, SoftMask 17, TransparencyGroup 11, UnsupportedImageFilter 9 (JPX), UnsupportedFontType 6 (deliberately broken PDF/A “fail” samples) | same |
Direct2D vs PDFium, all 15 blend modes, luminosity/alpha soft masks (with /BC, /TR), blended and nested groups, soft-masked image |
mean channel diff 0.00–0.44/255, 0 % pixels off by > 64 | CompositingTests (25 tests) |
Direct2D vs PDFium, tiling patterns (coloured, uncoloured, rotated /Matrix, overlapping cells, alpha, pattern strokes) |
mean 0.00–1.08/255, ≤ 1.08 % off (72 and 144 dpi; at fractional cell sizes PDFium snaps cells to whole pixels, so the exact period is asserted separately) | TilingPatternTests |
| Corpus with the Direct2D backend (2 913 files) | pages fully vector 99.17 % (95.07 % before this phase), vector page area 99.72 % (98.67 %); BlendMode, SoftMask, TransparencyGroup, Shading, JPX and TextClipping 0; Pattern 53 → 2 (a degenerate YStep of −1.2·10⁻³⁸, which PDFium paints as nothing — the fallback shows exactly that); UnsupportedCMap 37 → 12 (invalid encoding names). The rest are deliberately broken fonts, unknown operators and misspelt filters in veraPDF/Isartor “fail” files | eng/vectorpdf/baseline-corpus-summary.json |
| Mesh and function shadings vs PDFium | mean ≤ 1.2/255 at 144 dpi (types 1, 4 incl. shared edges, 4-bit data and a function, 5, 6 with a shared edge, 7) | MeshShadingTests |
| CCITT and JBIG2 | bit-exact decodes; renders equal PDFium (mean 0.00/255) | CcittFaxTests, Jbig2Tests (29 cases) |
| Knockout and non-isolated groups, also nested in isolated groups and soft masks | within 3/255 of hand-computed results | CompositingTests, TransparencyGroupTests |
| JPEG 2000 vs PDFium (OpenJPEG) | mean 0.43–2.47/255 (gray without /ColorSpace, RGB, JP2 RGBA with /SMaskInData; lossless 5/3 and lossy 9/7 in all five progression orders, with tiles and 3 resolution levels); repeated and parallel decodes bit-identical |
Jpeg2000Tests |
Vertical writing vs PDFium (Identity-V, /W2, embedded WMode 1 CMap) |
mean 0.54–0.71/255 on Direct2D and WPF | VerticalTextTests |
| Glyph-outline clips and pattern-filled text vs PDFium | mean 0.10–0.18/255 | TextClipTests |
| Two-circle radial shadings vs PDFium | mean 0.9–2.9/255 (half-pixel sampling phase) | RadialShadingTests |
| Direct2D first render vs PDFium (450-command page) | faster at every zoom: 100 % 26 ms vs 35 ms, 400 % 90 ms vs 194 ms, 1 600 % 0.55 s vs 1.16 s | eng/vectorpdf/baseline-bench.txt |
| Bare CFF FontMatrix vs PDFium, both backends (Top DICT narrow, skewed, rotated, mirrored, 1/2048; CID-keyed FD only, identity Top × FD, skewed and rotated Top × FD, two FDs with different matrices, FD-matrix glyphs in a text clip; program widths without /Widths) | mean ≤ 0.05/255, 0.00 % off, no fallback | CffFontMatrixTests |
| Type 1 program widths without /Widths vs PDFium, both backends (hsbw, sbw and seac glyphs; identity, narrow, skewed and 1/2048 FontMatrix; symbolic built-in encoding; /Widths too short, with and without /MissingWidth) | mean ≤ 0.31/255, ≤ 0.12 % off, no fallback | Type1ProgramWidthsTests |
| Embedded fonts by kind (corpus) | Type 1: 11 files, max diff 0.27/255; CFF: 140 files, 0 font fallbacks; TrueType: 665 files, median diff 0.105/255 | same |
| On-screen scrolling, text document, live surface | 60 fps (p50 16.7 ms, p95 ≤ 17.1 ms) at 100–1600 %, same as PDFium bitmaps | vectorpdf live, eng/vectorpdf/baseline-live.txt |
| On-screen scrolling, path-heavy document (400 page-spanning curves/page) | uncached live: 27–41 fps at 100–400 %; with PageSurfaceCache: 60 fps at 100–400 %, p95 33 ms at 800 % (above the cache limit), 60 fps at 1600 % |
same |
4. Gate status
M0 gate (12)
- Existing solution builds. · [x] Existing tests pass. · [x] New projects compile. · [x] Engine selection is centralized.
- Baselines captured (2026-09-27, win-x64, hardware GPU):
- Package: PdfViewer.exe is 45.4 MB (framework-dependent single file, PDFium and CMaps included). Debug symbols (0.37 MB zip) and System.Speech (0.69 MB, optional Read Aloud) ship as separate release assets.
- Open and first render: a 150-page document opens in 20 ms, and its first page renders at 150 dpi in 60 ms.
- Memory (
MemoryBaselineTests): three render passes over 150 pages hold 185 / 187 / 185 MB private, and 60 open/render/close cycles add 0 MB. - These tests found a leak in the Direct2D replayer: every render kept its page-sized target bitmap, reaching 4 GB after three passes. It is fixed, and the tests now gate against it.
ReleaseManifestTestsassert that every shipped NuGet package is credited in the notices and listed in the committed SBOM.- The publish script splits symbols out of the payload and fails on any file outside its allowlist.
- “No user-visible behaviour change”: waived by decision. The first pass made
Auto(vector-first) the default, where the plan puts vector-by-default at M8. Decided 2026-09-25 by the product owner: keepAutoas the default (§6, decision 1); the deviation is accepted, mitigated by the region-safe engine and the live vector host.
Vector foundation gate (12)
- Simple vector PDF opens without PDFium parsing.
- Paths render through Direct2D (ADR-005; ADR-011 decided 2026-09-26). WPF remains the fallback renderer.
- Text renders as glyph runs, not re-laid-out Unicode (embedded TrueType/OpenType by glyph ID; otherwise positioned substitutes or classified fallback).
- Embedded raster images remain images.
- Zoom to 1600 % never scales a cached bitmap: the default host draws a Direct2D detail tile at device resolution over the page bitmap, for dense pages and in night mode too (inverted on the GPU, M9); the WPF drawing host shows a live surface except for pages over 40 000 commands, which get the Direct2D bitmap and tiles. Only PDFium-mode pages (developer builds) are PDFium bitmaps.
- Device loss: the Direct2D device is recreated and the page re-rendered from the cached display list (
Direct2D_SurvivesDeviceLoss_WithoutReparsing). - Cancellation works (observed ≤ 32 ms).
Hybrid beta gate (12)
- Corpus thresholds on the rights-cleared corpus (2 913 files): open 100 % (≥ 99.5 %), pages classified 100 % (≥ 99 %), vector area 98.67 % (≥ 95 %). The corpus is standards-conformance heavy; broaden with real-world producers before the beta decision.
- ≤ 10 % first-visible-page latency (on-screen path): surface built in ~16 ms vs PDFium’s ~68 ms raster in the same run; scrolling holds 60 fps on text and, with
PageSurfaceCache, on the path-heavy fixture up to 400 %. Off-screen rasterization (benchvector.render.*) is still ~2× PDFium, which matters only if print/export move to the vector path. - Memory ceilings enforced (display-list cache, image cache, render dimensions, per-page budgets).
- Existing viewer workflows pass.
PDFium-free release gate
Met (M10, 2026-10-18). The published app contains no PDFium and makes no PDFium call: opening, viewing, text, annotations, forms, signatures, redaction, Document Safety, Save Clean Copy and saving run on the engine (PdfiumFreeGateTests), and the release build (-p:PdfiumRenderer=false) neither references PdfEngine.Pdfium nor ships pdfium.dll (the PDFium-free release gate, releasegate pdfium-free). PDFium remains only in developer and test builds (-p:PdfiumRenderer=true, the default for dotnet build and dotnet test), as PDFium mode and the test oracle.
-
M9: native document services. Properties, page geometry, permissions, outline, links, embedded files, annotations (read, create, change, delete, flatten), page organisation (rotate, delete, insert, import, extract, arrange, split, merge) and save as copy run on the vector engine. In Auto and Vector modes the viewer uses them; PDFium mode and the fallback renderer still open the document in PDFium. Agreement with PDFium on the corpus is in §3. Left for M10: the viewer still opens every document in PDFium first (for the rendering, text and printing fallbacks), and Save Clean Copy, Document Safety, forms filling through
PdfiumFormService, comparison and OCR still use the PDFium engine. - M9: native rendering. No pixel the viewer shows, prints or exports comes from PDFium in Auto or Vector mode.
- Region fallbacks drawn by the engine. The 26 corpus pages that still had fallback regions (33 tokens) are now drawn natively, the way PDFium draws them: unknown operators ignored (5); a content stream with an unknown filter or corrupt data skipped, and “stream” followed by spaces accepted (2); an inline image with an unknown filter skipped (1); an unknown colour-space name keeps the current space (2); an unknown or unreadable CMap read as identity and the text drawn (12); embedded programs DirectWrite cannot load replaced by a substitute for their name, and substitutes missing a glyph draw the rest (3); degenerate tiling patterns (near-zero
/YStep) paint nothing (2); a JPEG whose components do not match its/Indexedspace shown in its own colours (3, the veraPDF 6-2-4-3 samples); image samples exempt from the decompression-ratio guard up to their pixel size (1, a white 1650 × 1275 scan); forms nested to 40 levels like PDFium (1). A page keeps what was drawn before a parse error or a resource ceiling, andPdfFeatureSet.Recoveredrecords that the page was drawn by best effort. Knockout groups past the 256-element compositor limit are drawn as ordinary groups. - No provider, no placeholder. With no fallback provider, a region shows what the engine draws of it; the orange outline is only drawn in strict Vector mode (
OutlineUnsupportedRegions).PdfiumRegionFallbackProviderand the ≥ 50 % full-page PDFium path are removed; a page the engine cannot read at all is a white page with an “Unreadable page” report. - Bitmaps. Night mode no longer inverts bitmaps on the CPU: Direct2D draws the tile as by day and inverts it with an Invert effect (page bitmaps, thumbnails and detail tiles; day and night share the cached replayers; exact with blend modes). Pages over 40 000 commands were already Direct2D bitmaps with detail tiles; only the WPF drawing host keeps that limit.
- Forms and annotations. Widgets are drawn from their appearance streams. Appearances are generated in memory (
PdfFormFiller.GenerateAppearance) for text and choice fields when the form has/NeedAppearances, and for widgets without/AP(check boxes and radio buttons get a ZapfDingbats check or dot when on). A widget without/ASshows the state its field value names, else Off, as in PDFium. Hidden is honoured; printing usesGetPagePrintDisplayListAsync(Print flag only, NoView included). Non-widget annotations were already drawn from their appearance streams; ones without an appearance are not generated (PDFium generates some subtypes). - Everything else. Printing (vector job and image pages,
PageImagePaginator), export to images, PDF/A-1b flattening (Direct2DPageRasterizerwithbestEffort), Compare page images, OCR page images (VectorPdfRenderer, anIPdfRendererover the engine), page-mark previews, print preview and thumbnails come from the vector engine. - Engine mode (decided). The PDFium page renderer is compiled in only when
PDFIUM_RENDERERis defined: MSBuild propertyPdfiumRenderer, defaulttruefordotnet build/dotnet test(developer and CI builds, where PDFium mode is the oracle), andscripts/build_publish.ps1publishes with-p:PdfiumRenderer=false. The published app mapsPdfium(setting orPDF_ENGINE_MODE) toAutoand hides the menu item. -
Measured (
vectorpdf corpus --diff-all, no fallback provider, Direct2D on the GPU, 3 197 files, 8 561 pages):Before M9 After M9 Pages fully vector 99.70 % (26 pages with regions) 100 % Vector page area 99.90 % 100 % Mean pixel diff vs PDFium, the 26 former fallback pages (72 dpi) 6.12/255 (placeholders) 0.08/255 (max 0.60) Mean pixel diff vs PDFium, all diffed pages 4.041/255 (fully vector pages) 4.029/255 (every page) Render time at 72 dpi, vector / PDFium (same run) 274 s / 143 s (1.92×) 338 s / 171 s (1.98×) The machine was shared with other builds during both runs, so render times are only comparable through the PDFium column of the same run; the ratio is unchanged within noise. Three veraPDF 6.9 form files differ from PDFium by up to 0.51/255 since appearances are regenerated for
/NeedAppearances(PDFium’s page renderer draws the stale ones). Untyped errors: 0. - Tests:
NativeRenderingTests(damaged streams, unknown filters and colour spaces, CMaps, unloadable fonts, mismatched JPEGs, deep forms, a region without provider drawn natively and outlined only in strict mode, night tile = inverted day tile with a blend mode, generated widget appearances, Print/NoView), the updated fallback tests, and viewer tests for the night bitmap, exported images and the engine-mode flag. - Left for the gate: PDFium still serves text extraction and search (and the services listed below), so
pdfium.dllis still published; images the engine cannot decode at all (the showcase’s damaged JPEG) are left out where PDFium may draw part of them.
- Region fallbacks drawn by the engine. The 26 corpus pages that still had fallback regions (33 tokens) are now drawn natively, the way PDFium draws them: unknown operators ignored (5); a content stream with an unknown filter or corrupt data skipped, and “stream” followed by spaces accepted (2); an inline image with an unknown filter skipped (1); an unknown colour-space name keeps the current space (2); an unknown or unreadable CMap read as identity and the text drawn (12); embedded programs DirectWrite cannot load replaced by a substitute for their name, and substitutes missing a glyph draw the rest (3); degenerate tiling patterns (near-zero
- M9: native text. No text the viewer searches, selects, copies, reads aloud, exports, compares or checks for OCR comes from PDFium in Auto or Vector mode.
- Text page (
PdfEngine.Vector/Text).PdfTextExtractor.LoadPagebuilds aPdfTextPagefrom the page content:TextContentReaderreads text objects the way PDFium’s content parser builds them (one per text-showing operator, kerning items between TJ strings, single-precision positions, glyph ink boxes, marked content, form XObjects with their own CTM,gs/Font, strings cut at 32 767 bytes, no text before a font is set), andPdfTextPageapplies CPDF_TextPage’s rules: objects ordered along each line, overprinted bold dropped, spaces from TJ gaps, character spacing and object gaps (with PDFium’s thresholds),\r\nbetween lines, line-end hyphens (U+0002,IsHyphen), U+FB00–FB06 split into pieces, /ActualText in place of its glyphs, right-to-left runs reversed and mirrored, invisible text (3/7 Tr) kept. Boxes are in default user space: the tight box from the glyph outline (embedded TrueType placed at its hmtx side bearing as FreeType does, CFF/Type 1 control boxes from the charstrings, Type 3 /d1, an installed system face found by name for fonts that are not embedded), the loose box from the font’s ascent and descent through the text matrix. Search (PdfTextFind) ports CPDF_TextPageFind (words across spaces and line breaks, CJK characters one by one, match case, whole word). - Unicode as PDFium reads it.
ToUnicodeReaderreads /ToUnicode with PDFium’s rules (a section counts only with exactly its declared entries; ranges stay inside a 256-code block; four hex digits per unit; the smallest mapping wins).SimpleFontUnicodefollows PDFium’s simple-font loaders: the base encoding from the flags, name and /Encoding (WinAnsi’s undefined codes read as bullets), /Differences and base names through the glyph list (ZapfDingbats a-names, Adobe private-use names, Cyrillic and Hebrew afii names), a symbolic program’s built-in encoding, Mac Roman for symbolic TrueType programs, nothing for Type 3 names. Composite fonts read /ToUnicode or a Unicode CMap only (PDFium as built here has no CID-to-Unicode tables). - Services and viewer.
PdfVectorTextServiceimplementsIPdfTextService(segments, page text, search with the PDFium service’s normalization and padding); a PDFium-opened document is read through an attached vector document.PdfStructureTreebuilds the per-page structure tree as FPDF_StructTree_GetForPage does. InHybridVectorDocumentServicesearch, word segments, the selection layout (PageTextLayout) and the tagged reading order (screen reader, read mode, read aloud) come fromNativePageText; Export Text, Compare (PdfComparisonService), the OCR text-layer check and Make Searchable usePdfVectorTextService. PDFium mode keeps PDFium’s text; Auto mode reads text with PDFium only if the vector engine cannot open the file at all. -
Measured (
vectorpdf text <dir>: native against FPDFText_* on every page, 4 sampled words per page searched with no options, match case and whole word; the report holds counts and file names only):Corpus Pages Same text, white space collapsed Same character count Search hits equal Char box IoU (mean / ≥ 0.9) Loose box IoU (mean / ≥ 0.9) GovDocs1 001 (284 files) 8 201 (8 087 with text) 99.95 % 99.55 % 99.78 % of 96 411 0.991 / 97.1 % 0.967 / 83.4 % veraPDF + Isartor (2 906 files) 12 949 (875 with text) 99.88 % (98.29 % of pages with text) 99.79 % 99.31 % of 6 342 0.998 / 99.9 % 0.997 / 99.4 % PDF 2.0 examples (7 files) 8 100 % 100 % 100 % 0.999 / 100 % 0.969 / 82.0 % Overall 21 158 pages, 19 differ after collapsing white space (99.91 %; 99.79 % of the 8 969 pages with text). The rest, by cause: veraPDF/Isartor font test files built to fail (.notdef glyphs, missing glyphs, a one-byte code read against a two-byte code space, a CID font without /ToUnicode; 15 pages), a line-end hyphen and two spaces decided differently between glyphs whose boxes come from a substitute face or an embedded font with odd metrics (4 GovDocs pages). Search hits differ mostly where a sampled word meets those spaces. Box differences come from non-embedded fonts: PDFium draws the standard 14 with its own Foxit faces, the engine measures the Windows core fonts. The parity run was repeated after the speed work below with the same numbers in every column.
-
Speed (
vectorpdf textbench <dir>: the first text load of every page, nativePdfTextExtractor.LoadPageagainst FPDF_LoadPage + FPDFText_LoadPage, cold on a freshly opened document and warm with the page cache dropped; same machine, runs interleaved; GovDocs1 001, 8 201 pages):ms per page Before (median / p95 / mean) After PDFium, same run Cold first load 3.92 / 19.5 / 6.64 (PDFium 3.77 / 12.3) 1.19 / 5.70 / 1.89 2.46 / 7.77 / 3.18 Warm (fonts ready) 3.18 / 12.2 / 4.64 1.00 / 2.94 / 1.28 2.14 / 5.74 / 2.62 First page of each file (fonts set up) 5.87 / 30.5 / 15.7 2.38 / 11.3 / 3.98 6.47 / 17.2 / 7.81 Whole-document search (
vectorpdf textsearch, every page loaded and searched on a fresh document): 357 pages 929 → 436 ms (PDFium 615), 345 pages 1 508 → 663 ms (PDFium 1 216), 303 pages 853 → 525 ms (PDFium 893). Allocations over the benchmark fell from 37.5 GB to 8.9 GB and GC pauses from 17.2 s to 3.8 s. What it took (profiled with dotnet-trace and allocation ticks): the content walk read every token throughPdfLexer/PdfParser(a string per token, each number lexed three or four times);TextContentLexerreads operands from the bytes and leaves dictionaries and unusual arrays to the general parser (TextContentLexerTestschecks it against the former reading). Characters are values in 512-entry chunks (they were two objects each). Unicode, widths and glyph boxes are kept per code, the missing-font substitute once per document, the installed-font index is read in parallel in the background, and forms drawn several times are decoded once. Every native text page of the three corpora hashes the same before and after (vectorpdf texthash). The cache keeps pages within 400 000 characters (at least 8) instead of 8 pages, andPdfTextExtractor.Prefetchbuilds a drawn page’s text on a low-priority thread (bounded queue, dropped byInvalidateor closing, never waiting while a page builds); the viewer prefetches every page it draws, so selection on a visible page does not wait. - Tests:
NativeTextTests(words, kerning and spacing; ToUnicode ligatures; /ActualText; rotated page with a crop box offset and rotated text; Identity-V; Type 3 with and without /ToUnicode; invisible text; form XObjects; hyphens; overprinted bold; ExtGState font; rejected ToUnicode sections; search options; the service’s segments and search againstPdfiumTextService),NativeTextViewerTests(search, segments and layout at 0/90/180°, tagged reading order againstPdfiumDocumentService). - Left:
PdfiumDocumentServicekeeps its FPDFText path for PDFium mode (developer builds); for OCR the recognizer still draws pages with the renderer it is given; the non-embedded face metrics differ from PDFium’s built-in Foxit faces.
- Text page (
- M10: native services. In Auto and Vector modes nothing the viewer does opens a PDFium document or initialises the library.
- Opening (
HybridVectorDocumentService). The engine opens the file: a missing or wrong password raisesPdfPasswordRequiredException(the viewer prompts again), certificate-encrypted files open with the user’s certificates and work on an in-memory decrypted copy, damaged cross-reference data is rebuilt, and permissions come from the engine’s security handler. A file the engine cannot read is an error, not a PDFium fallback. PDFium is created lazily from the revision in memory, only in PDFium mode; the app no longer initialises PDFium at startup. - Forms (
PdfFormService).IPdfFormServiceon the engine: one model per widget in/Annotsorder with full names, kinds (push button, check box and radio told apart), values, options, flags and the widget’s check state; values set with appearances regenerated (PdfFormFiller) as one incremental update (a damaged file is rewritten whole first); field rules and calculations in/COorder asPdfFormScriptsrecognises them (no JavaScript is executed; custom scripts still get the “filled as typed” notice); reset to/DV; XFDF (nested names, as Acrobat writes it) and FDF export and import, told apart by content, unknown and read-only fields skipped and reported; flatten draws every visible widget into its page (generated appearance where the form asks for one, else its own for its state), removes the fields and writes the file whole. The viewer’s Fill Form Fields dialog fills the open revision in memory (it used to write a PDFium copy), and Tools gets Import Form Data, Export Form Data, Reset Form and Flatten Form. On-page editing (FormFieldsLayer,FormSession) was already native. - Signatures (
PdfSignatureService).IPdfSignatureServiceonPdfSignatureValidator. Signing (PdfSigner) and validation in the viewer were already native;PdfiumSignatureServicestays as the oracle inSigningTests. Status follows PDFium’s verifier (intact over the whole file: Valid or Untrusted by chain; bytes changed: DocumentModified; not a signature: Invalid), except that a later revision the signature permits keeps it Valid/Untrusted where PDFium says DocumentModified. - Redaction (
PdfRedactionService).IPdfRedactionServiceonPdfRedactor(the viewer already redacted natively): pending areas per document, normalized areas mapped to the crop box, written to a new file. - Document Safety (
PdfSafetyInspector). ThePdfiumSafetyInspectorreport from the engine’s parse:/JavaScriptname tree,/EmbeddedFilesname tree, security revision, URI and launch link actions on the first 50 pages (same limitation note). It also finds what PDFium’s API does not: scripts and launch actions in the open action, document, page, field and annotation event actions, annotation actions and/Nextchains, so its counts are never lower. - Save Clean Copy (
PdfSanitizer). Form fields are flattened into their pages (they stay visible, as in PDFium’s copy), then only the pages go into a new document (no outline, form, name trees, open action, document actions, information dictionary or XMP metadata). Launch, remote (GoToR/GoToE) and unrecognised link actions, media and file attachment annotations, every/AA, and annotation actions are removed (newSanitizedContentKind.TriggeredAction); pop-up parents and reply targets of removed annotations are cut so nothing removed stays reachable. Only reachable objects are written. The copy is re-opened and inspected; a copy that is not clean is deleted. Hidden layers stay hidden (the optional-content configuration is kept). - Everything else. Compare (window and report) and Recognise Text open the documents in the engine (
VectorPdfRenderer,PdfVectorTextService); Document Safety and Save Clean Copy use the native services. Organise, merge, split, extract and embedded files were already native. ThePdfiumEnginecall sites left inMainViewModelare all PDFium-mode branches. - Gate test.
PdfiumGuard(PdfEngine.Pdfium) is passed by every call that creates a PDFium document (FPDF_LoadDocument,FPDF_LoadMemDocument,FPDF_CreateNewDocumentin both bridges), byPdfiumEngineand byPdfiumDocumentService.PdfiumGuard.Disabled(orPDF_PDFIUM_DISABLED=1) refuses PDFium process-wide;DisableInThisFlow()refuses it for one asynchronous flow and records every attempt, even one a caller catches.PdfiumFreeGateTestsopens (plain, encrypted with a password prompt, damaged), renders, searches, extracts words, selection layout and read-mode content, annotates and saves, makes a clean copy, redacts, fills a form, exports and imports XFDF/FDF, resets, flattens, signs and validates, all in Auto mode with PDFium disabled: no attempt is recorded. - Measured (
vectorpdf services <dir>, 3 197 files, all opened by both): forms on 81 files with widgets, 116 widgets: 97.4 % agree withPdfiumFormService(page, rectangle where both normalize alike, partial name, own value, check state); the 3 that do not are widgets outside the form’s field tree (veraPDF 6-1-12-t01, PDF/UA-2 8.10.2.3-t01), which PDFium lists and the form model does not. Safety: 100 % of files agree kind by kind (external links 67 files, encryption 14, embedded files 55, launch actions 6, scripts 18; launch and script counts are at least PDFium’s: two Isartor files have launch actions outside links). Clean copies: 3 197 of 3 197 (every file,--clean 1) clean forPdfiumSafetyInspectorwith the same page count. The report holds counts, kinds and file names only. - Tests:
NativeFormsAndSafetyTests(field list againstPdfiumFormService, values PDFium reads back, refusals and validation, calculation order, XFDF/FDF round trips and a third-party FDF, reset, flatten drawn as the filled form, safety report againstPdfiumSafetyInspector, clean copy inert for both inspectors with the link kept, counts at least PDFium’s, refusal and discarded copy, signature status againstPdfiumSignatureServiceintact and tampered, redaction),PdfiumFreeGateTests. - Left: widgets outside the field tree are not modelled; PDFium mode keeps every PDFium path (it is the oracle). (
pdfium.dllleft the publish in “M10: PDFium-free release” below.)
- Opening (
- M10: PDFium-free release. The items of the gate (12_ACCEPTANCE_AND_RELEASE_GATES):
- Parser/open success on the full corpus. 3 197 of 3 197 files open in the engine (§3;
vectorpdf services, M10 above). - No fallback to PDFium in production. There is no PDFium in the production build to fall back to: no page, region, text, service or open path reaches it (M9, M10 above).
- Every feature that called PDFium has a replacement path. Rendering, printing and export (M9 native rendering), text (M9 native text), document services (M9), opening, forms, signatures, redaction, safety and clean copies (M10). In the viewer, every PDFium code path is behind
#if PDFIUM_RENDERER:PdfiumDocumentService,PdfiumNativeBridge,PdfiumFormEnvironment, the PDFium-mode branches ofHybridVectorDocumentServiceandMainViewModel(forms, Document Safety, Save Clean Copy, organise, merge, split, embedded files) andPdfDocumentServiceFactory; the engine-mode menu hides PDFium mode andCurrentEngineModemaps it toAuto. The XFDF export and PDF date helpers the native services used moved toAnnotationExchange. A-p:PdfiumRenderer=falsebuild compiles with no PDFium type, and publishes from a tree withoutsrc/PdfEngine.Pdfium,eng/pdfiumorpdfium.dll(checked 2026-10-18). One behaviour differs from developer builds: a document the engine cannot parse at all has no text there (developer builds read it with PDFium). - Encrypted documents. RC4 and AES up to 256-bit, user and owner passwords, certificate encryption, permissions (Encryption, Password protection above;
PdfiumFreeGateTests.OpeningEncryptedAndDamagedFiles_NeverReachesPdfium). - Annotations, forms, save, page organisation, signatures, redaction. Native (M9, M10 above), and run with PDFium absent by the PDFium-free test job (below).
- PDFium DLL absent from the publish output.
PdfViewer.csprojreferences PdfEngine.Pdfium and copiespdfium.dllonly under'$(PdfiumRenderer)' == 'true'(ReleaseManifestTests.TheApplicationProject_ReferencesPdfiumOnlyInPdfiumBuilds).releasegate pdfium-free(run by everyscripts/build_publish.ps1, so by CI and the release workflow) fails a payload with apdfium*.dllorPdfEngine.Pdfiumloose, bundled inPdfViewer.exe, named by a.deps.json, or extracted at run time; on the same source published with PDFium it reportsPdfViewer.exe!pdfium.dllandPdfViewer.exe!PdfEngine.Pdfium.dll. eng/pdfiumnot required for the production build. The publish above built without it.- The installer does not package PDFium. Its payload is the checked folder (
Payload.zipofpublish/app). - SBOM without a production PDFium component.
scripts/generate_sbom.ps1describes the published build (restored withPdfiumRenderer=false): first-partyPdfEngine.Abstractions,PdfEngine.Vector,PdfEngine.Vector.Windows,PdfEngine.Vector.Direct2D,PdfViewer.Core, Adobe cmap-resources and the 12 NuGet packages; nopdfium.dll,PdfEngine.Pdfiumor the libraries inside PDFium (FreeType, libjpeg-turbo, libpng, zlib, OpenJPEG, Little-CMS, ICU, abseil, AGG, fast_float, simdutf).ReleaseManifestTests.TheCommittedSbom_ListsNoPdfium. - Third-party notices updated.
THIRD_PARTY_NOTICES.mdcredits what ships and no longer PDFium; the MIT text it used to borrow from PDFium’s section is its own section. PDFium’s licences stay ineng/pdfium/for developer builds.ReleaseManifestTestswalks the restore graph from the application’s references without passing through PdfEngine.Pdfium, so it checks the PDFium-free build’s packages whichever configuration was restored. The About box, Privacy & Safety text, installer and status bar no longer name PDFium. - The app starts and works with PDFium disabled.
releasegate pdfium-freelaunches the published app withPDF_PDFIUM_DISABLED=1; its--startup-probe ... --searchrun (2026-10-18): page 1 drawn at 3 940 ms, “Startup probe” found 12 times on 12 of 12 pages, no PDFium assembly or module in the process, renderer not compiled in. -
Measured (2026-10-18, developer workstation, same source published with and without PDFium):
With PDFium (origin/main) PDFium-free Change Payload 38.55 MiB 31.46 MiB -7.10 MiB (-18.4 %) Payload compressed (what the installer carries) 13.24 MiB 9.64 MiB -3.60 MiB (-27.2 %) Bundled in PdfViewer.exe21 files 19 files pdfium.dll(6.93 MiB) andPdfEngine.Pdfium.dll(107 KiB) goneWarm start to page 1, median / p95 (15 launches) 2 553 / 2 742 ms 2 430 / 2 593 ms -4.8 % Cold start to page 1, median / p95 (3 launches) 3 126 / 3 581 ms 3 038 / 3 082 ms -2.8 % PdfViewerSetup.exeis 9.89 MiB (10 372 293 bytes); the previous baseline (2026-09-27, with PDFium and less engine) was 12.95 MiB, and the payload 37.11 MiB. Both baselines ineng/releasegatewere refreshed from these runs (payload and installer from the full build, startup from the PDFium-free run). - Tests.
dotnet test tests/PdfEngine.Vector.Tests: 1 064 passed, 1 skipped (the SWOP fit tool).dotnet test tests/PdfViewer.Tests(developer build, PDFium oracle included): 587 passed.dotnet test tests/PdfViewer.Tests -p:PdfiumRenderer=false(the published configuration, a new CI step): 357 passed at M10, 586 of the 713 developer-build cases since the oracle tests were ported (2026-10-18, below); it builds intobin\nopdfiumandobj\nopdfium(Directory.Build.props), so it cannot pick up the developer build’s PDFium files. Test files that need PDFium are listed by name asPdfiumOnlyTestinPdfViewer.Tests.csproj(one file since the oracle tests were ported:PdfiumFormRenderingTests, which tests the PDFium form-fill adapter itself; it was 17 at M10) and left out of that build, the list and each file’s reason are written to the CI job summary, andPdfiumFreeConfigurationTestschecks that each listed file exists and has a reason; single PDFium tests in otherwise PDFium-free files are behind#if PDFIUM_RENDERER, and where a PDFium read-back checked the result, the PDFium-free build reads it back with the engine. In that buildPdfiumFreeGateTestsfails a test if any PDFium assembly or module is in the process, andPdfiumFreeConfigurationTestschecks that PdfEngine.Pdfium cannot be loaded, that no*pdfium*file is beside the tests and that PDFium mode isAuto.
- Parser/open success on the full corpus. 3 197 of 3 197 files open in the engine (§3;
5. Remaining work, in priority order
- Live host tuning, remainder: done for deep zoom. A page-spanning path is tessellated only in a window around the requested tile: curves crossing the window are split, strokes cut, and fills closed along the window’s edge, so every pixel inside is unchanged. A zoom step starts preparing the visible tiles’ tessellations at once, while the previous tile stays on screen stretched. On the 400-curve fixture, the first tile at 1600 % went from 0.4–0.67 s to about 0.25 s (p50), and zoom request to crisp tile from about 0.33 s to 0.16 s. Page bitmaps still take the readback path; they are cached and reused. Geometries smaller than 1,024 device pixels are drawn directly rather than realized: building thousands of realizations (001767.pdf p2, a map of 9,381 small symbols) cost 20–80 s for the first tile at a new zoom, where drawing them costs milliseconds, and a realization of a shape that fits a tile or two is rarely drawn twice. Over the 20 heaviest GovDocs pages, the worst first tile (p95) went from 49.6 s to 1.0 s at 1600 % and from 81 s to 1.4 s at 800 %.
- Real-world corpus: GovDocs1 batch 001 (284 US-government PDFs) is in the corpus (3 197 files; pages fully vector 99.64 %, area 99.90 %). The font and image gaps it exposed are closed (CFF FontMatrix normalization and glyph matrices, substitute fallback chains, CCITT/JBIG2/JPX masks, JPEGs through their colour space): GovDocs pages fully vector 97.39 % -> 99.46 %. Next: more batches, CAD and scanned books; the residual high-frequency diffs on scanned grids are resampling, not errors.
- Remaining font coverage: a CFF FontMatrix that is singular is still refused (classified). (Done: a Type 1 (
FontFile) simple font without /Widths now advances by its program’s hsbw/sbw widths through its FontMatrix, as PDFium does;Type1ProgramWidthsTests.) - Transparency remainder: done for non-isolated groups over transparent backdrops (inside isolated groups, knockout elements and soft masks) and for blending elements of non-isolated knockout groups. Printing such pages keeps everything outside the groups’ areas as vectors (see Printing). Left: JBIG2 colour extension and 12-pixel extended templates. Colour management is done (see Colour management); left there: the PDF/A output intent as the CMYK default and blending in CMYK group spaces.
5a. PDF/A-1b flattening remainder:
- Flattened areas are DeviceRGB; on a CMYK document they get the sRGB default space, not CMYK pixels for its CMYK output intent.
- Text in a transparent Type 3 font keeps only its advance (Type 3 glyphs ignore the rendering mode), so it is not searchable.
- Still refused: form field widgets that are translucent or whose appearance draws transparency, translucent annotations without an appearance stream (the converter generates theirs afterwards), and translucent annotations with NoZoom or NoRotate. Over the whole veraPDF and Isartor corpus (2 906 files), these are the 13 PDF/A-1b refusals left; 165 files are flattened, and none fails with an error.
- The copy over the images repeats marked-content operators, so MCIDs appear twice on flattened pages (no matter for PDF/A-1b; it would for PDF/A-1a or PDF/UA).
- (M9) Pages are no longer drawn by PDFium when flattening, so its buffer limit on very large pages at 600 dpi no longer applies.
- Real-world corpus: the rights-cleared corpus is conformance-heavy; add scanned, CAD and publishing samples under their licences.
- Forms and signatures remainder: opt-in online revocation checks when validating; the ESIC extension entry; timestamp requests with hashes other than SHA-256. 7a. Encryption remainder: certificates on smart cards/HSMs that need a PIN prompt are untested (the Windows CNG provider shows its own prompt); re-encrypting a saved copy for the same certificate recipients (password encryption is done).
- Release remainder: the app and installer are Authenticode-signed with a self-signed certificate, locally and in GitHub releases (
.github/workflows/release.yml, eng/signing/README.md). A certificate from a trusted CA is future scope. Startup, installer-size and PDFium-free gates are in place (eng/releasegate). PDFium-free gate, test coverage: the PDFium-free test job runs 586 viewer test cases (it was 364 of 594); the developer build runs 713, the 127 more being the PDFium row of each engine theory and the PDFium-only tests. One file stays out (PdfiumFormRenderingTests, the PDFium form-fill environment; each listed file carries aReason, shown in the CI job summary with the#if PDFIUM_RENDERERtests): PDFium mode, the PDFium adapter (ParsePdfDate,NativeMemoryOwner) and two engine gaps (image export PNG only; a 40000 x 40000 render overflows instead of being refused). Tests of viewer behaviour run on the vector engine in every build and on PDFium too in the developer build (TestEngines); differential tests compare with what PDFium gave for their synthetic documents, committed intests/PdfViewer.Tests/PdfiumGoldens(JSON, three PNGs, one PDFium-annotated PDF), and the developer build fails when PDFium’s live results drift from them (scripts/update_pdfium_goldens.ps1regenerates them). - Differential fixtures for Type3, stencil/SMask images, rotated crop boxes, and text in embedded TrueType fonts.
- Editing remainder: none for vertical columns. Sideways Latin text (UAX #50 orientation, the font’s horizontal form, read back as part of the column) and tate-chu-yoko (short digit runs upright in one em, an editing option, read back and kept as they are) are done.
6. Decisions for the product owner
- Default engine mode — decided 2026-09-25: keep
Auto. Deviation from M0/M8 accepted by the product owner; mitigated by region-safe fallback and the live vector host. - ADR-011 — decided 2026-09-26: Direct2D. The product owner asked for the best viewer and allowed replacing WPF where it is the limit; Direct2D renders pages and detail tiles, WPF remains the application shell and the fallback renderer.