From cdd49f3edec95e04db1f92727d51f9d0388425c7 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sat, 21 Nov 2026 09:49:14 +0100 Subject: [PATCH 1/4] fix(kernel): list glyph 0 writes and map glyph 0 to U+FFFD (#592) An embedded font drew a missing character as glyph 0 and the save said nothing. PdfCanvas.NotdefGlyphs and PdfDocument.NotdefGlyphs now list each glyph 0 the canvas writes, one entry per character and font resource, capped at 1,000 with the rest counted in NotdefGlyphsDropped. The ToUnicode map no longer lists a code point against glyph 0; it carries one entry, <0000> , which ISO 14289-1 7.21.7 accepts. The content stream is unchanged. --- .../Canvas/NotdefGlyphTally.cs | 74 ++++ .../Canvas/NotdefGlyphWarning.cs | 87 ++++ src/VellumPdf.Kernel/Canvas/PdfCanvas.cs | 99 ++++- .../Canvas/TextEncodingWarning.cs | 5 + src/VellumPdf.Kernel/Document/PdfDocument.cs | 60 +++ src/VellumPdf.Kernel/Document/PdfPage.cs | 32 +- .../Fonts/EmbeddedFontHandle.cs | 19 + .../Fonts/TrueTypeFontEmbedder.cs | 27 +- src/VellumPdf.Kernel/PublicAPI.Unshipped.txt | 9 + .../Fonts/CmapFormat12Tests.cs | 2 +- .../GlyphZeroToUnicodeTests.cs | 52 +++ .../NoBreakSpaceBundledFontTests.cs | 9 +- .../NotdefGlyphTests.cs | 407 ++++++++++++++++++ .../ToUnicodeLineEndTests.cs | 2 +- .../ToUnicodeStandInTests.cs | 9 +- .../VellumPdf.Kernel.Tests.csproj | 1 + 16 files changed, 877 insertions(+), 17 deletions(-) create mode 100644 src/VellumPdf.Kernel/Canvas/NotdefGlyphTally.cs create mode 100644 src/VellumPdf.Kernel/Canvas/NotdefGlyphWarning.cs create mode 100644 tests/VellumPdf.Conformance.Tests/GlyphZeroToUnicodeTests.cs create mode 100644 tests/VellumPdf.Kernel.Tests/NotdefGlyphTests.cs diff --git a/src/VellumPdf.Kernel/Canvas/NotdefGlyphTally.cs b/src/VellumPdf.Kernel/Canvas/NotdefGlyphTally.cs new file mode 100644 index 000000000..fc930e5a4 --- /dev/null +++ b/src/VellumPdf.Kernel/Canvas/NotdefGlyphTally.cs @@ -0,0 +1,74 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Text; + +namespace VellumPdf.Canvas; + +/// +/// The glyph-0 writes of one canvas: at most distinct (character, font +/// resource) entries in order of first occurrence, and a count of the occurrences that did not fit. +/// Created on the first glyph 0, so a canvas without one allocates nothing for it. +/// +internal sealed class NotdefGlyphTally +{ + /// + /// The most entries held per canvas and per document. It is the cap the layout channel uses, + /// not a figure any standard gives; it bounds memory against text that produces a distinct + /// entry per character. + /// + internal const int MaxEntries = 1000; + + // A code point that cannot be a Unicode scalar stands for "character not known". + internal const int UnknownCodePoint = 0x110000; + + private readonly List _entries = []; + private readonly Dictionary<(int CodePoint, string? Resource), int>? _index; + + internal NotdefGlyphTally() => _index = []; + + private NotdefGlyphTally(NotdefGlyphTally source) + { + foreach (var e in source._entries) + _entries.Add(new NotdefGlyphWarning(e.Character, e.FontResourceName, e.FontName, e.Count)); + Dropped = source.Dropped; + Total = source.Total; + } + + internal IReadOnlyList Entries => _entries; + + /// Occurrences not stored because the entry would have been past the cap. + internal int Dropped { get; private set; } + + /// Every occurrence, stored or dropped. Changes whenever anything is added. + internal int Total { get; private set; } + + internal static int CodePointOf(Rune? character) => character?.Value ?? UnknownCodePoint; + + internal void Add(Rune? character, string? resource, string? fontName, int count = 1) + { + Total = Saturate(Total, count); + var key = (CodePointOf(character), resource); + if (_index!.TryGetValue(key, out var at)) + { + var entry = _entries[at]; + entry.Count = Saturate(entry.Count, count); + return; + } + + if (_entries.Count >= MaxEntries) + { + Dropped = Saturate(Dropped, count); + return; + } + + _index[key] = _entries.Count; + _entries.Add(new NotdefGlyphWarning(character, resource, fontName, count)); + } + + /// A copy that later writes to this tally do not change. + internal NotdefGlyphTally Snapshot() => new(this); + + internal static int Saturate(int current, int add) => + add > int.MaxValue - current ? int.MaxValue : current + add; +} diff --git a/src/VellumPdf.Kernel/Canvas/NotdefGlyphWarning.cs b/src/VellumPdf.Kernel/Canvas/NotdefGlyphWarning.cs new file mode 100644 index 000000000..35642687e --- /dev/null +++ b/src/VellumPdf.Kernel/Canvas/NotdefGlyphWarning.cs @@ -0,0 +1,87 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Text; + +namespace VellumPdf.Canvas; + +/// +/// One character, in one font, that a canvas wrote as glyph 0 (the .notdef glyph) because +/// the font has no glyph for it, with the number of times it was written. Read the entries from +/// and +/// . +/// +/// +/// Nothing here is refused and nothing throws. The type has no public constructor and only +/// getters, so it takes no input that could be wrong. ISO 19005-2, 6.2.11.8, and ISO 14289-1, +/// 7.21.8, forbid a reference to the .notdef glyph in a PDF/A-2 or PDF/UA-1 file; this +/// type reports that a canvas wrote one and leaves the decision to the caller. +/// An entry exists for every glyph id 0 the canvas wrote through +/// and through the library's own +/// text drawing. It does not exist for content bytes set directly on a +/// , for a canvas whose has +/// not run, or for entries past the 1,000 the list holds; +/// counts those. Do not read an empty list as +/// proof that the file holds no glyph 0. +/// Reading an entry while another thread draws on the canvas that holds it is not +/// supported. +/// +public sealed class NotdefGlyphWarning +{ + internal NotdefGlyphWarning(Rune? character, string? fontResourceName, string? fontName, int count) + { + Character = character; + FontResourceName = fontResourceName; + FontName = fontName; + Count = count; + } + + /// + /// The character that had no glyph, or null when the canvas never saw the text. + /// + /// + /// Nothing here is refused and nothing throws. The value is null for glyph ids passed to + /// , because the canvas receives + /// ids and not text. The caller of that method holds the text and can find the characters with + /// EmbeddedFontHandle.GetGlyphId, which returns 0 for exactly these. A character outside + /// the Basic Multilingual Plane is one , so it is one entry. + /// + public Rune? Character { get; } + + /// + /// The resource name the content stream selects the font by, such as TT1, or null when + /// no font had been selected on the canvas. + /// + /// + /// Nothing here is refused and nothing throws. The name is the one given to the last + /// or + /// call on the canvas. It does not follow + /// a font that brings back. Resource names are counters + /// local to one document, so within a document the pair of character and name identifies one + /// character in one font. + /// + public string? FontResourceName { get; } + + /// + /// The font's PostScript name without the subset tag, such as DejaVuSans, or null when + /// the canvas does not know it. + /// + /// + /// Nothing here is refused and nothing throws. Only the library's own text drawing knows + /// the name. Glyph ids passed to + /// leave it null; use + /// to find the font. + /// + public string? FontName { get; } + + /// + /// The number of times glyph 0 was written for this character in this font, saturating at + /// . + /// + /// + /// Nothing here is refused and nothing throws. The list a canvas returns is live, so the + /// count of an entry grows while the canvas draws. Do not read it from another thread + /// while the canvas draws. + /// + public int Count { get; internal set; } +} diff --git a/src/VellumPdf.Kernel/Canvas/PdfCanvas.cs b/src/VellumPdf.Kernel/Canvas/PdfCanvas.cs index 716b3af6e..e14e447bd 100644 --- a/src/VellumPdf.Kernel/Canvas/PdfCanvas.cs +++ b/src/VellumPdf.Kernel/Canvas/PdfCanvas.cs @@ -60,6 +60,12 @@ public sealed class PdfCanvas private readonly List _textEncodingWarnings = []; + // Glyph-0 writes, created on the first one. The resource name is kept apart from _currentFont + // because SetFontByName selects a font the canvas holds no resource object for. + private NotdefGlyphTally? _notdef; + private string? _currentFontResource; + private static readonly IReadOnlyList NoNotdefGlyphs = []; + /// /// Characters passed to that WinAnsiEncoding could not represent and /// that were therefore substituted with '?' in the content stream. Empty when every character @@ -67,8 +73,50 @@ public sealed class PdfCanvas /// fonts; with a Symbol or ZapfDingbats font this list is not meaningful, since those fonts /// use their own symbolic encoding rather than WinAnsi. /// + /// + /// Only adds to this list. A glyph 0 written by + /// is listed in + /// . + /// public IReadOnlyList TextEncodingWarnings => _textEncodingWarnings; + /// + /// The characters this canvas wrote as glyph 0 (.notdef), one entry per character and + /// font resource, in order of first occurrence. Empty until the first one. + /// + /// + /// Nothing here is refused and nothing throws. The list takes no input, and the canvas + /// writes glyph 0 as it always has. ISO 19005-2, 6.2.11.8, and ISO 14289-1, 7.21.8, forbid a + /// reference to .notdef in a PDF/A-2 or PDF/UA-1 file, so this list is how a caller of + /// the Kernel finds out. It is separate from , which lists + /// characters that wrote as '?'; glyph 0 is not listed there. + /// The list is live: it holds everything this canvas wrote since it was created, and the + /// entries' counts grow as the canvas draws. At most 1,000 entries are held; + /// counts the occurrences of entries past that. Glyph ids + /// passed to are listed with no + /// character, because the canvas sees ids and not text. Do not read an empty list as + /// proof that the file holds no glyph 0: content bytes set directly on the page are not + /// scanned, and a Tj written through another route is not seen. + /// Reading the list while another thread draws on this canvas is not supported. + /// gathers the lists of a document's + /// finished pages. + /// + public IReadOnlyList NotdefGlyphs => _notdef?.Entries ?? NoNotdefGlyphs; + + /// + /// The number of glyph-0 writes not listed in because the list + /// already held 1,000 entries, saturating at . + /// + /// + /// Nothing here is refused and nothing throws. A write for an entry already in the list + /// is counted in that entry, not here. Do not read zero as proof that the list is + /// complete for content written some other way; see . + /// + public int NotdefGlyphsDropped => _notdef?.Dropped ?? 0; + + // For the layout channel, which reads the tally by difference. + internal NotdefGlyphTally? NotdefTally => _notdef; + /// Creates a content stream builder targeting the given page. public PdfCanvas(PdfPage page) => _page = page; @@ -539,6 +587,7 @@ public PdfCanvas SetFont(PdfFontResource font, double size) var sizeToken = N(size); _usedFonts[font.ResourceName] = font; _currentFont = font; + _currentFontResource = font.ResourceName; _currentFontSize = size; WriteEscapedName(font.ResourceName); _ops.Write(Encoding.ASCII.GetBytes($" {sizeToken} Tf\n")); @@ -555,6 +604,7 @@ public PdfCanvas SetFontByName(string resourceName, double size) { var sizeToken = N(size); _currentFont = null; + _currentFontResource = resourceName; WriteEscapedName(resourceName); _ops.Write(Encoding.ASCII.GetBytes($" {sizeToken} Tf\n")); return this; @@ -631,7 +681,46 @@ public PdfCanvas ShowGlyphsAligned(ReadOnlySpan glyphIds, double measure /// Emits a hex-encoded glyph-id run using the PDF Tj operator. /// Each glyph id is encoded as 2 bytes big-endian (Identity-H CIDFont encoding). /// + /// + /// Every id is written as given and nothing is refused. Each id 0 is counted in + /// with no character and no font name, under the resource name of + /// the last font selected on this canvas; it is not counted in + /// . EmbeddedFontHandle.GetGlyphId returns 0 for a + /// character the font has no glyph for, so a caller holding the text can find which characters + /// those are. A PDF/A-2 or PDF/UA-1 file must not reference glyph 0 (ISO 19005-2, 6.2.11.8; ISO + /// 14289-1, 7.21.8). Do not pass glyph 0 for either claim; the save accepts it, and a + /// validator then reports the file. + /// public PdfCanvas ShowGlyphs(ReadOnlySpan glyphIds) + { + WriteGlyphs(glyphIds); + var zeros = 0; + foreach (var gid in glyphIds) + if (gid == 0) zeros++; + if (zeros > 0) (_notdef ??= new()).Add(null, _currentFontResource, null, zeros); + return this; + } + + /// + /// Maps to glyph ids in and writes the run as + /// does, but lists each glyph 0 with its + /// character and the font's name. The bytes written are the same. + /// + internal PdfCanvas ShowEmbeddedText(EmbeddedFontHandle font, string text) + { + var gids = new ushort[text.Length]; + var count = 0; + foreach (var rune in text.EnumerateRunes()) + { + var gid = font.GetGlyphId(rune.Value); + gids[count++] = gid; + if (gid == 0) (_notdef ??= new()).Add(rune, font.ResourceName, font.PostScriptName); + } + WriteGlyphs(gids.AsSpan(0, count)); + return this; + } + + private void WriteGlyphs(ReadOnlySpan glyphIds) { _ops.WriteByte((byte)'<'); foreach (var gid in glyphIds) @@ -642,7 +731,6 @@ public PdfCanvas ShowGlyphs(ReadOnlySpan glyphIds) _ops.WriteByte(HexNibble(gid & 0xF)); } _ops.Write("> Tj\n"u8); - return this; } private static byte HexNibble(int v) => (byte)(v < 10 ? '0' + v : 'A' + v - 10); @@ -773,11 +861,18 @@ public PdfCanvas DoXObject(string resourceName) /// ) and stores the accumulated operator bytes /// as the page content. Call exactly once when the page is complete. /// + /// + /// Also stores a snapshot of and + /// on the page, which gathers. The + /// snapshot replaces whatever an earlier canvas finished on the same page stored, as the + /// content bytes replace the earlier canvas's bytes. Drawing after Finish is not part of + /// the snapshot until Finish runs again. + /// public void Finish() { foreach (var (name, font) in _usedFonts) _page.RegisterStandard14FontUsage(name, font); - _page.ContentBytes = _ops.ToArray(); + _page.SetContent(_ops.ToArray(), _notdef?.Snapshot()); } // ── Private helpers ───────────────────────────────────────────────────── diff --git a/src/VellumPdf.Kernel/Canvas/TextEncodingWarning.cs b/src/VellumPdf.Kernel/Canvas/TextEncodingWarning.cs index a27cd0454..ef491a777 100644 --- a/src/VellumPdf.Kernel/Canvas/TextEncodingWarning.cs +++ b/src/VellumPdf.Kernel/Canvas/TextEncodingWarning.cs @@ -12,6 +12,11 @@ namespace VellumPdf.Canvas; /// warning. Use an embedded font (via SetFontByName + ShowGlyphs) to render glyphs /// outside WinAnsi. /// +/// +/// Only the Standard-14 path lists a character here. A glyph 0 +/// that writes is listed in +/// , not in this type. +/// /// /// The unrepresentable scalar. A rather than a so that a /// character outside the Basic Multilingual Plane is reported once, as itself, instead of twice as diff --git a/src/VellumPdf.Kernel/Document/PdfDocument.cs b/src/VellumPdf.Kernel/Document/PdfDocument.cs index 7b9d51b01..6c521f31e 100644 --- a/src/VellumPdf.Kernel/Document/PdfDocument.cs +++ b/src/VellumPdf.Kernel/Document/PdfDocument.cs @@ -3,6 +3,7 @@ using System.Text; using VellumPdf.Annotations; +using VellumPdf.Canvas; using VellumPdf.Core; using VellumPdf.Encryption; using VellumPdf.Fonts; @@ -219,6 +220,65 @@ public PdfPage AddPage(PdfRectangle size) /// The pages in this document, in order. public IReadOnlyList Pages => _pages; + private static readonly IReadOnlyList NoNotdefGlyphs = []; + + /// + /// The characters the document's finished pages wrote as glyph 0 (.notdef), one entry + /// per character and font resource, in page order, with the counts of all pages added together. + /// + /// + /// Nothing here is refused and nothing throws. The property takes no input, and a save + /// is not refused for glyph 0. ISO 19005-2, 6.2.11.8, and ISO 14289-1, 7.21.8, forbid a + /// reference to .notdef in a PDF/A-2 or PDF/UA-1 file, so this list is how a caller of + /// the Kernel finds out before a validator does. + /// The list is built on each read from what each page's last + /// stored, so it holds what the content streams hold. A page + /// whose canvas was never finished contributes nothing, drawing after Finish counts only + /// once Finish runs again, and a page whose was set + /// directly contributes nothing. At most 1,000 entries are held; + /// counts the occurrences past that. + /// , + /// and + /// draw nothing and leave the list as it was, whether they + /// succeed or throw. + /// The character is null for glyph ids written through + /// ; see + /// . Do not read an empty list as proof that + /// the file holds no glyph 0: it does not see content bytes set directly, and it does not see + /// an unfinished page. + /// Reading the list while another thread calls on one of + /// the document's pages is not supported. + /// + public IReadOnlyList NotdefGlyphs => GatherNotdefGlyphs().Entries; + + /// + /// The number of glyph-0 writes not listed in because a page's list + /// or the document's list already held 1,000 entries, saturating at . + /// + /// + /// Nothing here is refused and nothing throws. The value is computed on each read, like + /// , and has the same boundary. Do not read zero as proof that + /// the file holds no glyph 0 the list does not see. + /// + public int NotdefGlyphsDropped => GatherNotdefGlyphs().Dropped; + + private (IReadOnlyList Entries, int Dropped) GatherNotdefGlyphs() + { + NotdefGlyphTally? merged = null; + var dropped = 0; + foreach (var page in _pages) + { + if (page.NotdefTally is not { } tally) continue; + dropped = NotdefGlyphTally.Saturate(dropped, tally.Dropped); + merged ??= new NotdefGlyphTally(); + foreach (var e in tally.Entries) + merged.Add(e.Character, e.FontResourceName, e.FontName, e.Count); + } + + if (merged is null) return (NoNotdefGlyphs, dropped); + return (merged.Entries, NotdefGlyphTally.Saturate(dropped, merged.Dropped)); + } + /// /// Returns a for a Standard-14 font, creating /// and caching one with an auto-assigned resource name (F1, F2, …) on first call. diff --git a/src/VellumPdf.Kernel/Document/PdfPage.cs b/src/VellumPdf.Kernel/Document/PdfPage.cs index d45d327f6..09e5a1485 100644 --- a/src/VellumPdf.Kernel/Document/PdfPage.cs +++ b/src/VellumPdf.Kernel/Document/PdfPage.cs @@ -39,8 +39,38 @@ public sealed class PdfPage /// Creates a page with the given media box. public PdfPage(PdfRectangle mediaBox) => MediaBox = mediaBox; + private byte[]? _contentBytes; + /// Raw PDF content stream bytes. Set by . - public byte[]? ContentBytes { get; set; } + /// + /// Any value is accepted and nothing is scanned. Setting it discards the glyph-0 entries the + /// page took from , because the bytes they described are + /// gone, so does not list a glyph 0 that bytes set here + /// hold. Do not read an empty as proof that bytes + /// set here reference no glyph 0. + /// + public byte[]? ContentBytes + { + get => _contentBytes; + set + { + _contentBytes = value; + NotdefTally = null; + } + } + + /// + /// What the canvas that last finished this page wrote as glyph 0, as it stood at that + /// Finish. Cleared when is set directly. + /// + internal Canvas.NotdefGlyphTally? NotdefTally { get; private set; } + + // Called by PdfCanvas.Finish(): the bytes and the glyph-0 snapshot belong together. + internal void SetContent(byte[] bytes, Canvas.NotdefGlyphTally? notdef) + { + _contentBytes = bytes; + NotdefTally = notdef; + } // Called by PdfCanvas.Finish() — the font dict itself is materialised as a shared // indirect object (once per face, document-wide) by PdfDocument.Save() before the diff --git a/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs b/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs index 812311c8f..1c58f5e9c 100644 --- a/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs +++ b/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs @@ -29,6 +29,10 @@ public sealed class EmbeddedFontHandle /// PDF resource name assigned to this font (e.g. "TT1"). public string ResourceName => Embedder.ResourceName; + /// The font's PostScript name without a subset tag, for reports that name the + /// font. + internal string PostScriptName => Embedder.PostScriptName; + /// /// SHA-256 of the font program this handle embeds, as the owning document keyed it. Another /// document that embedded the same program recognises it by this value. @@ -59,6 +63,13 @@ public double MeasureString(string text, double pointSize) => /// draw them must still be able to show a space. A font that has the glyph keeps it. The same /// lookup measures the text, so the width of the space that is drawn is the width that was /// measured. + /// Nothing here is refused and nothing throws. A 0 is not an error at this call, + /// but writes + /// it as CID 0, which ISO 19005-2, 6.2.11.8, and ISO 14289-1, 7.21.8, forbid in a PDF/A-2 or + /// PDF/UA-1 file. The font's ToUnicode CMap maps glyph 0 to U+FFFD. A Kernel caller sees the + /// write in , without the character. Do + /// not pass a code point this method answers 0 for to ShowGlyphs under either + /// claim. /// public ushort GetGlyphId(int codePoint) => Embedder.GetGlyphId(codePoint); @@ -67,6 +78,14 @@ public double MeasureString(string text, double pointSize) => /// them into . Returns the number of glyph ids written. /// The buffer must be at least as long as the number of Unicode scalars in the string. /// + /// + /// Each id is the one returns, so a 0 means the font has no glyph + /// for the character, except the stand-ins described there. A scalar past the end of the buffer + /// is left out and the returned count says how many were written. An unpaired surrogate is + /// looked up as U+FFFD. Do not pass the ids to + /// under a + /// PDF/A-2 or PDF/UA-1 claim without checking them for 0; see . + /// public int GetGlyphIds(string text, Span buffer) { var idx = 0; diff --git a/src/VellumPdf.Kernel/Fonts/TrueTypeFontEmbedder.cs b/src/VellumPdf.Kernel/Fonts/TrueTypeFontEmbedder.cs index b016dbdcf..96dfe5170 100644 --- a/src/VellumPdf.Kernel/Fonts/TrueTypeFontEmbedder.cs +++ b/src/VellumPdf.Kernel/Fonts/TrueTypeFontEmbedder.cs @@ -217,6 +217,12 @@ internal void AddUsageFrom(TrueTypeFontEmbedder other) } /// Returns the glyph ID for a Unicode code point, registering it for subsetting. + /// + /// A code point the font has no glyph for gives glyph 0 (.notdef), except the stand-ins + /// described on . Glyph 0 is registered like + /// any other glyph, and the font's ToUnicode CMap maps it to U+FFFD, not to the code point. + /// Nothing is refused and nothing throws. + /// public ushort GetGlyphId(int codePoint) { if (_unicodeToGid.TryGetValue(codePoint, out var cachedGid)) return cachedGid; @@ -250,7 +256,8 @@ public double MeasureString(string text, double pointSize) return total / 1000.0 * pointSize; } - private string PostScriptName => + // The name without the subset tag, as a glyph-0 report names the font. + internal string PostScriptName => _name.PostScriptName ?? _name.FamilyName ?? "Unknown"; // A subsetted font's name must carry a six-uppercase-letter tag + '+' prefix @@ -387,6 +394,9 @@ public Core.PdfStream BuildFontFileStream() /// project, so this member does not claim that a carriage return and line feed pair is /// invalid; the single form keeps the output reproducible. The compressed bytes can still /// differ between .NET runtimes. This member refuses no input and throws nothing. + /// Glyph 0 gets one entry, <0000> <FFFD>, when any code point was + /// assigned glyph 0, and no code point is listed against it; every other glyph gets the code + /// point or points that were assigned to it, as before. /// public Core.PdfStream BuildToUnicodeCMap() { @@ -714,7 +724,14 @@ internal static string BuildToUnicodeCMapContent( // must not take over a glyph that ordinary spaces use, or copying a space out of the PDF // gives a narrow no-break space (#562). So a stand-in is listed only when no code point that // owns the glyph is in use, and when several stand-ins share it the lowest code point is - // listed. Glyph 0 and duplicates between code points the font really maps are left alone. + // listed. Duplicates between code points the font really maps are left alone. + // + // Glyph 0 stands for no character, and a CMap maps a code to one string, so the code points + // that were measured or drawn as glyph 0 are not listed one by one. When there was at least + // one, glyph 0 gets the single entry U+FFFD, the replacement character, which satisfies the + // value rule of ISO 14289-1 7.21.7 (greater than zero, and neither U+FEFF nor U+FFFE). + // A glyph 0 can be measured without being drawn, as a running band's cut tail is, so the + // entry can appear without a .notdef in the content. var owned = new HashSet(); foreach (var (cp, gid) in unicodeToGid) if (!fallbackCodePoints.Contains(cp)) owned.Add(gid); @@ -728,11 +745,13 @@ internal static string BuildToUnicodeCMapContent( } var pairs = unicodeToGid - .Where(kv => !fallbackCodePoints.Contains(kv.Key) - || (listedStandIn.TryGetValue(kv.Value, out var listed) && listed == kv.Key)) + .Where(kv => kv.Value != 0 + && (!fallbackCodePoints.Contains(kv.Key) + || (listedStandIn.TryGetValue(kv.Value, out var listed) && listed == kv.Key))) .Select(kv => (gid: kv.Value, cp: kv.Key)) .OrderBy(p => p.gid) .ToList(); + if (unicodeToGid.Values.Contains((ushort)0)) pairs.Insert(0, (gid: (ushort)0, cp: 0xFFFD)); // Write in chunks of 100: Adobe TN5014 §7.4 caps beginbfchar/endbfchar at "a maximum of // 100 lines in each ~bfchar set" — a limit ISO 32000-2 §9.10.3 carries over unchanged by diff --git a/src/VellumPdf.Kernel/PublicAPI.Unshipped.txt b/src/VellumPdf.Kernel/PublicAPI.Unshipped.txt index 96d8c6bc3..267eb3be4 100644 --- a/src/VellumPdf.Kernel/PublicAPI.Unshipped.txt +++ b/src/VellumPdf.Kernel/PublicAPI.Unshipped.txt @@ -12,3 +12,12 @@ VellumPdf.Images.GifLoadOptions.PlaceOnLogicalScreen.init -> void override VellumPdf.Images.GifLoadOptions.ToString() -> string! static VellumPdf.Images.GifLoadOptions.operator !=(VellumPdf.Images.GifLoadOptions? left, VellumPdf.Images.GifLoadOptions? right) -> bool static VellumPdf.Images.GifLoadOptions.operator ==(VellumPdf.Images.GifLoadOptions? left, VellumPdf.Images.GifLoadOptions? right) -> bool +VellumPdf.Canvas.NotdefGlyphWarning +VellumPdf.Canvas.NotdefGlyphWarning.Character.get -> System.Text.Rune? +VellumPdf.Canvas.NotdefGlyphWarning.Count.get -> int +VellumPdf.Canvas.NotdefGlyphWarning.FontName.get -> string? +VellumPdf.Canvas.NotdefGlyphWarning.FontResourceName.get -> string? +VellumPdf.Canvas.PdfCanvas.NotdefGlyphs.get -> System.Collections.Generic.IReadOnlyList! +VellumPdf.Canvas.PdfCanvas.NotdefGlyphsDropped.get -> int +VellumPdf.Document.PdfDocument.NotdefGlyphs.get -> System.Collections.Generic.IReadOnlyList! +VellumPdf.Document.PdfDocument.NotdefGlyphsDropped.get -> int diff --git a/tests/VellumPdf.Conformance.Tests/Fonts/CmapFormat12Tests.cs b/tests/VellumPdf.Conformance.Tests/Fonts/CmapFormat12Tests.cs index 8aa6c9c47..18495926a 100644 --- a/tests/VellumPdf.Conformance.Tests/Fonts/CmapFormat12Tests.cs +++ b/tests/VellumPdf.Conformance.Tests/Fonts/CmapFormat12Tests.cs @@ -612,7 +612,7 @@ private static byte[] DrawText(byte[] font, string text, PdfConformance conforma /// The PDF with every FlateDecode stream inflated in place, as one Latin-1-safe byte array, so /// a test can search the ToUnicode map and the content stream for text. /// - private static byte[] Inflated(byte[] pdf) + internal static byte[] Inflated(byte[] pdf) { var text = Encoding.Latin1.GetString(pdf); var output = new MemoryStream(); diff --git a/tests/VellumPdf.Conformance.Tests/GlyphZeroToUnicodeTests.cs b/tests/VellumPdf.Conformance.Tests/GlyphZeroToUnicodeTests.cs new file mode 100644 index 000000000..414d2daf9 --- /dev/null +++ b/tests/VellumPdf.Conformance.Tests/GlyphZeroToUnicodeTests.cs @@ -0,0 +1,52 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using VellumPdf.Canvas; +using VellumPdf.Conformance.Tests.Fonts; +using VellumPdf.Document; +using Xunit; + +namespace VellumPdf.Conformance.Tests; + +/// +/// The ToUnicode map maps glyph 0 to U+FFFD, which the Unicode value rule accepts (ISO 14289-1, +/// 7.21.7), so a file that draws a missing character fails the .notdef rule and only that one (#592). +/// +public sealed class GlyphZeroToUnicodeTests +{ + private static byte[] DocumentDrawingAMissingCharacter() + { + using var doc = new PdfDocument + { + Conformance = VellumPdf.Document.PdfConformance.PdfA2u, + Timestamp = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero), + DocumentId = new byte[16], + }; + var page = doc.AddPage(); + var font = doc.UseTrueTypeFont(CmapFormat12Tests.LoadAsset("DejaVuSans.ttf")); + doc.RegisterEmbeddedFontUsage(page, font); + var canvas = new PdfCanvas(page); + canvas.BeginText().SetFontByName(font.ResourceName, 12).SetTextMatrix(1, 0, 0, 1, 72, 700); + var ids = new ushort[2]; + font.GetGlyphIds("A\u26B9", ids); + canvas.ShowGlyphs(ids).EndText(); + canvas.Finish(); + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + [Fact] + public void AMissingCharacter_failsTheNotdefRule_andNotTheToUnicodeRule() + { + var pdf = DocumentDrawingAMissingCharacter(); + var text = System.Text.Encoding.Latin1.GetString(CmapFormat12Tests.Inflated(pdf)); + Assert.Contains("<0000> ", text, StringComparison.Ordinal); + Assert.DoesNotContain("<0000> <26B9>", text, StringComparison.Ordinal); + + var ids = PdfPreflight.Validate(pdf, PdfConformance.PdfA2U).Assertions.Select(a => a.RuleId).ToList(); + + Assert.Contains("ISO19005-2:6.2.11.8-notdef", ids); + Assert.DoesNotContain("ISO19005-2:6.2.11.7.2-tounicode", ids); + } +} diff --git a/tests/VellumPdf.Conformance.Tests/NoBreakSpaceBundledFontTests.cs b/tests/VellumPdf.Conformance.Tests/NoBreakSpaceBundledFontTests.cs index a09775401..28a8483bc 100644 --- a/tests/VellumPdf.Conformance.Tests/NoBreakSpaceBundledFontTests.cs +++ b/tests/VellumPdf.Conformance.Tests/NoBreakSpaceBundledFontTests.cs @@ -135,9 +135,9 @@ public void LiberationMono_toUnicode_aStandInAloneStillNamesItsGlyph() Assert.Contains((narrow, NarrowNoBreakSpace), entries); } - /// Characters the font lacks that are not one of the two spaces get no stand-in, so each keeps its own glyph-0 entry in the CMap. + /// Characters the font lacks that are not one of the two spaces get no stand-in, so they stay glyph 0, and the CMap maps glyph 0 to U+FFFD once instead of listing each of them. [Fact] - public void LiberationMono_toUnicode_missingCharactersThatAreNotSpacesKeepTheirNotdefEntries() + public void LiberationMono_toUnicode_missingCharactersThatAreNotSpacesShareOneReplacementEntryForGlyphZero() { using var doc = new PdfDocument(); var courier = doc.EmbedStandard14Font(Standard14.Courier); @@ -146,8 +146,9 @@ public void LiberationMono_toUnicode_missingCharactersThatAreNotSpacesKeepTheirN var entries = ToUnicodeEntries(courier); - Assert.Contains((0, 0x4E00), entries); - Assert.Contains((0, 0x4E01), entries); + Assert.Contains((0, 0xFFFD), entries); + Assert.DoesNotContain((0, 0x4E00), entries); + Assert.DoesNotContain((0, 0x4E01), entries); } /// diff --git a/tests/VellumPdf.Kernel.Tests/NotdefGlyphTests.cs b/tests/VellumPdf.Kernel.Tests/NotdefGlyphTests.cs new file mode 100644 index 000000000..2df98780e --- /dev/null +++ b/tests/VellumPdf.Kernel.Tests/NotdefGlyphTests.cs @@ -0,0 +1,407 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Text; +using VellumPdf.Canvas; +using VellumPdf.Document; +using VellumPdf.Fonts; + +namespace VellumPdf.Kernel.Tests; + +/// +/// A character the embedded font has no glyph for is written as glyph 0. The canvas lists each +/// such write, the document gathers the lists of its finished pages, and the font's ToUnicode CMap +/// carries one entry, U+FFFD, for glyph 0 (#592). The fonts are in-tree: DejaVu Sans lacks U+26B9 +/// and U+1F31F, and Liberation Mono lacks U+2609, which DejaVu Sans has. +/// +public sealed class NotdefGlyphTests +{ + private static readonly string FontsDir = Path.Combine(AppContext.BaseDirectory, "Fonts"); + + private static byte[] Font(string name) => File.ReadAllBytes(Path.Combine(FontsDir, name)); + + private static PdfDocument NewDocument() => new() + { + Timestamp = new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero), + DocumentId = new byte[16], + }; + + // (character, resource, font name, count) for every entry, so an assertion names all four. + private static List<(string? Character, string? Resource, string? Name, int Count)> Project( + IReadOnlyList list) => + [.. list.Select(e => (e.Character?.ToString(), e.FontResourceName, e.FontName, e.Count))]; + + // \u2500\u2500 The ToUnicode CMap \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 + + private static List BfcharLines(string map) => + [.. map.Split('\n').Where(l => l.StartsWith("<", StringComparison.Ordinal) && l != "<0000> ")]; + + private static string Header(int entries) => + "/CIDInit /ProcSet findresource begin\n" + + "12 dict begin\n" + + "begincmap\n" + + "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n" + + "/CMapName /Adobe-Identity-UCS def\n" + + "/CMapType 2 def\n" + + "1 begincodespacerange\n" + + "<0000> \n" + + "endcodespacerange\n" + + $"{entries} beginbfchar\n"; + + private const string Trailer = + "endbfchar\n" + + "endcmap\n" + + "CMapName currentdict /CMap defineresource pop\n" + + "end end\n"; + + [Fact] + public void ToUnicode_glyphZero_isOneEntryForReplacementCharacter() + { + var map = TrueTypeFontEmbedder.BuildToUnicodeCMapContent( + new Dictionary { [0x26B9] = 0, [0x1F31F] = 0, [0x41] = 36 }, new HashSet()); + + Assert.Equal(Header(2) + "<0000> \n<0024> <0041>\n" + Trailer, map); + } + + [Fact] + public void ToUnicode_noGlyphZero_hasNoGlyphZeroEntry() + { + var map = TrueTypeFontEmbedder.BuildToUnicodeCMapContent( + new Dictionary { [0x41] = 36 }, new HashSet()); + + Assert.Equal(Header(1) + "<0024> <0041>\n" + Trailer, map); + Assert.DoesNotContain(BfcharLines(map), l => l.StartsWith("<0000>", StringComparison.Ordinal)); + } + + [Fact] + public void ToUnicode_glyphZeroEntryIsFirst_andCountsTowardTheHundredLineSet() + { + var assignments = new Dictionary { [0x26B9] = 0, [0x2609] = 0 }; + for (var i = 0; i < 101; i++) assignments[0x100 + i] = (ushort)(i + 1); + + var map = TrueTypeFontEmbedder.BuildToUnicodeCMapContent(assignments, new HashSet()); + + var lines = map.Split('\n'); + Assert.Equal("100 beginbfchar", lines[9]); + Assert.Equal("<0000> ", lines[10]); + Assert.Equal("2 beginbfchar", lines[9 + 1 + 100 + 1]); + Assert.Single(BfcharLines(map), l => l.StartsWith("<0000>", StringComparison.Ordinal)); + Assert.Equal(1 + 101, BfcharLines(map).Count); + } + + [Fact] + public void KernelDocument_drawingAMissingCharacter_mapsGlyphZeroToReplacementCharacter() + { + using var doc = NewDocument(); + var page = doc.AddPage(); + var handle = doc.UseTrueTypeFont(Font("DejaVuSans.ttf")); + var gids = new ushort[2]; + Assert.Equal(2, handle.GetGlyphIds("A\u26B9", gids)); + Assert.Equal(0, gids[1]); + doc.RegisterEmbeddedFontUsage(page, handle); + var canvas = new PdfCanvas(page); + canvas.BeginText().SetFontByName(handle.ResourceName, 12).ShowGlyphs(gids).EndText(); + canvas.Finish(); + using var ms = new MemoryStream(); + doc.Save(ms); + + var map = Encoding.ASCII.GetString(Assert.Single(ToUnicodeLineEndTests.ToUnicodeMaps(ms.ToArray()))); + + Assert.Equal(["<0000> ", "<0024> <0041>"], BfcharLines(map)); + } + + // \u2500\u2500 The canvas list \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 + + [Fact] + public void ShowEmbeddedText_writesTheBytesGetGlyphIdsAndShowGlyphsWrite_andListsEachCharacter() + { + using var doc = NewDocument(); + var handle = doc.UseTrueTypeFont(Font("DejaVuSans.ttf")); + const string text = "A\u26B9\u26B9B\U0001F31F"; + + var viaText = new PdfCanvas(doc.AddPage()); + viaText.BeginText().SetFontByName(handle.ResourceName, 12).ShowEmbeddedText(handle, text); + viaText.EndText().Finish(); + + var viaIds = new PdfCanvas(doc.AddPage()); + var gids = new ushort[text.Length]; + var count = handle.GetGlyphIds(text, gids); + viaIds.BeginText().SetFontByName(handle.ResourceName, 12).ShowGlyphs(gids.AsSpan(0, count)); + viaIds.EndText().Finish(); + + Assert.Equal(doc.Pages[1].ContentBytes, doc.Pages[0].ContentBytes); + Assert.Equal( + [("\u26B9", "TT1", "DejaVuSans", 2), ("\U0001F31F", "TT1", "DejaVuSans", 1)], + Project(viaText.NotdefGlyphs)); + Assert.Equal([(null, "TT1", null, 3)], Project(viaIds.NotdefGlyphs)); + } + + [Fact] + public void ShowGlyphs_underASelectedFontName_listsGlyphZeroWithNoCharacter() + { + var canvas = new PdfCanvas(new PdfPage(new PdfRectangle(0, 0, 100, 100))); + canvas.BeginText().SetFontByName("TT1", 12).ShowGlyphs([0, 36, 0]).EndText(); + + Assert.Equal([(null, "TT1", null, 2)], Project(canvas.NotdefGlyphs)); + Assert.Empty(canvas.TextEncodingWarnings); + } + + [Fact] + public void SetFont_namesTheResourceOfTheStandard14Font() + { + using var doc = NewDocument(); + var canvas = new PdfCanvas(doc.AddPage()); + canvas.BeginText().SetFont(doc.UseFont(Standard14.Helvetica), 12).ShowGlyphs([0]).EndText(); + + Assert.Equal([(null, "F1", null, 1)], Project(canvas.NotdefGlyphs)); + } + + [Fact] + public void ACanvasWithNoGlyphZero_listsNothingAndAllocatesNothing() + { + var canvas = new PdfCanvas(new PdfPage(new PdfRectangle(0, 0, 100, 100))); + canvas.BeginText().SetFontByName("TT1", 12).ShowGlyphs([36, 37]).EndText(); + + Assert.Empty(canvas.NotdefGlyphs); + Assert.Equal(0, canvas.NotdefGlyphsDropped); + Assert.Same(canvas.NotdefGlyphs, canvas.NotdefGlyphs); + Assert.Same(canvas.NotdefGlyphs, new PdfCanvas(new PdfPage(new PdfRectangle(0, 0, 100, 100))).NotdefGlyphs); + } + + [Fact] + public void ShowGlyphs_beforeAnyFontIsSelected_listsGlyphZeroWithNoResourceName() + { + var canvas = new PdfCanvas(new PdfPage(new PdfRectangle(0, 0, 100, 100))); + canvas.BeginText().ShowGlyphs([0]).EndText(); + + Assert.Equal([(null, null, null, 1)], Project(canvas.NotdefGlyphs)); + } + + [Fact] + public void ASizeThatIsRefused_leavesTheCurrentFontResourceUnchanged() + { + var canvas = new PdfCanvas(new PdfPage(new PdfRectangle(0, 0, 100, 100))); + canvas.SetFontByName("TT1", 12); + Assert.ThrowsAny(() => canvas.SetFontByName("TT2", double.NaN)); + canvas.BeginText().ShowGlyphs([0]).EndText(); + + Assert.Equal([(null, "TT1", null, 1)], Project(canvas.NotdefGlyphs)); + } + + [Fact] + public void Entries_areDeduplicatedByCharacterAndResource_inOrderOfFirstOccurrence() + { + var canvas = new PdfCanvas(new PdfPage(new PdfRectangle(0, 0, 100, 100))); + canvas.BeginText(); + canvas.SetFontByName("TT1", 12).ShowGlyphs([0]); + canvas.SetFontByName("TT2", 12).ShowGlyphs([0]); + canvas.SetFontByName("TT1", 12).ShowGlyphs([0]); + canvas.EndText(); + + Assert.Equal([(null, "TT1", null, 2), (null, "TT2", null, 1)], Project(canvas.NotdefGlyphs)); + } + + [Fact] + public void ShowEmbeddedText_listsCharactersInOrderOfFirstOccurrence() + { + using var doc = NewDocument(); + var handle = doc.UseTrueTypeFont(Font("LiberationMono-Regular.ttf")); + var canvas = new PdfCanvas(doc.AddPage()); + canvas.BeginText().SetFontByName(handle.ResourceName, 12).ShowEmbeddedText(handle, "\u26B9\u2609\u26B9"); + + Assert.Equal( + [("\u26B9", "TT1", "LiberationMono", 2), ("\u2609", "TT1", "LiberationMono", 1)], + Project(canvas.NotdefGlyphs)); + } + + [Fact] + public void AStandInGlyph_isNotGlyphZero() + { + using var doc = NewDocument(); + var handle = doc.UseTrueTypeFont(Font("LiberationMono-Regular.ttf")); + var canvas = new PdfCanvas(doc.AddPage()); + canvas.BeginText().SetFontByName(handle.ResourceName, 12).ShowEmbeddedText(handle, "1\u202F000"); + + Assert.Empty(canvas.NotdefGlyphs); + } + + [Fact] + public void TheCanvasListHoldsAThousandEntries_andCountsTheRestAsDropped() + { + var canvas = new PdfCanvas(new PdfPage(new PdfRectangle(0, 0, 100, 100))); + canvas.BeginText(); + for (var i = 1; i <= 1001; i++) canvas.SetFontByName($"X{i}", 12).ShowGlyphs([0]); + for (var i = 0; i < 3; i++) canvas.SetFontByName("X1001", 12).ShowGlyphs([0]); + + Assert.Equal(1000, canvas.NotdefGlyphs.Count); + Assert.DoesNotContain(canvas.NotdefGlyphs, e => e.FontResourceName == "X1001"); + Assert.Equal(4, canvas.NotdefGlyphsDropped); + + // An entry that is already held still counts after the cap. + canvas.SetFontByName("X1", 12).ShowGlyphs([0, 0]); + Assert.Equal(3, canvas.NotdefGlyphs[0].Count); + Assert.Equal(4, canvas.NotdefGlyphsDropped); + } + + [Fact] + public void Counts_saturateAtIntMaxValue() + { + var tally = new NotdefGlyphTally(); + tally.Add(null, "TT1", null, int.MaxValue); + tally.Add(null, "TT1", null, int.MaxValue); + Assert.Equal(int.MaxValue, Assert.Single(tally.Entries).Count); + Assert.Equal(int.MaxValue, tally.Total); + + for (var i = 0; i < NotdefGlyphTally.MaxEntries; i++) tally.Add(null, $"X{i}", null); + tally.Add(null, "past", null, int.MaxValue); + tally.Add(null, "past", null, int.MaxValue); + Assert.Equal(int.MaxValue, tally.Dropped); + } + + // \u2500\u2500 The page and the document \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 + + private static PdfPage FinishedPage(PdfDocument doc, params string[] resources) + { + var page = doc.AddPage(); + var canvas = new PdfCanvas(page); + canvas.BeginText(); + foreach (var r in resources) canvas.SetFontByName(r, 12).ShowGlyphs([0]); + canvas.EndText().Finish(); + return page; + } + + [Fact] + public void TheDocumentList_addsTheCountsOfEveryFinishedPage() + { + using var doc = NewDocument(); + FinishedPage(doc, "TT1"); + FinishedPage(doc, "TT1", "TT2"); + doc.AddPage(); // never given a canvas + + Assert.Equal([(null, "TT1", null, 2), (null, "TT2", null, 1)], Project(doc.NotdefGlyphs)); + Assert.Equal(0, doc.NotdefGlyphsDropped); + } + + [Fact] + public void ADocumentWithNoGlyphZero_returnsTheSameEmptyList() + { + using var doc = NewDocument(); + FinishedPage(doc); + + Assert.Empty(doc.NotdefGlyphs); + Assert.Same(doc.NotdefGlyphs, doc.NotdefGlyphs); + } + + [Fact] + public void DrawingAfterFinish_isNotCountedUntilFinishRunsAgain() + { + using var doc = NewDocument(); + var page = doc.AddPage(); + var canvas = new PdfCanvas(page); + canvas.BeginText().SetFontByName("TT1", 12).ShowGlyphs([0]).EndText().Finish(); + + canvas.BeginText().ShowGlyphs([0]).EndText(); + Assert.Equal(2, Assert.Single(canvas.NotdefGlyphs).Count); + Assert.Equal(1, Assert.Single(doc.NotdefGlyphs).Count); + + canvas.Finish(); + Assert.Equal(2, Assert.Single(doc.NotdefGlyphs).Count); + } + + [Fact] + public void ASecondCanvasFinishedOnAPage_replacesTheFirstOnesEntries() + { + using var doc = NewDocument(); + var page = FinishedPage(doc, "TT1"); + Assert.Single(doc.NotdefGlyphs); + + new PdfCanvas(page).BeginText().EndText().Finish(); + + Assert.Empty(doc.NotdefGlyphs); + } + + [Fact] + public void SettingContentBytesDirectly_clearsThePagesEntries() + { + using var doc = NewDocument(); + var page = FinishedPage(doc, "TT1"); + Assert.Single(doc.NotdefGlyphs); + + page.ContentBytes = "BT <0000> Tj ET"u8.ToArray(); + + Assert.Empty(doc.NotdefGlyphs); + } + + [Fact] + public void TheDocumentList_isCappedAtAThousandEntries_andAddsEveryDropCount() + { + using var doc = NewDocument(); + FinishedPage(doc, [.. Enumerable.Range(0, 600).Select(i => $"A{i}")]); + FinishedPage(doc, [.. Enumerable.Range(0, 600).Select(i => $"B{i}")]); + + Assert.Equal(1000, doc.NotdefGlyphs.Count); + Assert.Equal(200, doc.NotdefGlyphsDropped); + + // A page whose own list already dropped adds that count to the document's. + FinishedPage(doc, [.. Enumerable.Range(0, 1002).Select(i => $"C{i}")]); + Assert.Equal(1000, doc.NotdefGlyphs.Count); + Assert.Equal(200 + 2 + 1000, doc.NotdefGlyphsDropped); + } + + private static (PdfDocument Doc, (string?, string?, string?, int)[] Expected) DocumentWithOneEntry() + { + var doc = NewDocument(); + var page = doc.AddPage(); + var handle = doc.UseTrueTypeFont(Font("DejaVuSans.ttf")); + doc.RegisterEmbeddedFontUsage(page, handle); + var canvas = new PdfCanvas(page); + canvas.BeginText().SetFontByName(handle.ResourceName, 12).ShowEmbeddedText(handle, "A\u26B9").EndText(); + canvas.Finish(); + return (doc, [("\u26B9", "TT1", "DejaVuSans", 1)]); + } + + [Fact] + public void ARefusedSaveAndTheSavesThatFollow_leaveTheDocumentListAsItWas() + { + var (doc, expected) = DocumentWithOneEntry(); + using var _ = doc; + Assert.Equal(expected, Project(doc.NotdefGlyphs)); + + using (var closed = new MemoryStream()) + { + closed.Dispose(); + Assert.ThrowsAny(() => doc.Save(closed)); + } + Assert.Equal(expected, Project(doc.NotdefGlyphs)); + + using var ms = new MemoryStream(); + doc.Save(ms); + Assert.Equal(expected, Project(doc.NotdefGlyphs)); + } + + [Fact] + public async Task SaveAsync_leavesTheDocumentListAsItWas() + { + var (doc, expected) = DocumentWithOneEntry(); + using var _ = doc; + + using var ms = new MemoryStream(); + await doc.SaveAsync(ms, TestContext.Current.CancellationToken); + + Assert.Equal(expected, Project(doc.NotdefGlyphs)); + } + + [Fact] + public void PrepareForSigning_leavesTheDocumentListAsItWas() + { + var (doc, expected) = DocumentWithOneEntry(); + using var _ = doc; + + doc.PrepareForSigning(new SignaturePlaceholderOptions + { + SigningTime = new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero), + }); + + Assert.Equal(expected, Project(doc.NotdefGlyphs)); + } +} diff --git a/tests/VellumPdf.Kernel.Tests/ToUnicodeLineEndTests.cs b/tests/VellumPdf.Kernel.Tests/ToUnicodeLineEndTests.cs index ca922611c..81509c334 100644 --- a/tests/VellumPdf.Kernel.Tests/ToUnicodeLineEndTests.cs +++ b/tests/VellumPdf.Kernel.Tests/ToUnicodeLineEndTests.cs @@ -144,7 +144,7 @@ private static byte[] SaveKernelDocument(byte[] font) private static int Count(byte[] data, byte value) => data.Count(b => b == value); /// The inflated body of every stream that starts with /CIDInit, which is only the ToUnicode maps. - private static List ToUnicodeMaps(byte[] pdf) + internal static List ToUnicodeMaps(byte[] pdf) { var text = Encoding.Latin1.GetString(pdf); var maps = new List(); diff --git a/tests/VellumPdf.Kernel.Tests/ToUnicodeStandInTests.cs b/tests/VellumPdf.Kernel.Tests/ToUnicodeStandInTests.cs index d2d99888f..fddf57f52 100644 --- a/tests/VellumPdf.Kernel.Tests/ToUnicodeStandInTests.cs +++ b/tests/VellumPdf.Kernel.Tests/ToUnicodeStandInTests.cs @@ -67,15 +67,16 @@ public void StandInsOnDifferentGlyphs_areBothListed() } /// - /// Code points that are not stand-ins are never dropped, whatever they share, glyph 0 included: - /// two missing characters both keep their .notdef entry. + /// Code points that are not stand-ins keep their entries, whatever glyph they share, except + /// glyph 0: the missing characters get one entry for it, U+FFFD, and no code point is listed + /// against it. /// [Fact] - public void CodePointsThatAreNotStandIns_keepTheirEntries_glyphZeroIncluded() + public void CodePointsThatAreNotStandIns_keepTheirEntries_glyphZeroGetsOneReplacementEntry() { var entries = Entries( new Dictionary { [0x4E00] = 0, [0x4E01] = 0, [0x41] = 36, [0x61] = 36 }); - Assert.Equal([(0, 0x4E00), (0, 0x4E01), (36, 0x41), (36, 0x61)], entries); + Assert.Equal([(0, 0xFFFD), (36, 0x41), (36, 0x61)], entries); } } diff --git a/tests/VellumPdf.Kernel.Tests/VellumPdf.Kernel.Tests.csproj b/tests/VellumPdf.Kernel.Tests/VellumPdf.Kernel.Tests.csproj index 8f63848dc..704239eb2 100644 --- a/tests/VellumPdf.Kernel.Tests/VellumPdf.Kernel.Tests.csproj +++ b/tests/VellumPdf.Kernel.Tests/VellumPdf.Kernel.Tests.csproj @@ -28,6 +28,7 @@ + From 111e4ef14edb5316270bf02d02f931aed4c7880c Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sat, 21 Nov 2026 09:51:13 +0100 Subject: [PATCH 2/4] feat(layout): report glyph 0 and unembedded fonts under a claim (#592, #593) The layout now reports through Document.Diagnostics what a PDF/A or PDF/UA file fails on without saying so. NotdefGlyph (102) lists each character an embedded font has no glyph for, per font, with its count. UnembeddedFont (601) lists each element that selects a Standard 14 font while a conformance claim is set, which is what a list, table, heading or running band without its own style does because SetDefaultFont reaches only Document.Add(string). Both cite the clause of the claim, save by default and are refused by StrictDiagnostics. Paragraphs, table cells and running bands now select the font and show text through one TextEmitter, so one report covers every built-in element. The bytes written do not change. --- CHANGELOG.md | 29 ++ src/VellumPdf.Layout/Core/TextStyle.cs | 28 ++ src/VellumPdf.Layout/Document.cs | 81 +++- src/VellumPdf.Layout/Elements/Heading.cs | 14 + src/VellumPdf.Layout/Elements/ListElement.cs | 15 + src/VellumPdf.Layout/Elements/ListItem.cs | 14 + src/VellumPdf.Layout/Elements/Paragraph.cs | 15 + src/VellumPdf.Layout/Elements/RunningBand.cs | 16 +- src/VellumPdf.Layout/Elements/Table/Cell.cs | 19 +- .../Elements/Table/TableElement.cs | 14 + src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 60 ++- src/VellumPdf.Layout/PublicAPI.Unshipped.txt | 2 + .../Rendering/DocumentRenderer.cs | 26 +- .../Rendering/LayoutDiagnosticSink.cs | 124 +++++- .../Rendering/ParagraphRenderer.cs | 51 +-- .../Rendering/Table/TableRenderer.cs | 28 +- src/VellumPdf.Layout/Rendering/TextEmitter.cs | 76 ++++ .../FontReportByteIdentityTests.cs | 166 ++++++++ .../FontReportSupport.cs | 113 +++++ .../NotdefGlyphReportTests.cs | 401 ++++++++++++++++++ .../UnembeddedFontReportTests.cs | 324 ++++++++++++++ .../VellumPdf.Layout.Tests.csproj | 1 + tests/VellumPdf.TestSupport/ExternalTool.cs | 5 +- 23 files changed, 1515 insertions(+), 107 deletions(-) create mode 100644 src/VellumPdf.Layout/Rendering/TextEmitter.cs create mode 100644 tests/VellumPdf.Layout.Tests/FontReportByteIdentityTests.cs create mode 100644 tests/VellumPdf.Layout.Tests/FontReportSupport.cs create mode 100644 tests/VellumPdf.Layout.Tests/NotdefGlyphReportTests.cs create mode 100644 tests/VellumPdf.Layout.Tests/UnembeddedFontReportTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 65cb120c2..7be545abe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,6 +62,26 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - The marker the library draws on a list item, such as the nested bullet in a Standard 14 font, is not listed as an unencodable character when the document draws the list. A list that your own renderer draws through a `DrawContext` you built can still list it. +- **`PdfCanvas.NotdefGlyphs`, `PdfDocument.NotdefGlyphs` and `NotdefGlyphWarning` (#592).** A + character an embedded font has no glyph for is written as glyph 0, and until now nothing said + so. `PdfCanvas.NotdefGlyphs` lists each glyph 0 the canvas writes, one entry per character and + font resource in order of first occurrence, with a `Count`; `PdfDocument.NotdefGlyphs` gathers + the lists of the pages whose canvas was finished. `Character` is null for glyph ids passed to + `PdfCanvas.ShowGlyphs`, because the canvas sees ids and not text. Each list holds at most 1,000 + entries, and `NotdefGlyphsDropped` counts the rest. `TextEncodingWarnings` is unchanged and does + not list glyph 0. +- **`LayoutDiagnosticCode.NotdefGlyph` (#592).** The layout reports each character and font + that was written as glyph 0, with the count, in `Document.Diagnostics`: built-in elements, list + markers and running bands name the character, and a custom renderer that passes glyph ids is + reported with the character unknown. The clause is ISO 19005-2:2011, 6.2.11.8 under a PDF/A + claim and ISO 14289-1:2014, 7.21.8 under PDF/UA-1; it is null with no claim. The save still + succeeds. `StrictDiagnostics` refuses it. +- **`LayoutDiagnosticCode.UnembeddedFont` (#593).** While `Document.Conformance` is not `None`, + each element that selects a named Standard 14 font is reported once per element and font, with + the number of font operators it wrote. A list, table, heading, paragraph or running band + without a style of its own reaches this, because `SetDefaultFont` still applies only to + `Document.Add(string)`. The clause is ISO 19005-2:2011, 6.2.11.4.1 or ISO 14289-1:2014, + 7.21.4.1. The save still succeeds, and `StrictDiagnostics` refuses it. - **Internal name tree and number tree writers (#241).** `NameTreeWriter` and `NumberTreeWriter` in `VellumPdf.Kernel` build the structures ISO 32000-2, 7.9.6 and 7.9.7 define, which the catalog's `/Names` and `/PageLabels` entries, and later named destinations and embedded files, @@ -243,6 +263,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **The ToUnicode map no longer lists a code point against glyph 0 (#592).** A font whose + subset used glyph 0 wrote one `<0000> <...>` line per missing character. On a test file with + U+26B9 and U+1F31F, pdftotext (poppler 26.08) extracted U+1F31F for both. The map now has one entry for glyph 0, + `<0000> `, and no other. A document that draws no glyph 0 is unchanged byte for byte. A + document that does changes only in that stream; the content stream still shows glyph 0. + + **Attention:** the file still references `.notdef`, so veraPDF still fails ISO 19005-2, + 6.2.11.8 and ISO 14289-1, 7.21.8. The reports above are how to find it. + - **On .NET 10 an empty stream was written as `/FlateDecode` with no data (#640).** `PdfStream` compressed through `ZLibStream`, which on .NET 10.0.15 writes nothing for empty input, so an empty page's `/Contents` came out as `/Filter /FlateDecode /Length 0` with an empty body, which is not diff --git a/src/VellumPdf.Layout/Core/TextStyle.cs b/src/VellumPdf.Layout/Core/TextStyle.cs index 8d24b92d8..28010e35a 100644 --- a/src/VellumPdf.Layout/Core/TextStyle.cs +++ b/src/VellumPdf.Layout/Core/TextStyle.cs @@ -23,6 +23,11 @@ public TextStyle() { } /// A style with default values (Helvetica, 12 pt, auto leading, black). /// /// One shared instance. Every property of this type is init-only, so it cannot change. + /// Its font is Helvetica, which is not embedded. Elements without a style of their own + /// fall back to it, and under a PDF/A or PDF/UA + /// the save reports each as + /// ; see + /// . /// public static readonly TextStyle Default = new(); @@ -51,6 +56,22 @@ public TextStyle() { } /// it throws instead of saving. Do not pass text /// the font cannot encode; use an embedded font. A later major version refuses it /// always. + /// An embedded font writes a character it has no glyph for as glyph 0, the .notdef + /// glyph. The save lists each such character and font in + /// as + /// , with the clause that + /// forbids it under a PDF/A or PDF/UA claim, and still saves. The font's ToUnicode map gives + /// glyph 0 the one entry U+FFFD. Do not pass text the font cannot draw to such a + /// document. A later major version refuses it always. + /// A Standard 14 font is not embedded. While + /// is not + /// , each element whose style selects one + /// is listed in as + /// , once per element and + /// font, and the save still succeeds. With + /// set, either report refuses the + /// save. Do not pass a Standard 14 font under either claim. A later major version + /// refuses it always. /// /// /// Raised from and the other @@ -67,6 +88,13 @@ public TextStyle() { } /// paragraph that share one style instance is joined and measured as a pair, so it saves; split /// between runs of different instances, each half is unpaired and the save throws. /// + /// + /// Raised from the save, not from this property, when + /// is set and text in this style is + /// written as glyph 0, or the style selects a Standard 14 font under a conformance claim; see + /// and + /// . + /// public FontReference FontRef { get; init; } = Standard14.Helvetica; /// diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index 133cd6f34..71f326517 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -86,6 +86,9 @@ public Document() { } /// it is until 3.0. holds the same substitutions grouped by /// character; see for what it leaves /// out. + /// A character an embedded font has no glyph for is written as glyph 0, not as '?', and + /// is not listed here. reports it in + /// . /// public IReadOnlyList TextEncodingWarnings => _textEncodingWarnings; @@ -108,6 +111,9 @@ public Document() { } /// ?, mirroring ), /// and /// (a null below the second level of a list), + /// (a character an embedded font has no glyph + /// for, written as glyph 0), (an element that + /// selects a Standard 14 font under a conformance claim), /// (mirroring ) /// and . Every one saves by default; only /// refuses it, and a later major version refuses them @@ -122,8 +128,15 @@ public Document() { } /// written as ? on the document's canvas is still listed, because it is read from the /// canvas after each element is drawn, whichever renderer wrote it. The one exception is text /// the library wrote itself: the marker of a built-in list is not listed when the document - /// draws the list, and through a context you built it can be. Callers of the Kernel alone have - /// no channel, and + /// draws the list, and through a context you built it can be. Glyph 0 that a custom renderer + /// writes with on the + /// document's canvas is listed as , with the + /// character unknown, whichever renderer wrote it. A context you construct reports no + /// , a Standard 14 font that a renderer + /// fetches with and never selects + /// is not reported, and neither is one that a renderer selects with its own + /// call. Callers of + /// the Kernel alone have no channel, and /// exposes /// none. /// Input that is refused is thrown, not listed. Do not read an empty list as proof that @@ -247,12 +260,26 @@ public PdfRectangle PageSize /// forbids the Encrypt key in a PDF/A file. For PDF/UA-1 it throws only when the /// encryption settings leave out , because ISO 14289-1, /// 7.16, requires the permission that allows extraction for accessibility. + /// With a level set, the save reports an element that selects a Standard 14 font, such as + /// the Helvetica a list, table, heading, paragraph or running band without its own style falls + /// back to, as , and a character an embedded + /// font has no glyph for as . Both save unless + /// is set; see . + /// does not reach those elements. Do not pass a style with + /// a Standard 14 font, or text the font cannot draw, to a PDF/A or PDF/UA document. A later + /// major version refuses it always. /// /// /// Raised from and the other save overloads, when /// has been called and this is a PDF/A level or a value the enumeration /// does not name, or PDF/UA-1 without . /// + /// + /// Raised from the same calls, not from this setter, when is + /// set and the document has a level and writes a Standard 14 font or a glyph 0; the save + /// reports them as and + /// . + /// public PdfConformance Conformance { get => _pdf.Conformance; @@ -472,6 +499,14 @@ public byte[]? DocumentId /// style in force when it is called, so text added before this call keeps the earlier /// style, and a , , list, table or running band /// never uses it. Give those their own style. + /// A list, table, paragraph, heading or running band without a style of its own does not + /// take this one. The font is then Helvetica, which is not embedded. While + /// is not + /// the save reports the element as + /// in and + /// still saves; only refuses it. Do not leave the + /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded + /// font. A later major version refuses it always. /// A null style is stored. A later then uses /// . /// The style is not checked here. Its refusals are raised from the save, for the text @@ -494,6 +529,12 @@ public byte[]? DocumentId /// call, when text a later adds in this style holds an /// unpaired surrogate and is measured in an embedded font; see . /// + /// + /// Raised from and the other save overloads, not + /// from here, when is set, the document has a + /// conformance claim and the element writes Helvetica or another Standard 14 font; the save + /// reports it as . + /// public Document SetDefaultFont(TextStyle style) { _defaultStyle = style; return this; } /// Sets a header band with optional style and alignment. Returns this document for chaining. @@ -507,11 +548,25 @@ public byte[]? DocumentId /// and . /// and values the enumeration does not name are drawn /// left-aligned; see . + /// A null is , not the style set + /// with . The font is then Helvetica, which is not embedded. While + /// is not + /// the save reports the element as + /// in and + /// still saves; only refuses it. Do not leave the + /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded + /// font. A later major version refuses it always. /// /// /// is . /// /// + /// + /// Raised from and the other save overloads, not + /// from here, when is set, the document has a + /// conformance claim and the element writes Helvetica or another Standard 14 font; the save + /// reports it as . + /// public Document SetHeader(string template, TextStyle? style = null, HorizontalAlignment alignment = HorizontalAlignment.Center) { Header = new RunningBand(template, style, alignment); @@ -529,11 +584,25 @@ public Document SetHeader(string template, TextStyle? style = null, HorizontalAl /// and . /// and values the enumeration does not name are drawn /// left-aligned; see . + /// A null is , not the style set + /// with . The font is then Helvetica, which is not embedded. While + /// is not + /// the save reports the element as + /// in and + /// still saves; only refuses it. Do not leave the + /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded + /// font. A later major version refuses it always. /// /// /// is . /// /// + /// + /// Raised from and the other save overloads, not + /// from here, when is set, the document has a + /// conformance claim and the element writes Helvetica or another Standard 14 font; the save + /// reports it as . + /// public Document SetFooter(string template, TextStyle? style = null, HorizontalAlignment alignment = HorizontalAlignment.Center) { Footer = new RunningBand(template, style, alignment); @@ -884,6 +953,14 @@ public Document Add(Heading heading) /// With null, the paragraph takes the style from the most recent /// call made before this one. /// A null is refused here. + /// When no style was set with and + /// is null, the paragraph takes . The font is then Helvetica, + /// which is not embedded. While is not + /// the save reports the element as + /// in and + /// still saves; only refuses it. Do not leave the + /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded + /// font. A later major version refuses it always. /// /// /// is . diff --git a/src/VellumPdf.Layout/Elements/Heading.cs b/src/VellumPdf.Layout/Elements/Heading.cs index 0a1f87cff..95730316f 100644 --- a/src/VellumPdf.Layout/Elements/Heading.cs +++ b/src/VellumPdf.Layout/Elements/Heading.cs @@ -125,11 +125,25 @@ public sealed class Heading /// A null becomes 14pt Helvetica. A null is /// refused here. An empty string is not /// null and is accepted. + /// A null is not the style set with + /// . The font is then Helvetica, which is not embedded. + /// While is not + /// the save reports the element as + /// in and + /// still saves; only refuses it. Do not leave the + /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded + /// font. A later major version refuses it always. /// /// /// is . /// /// + /// + /// Raised from and the other save overloads, not + /// from here, when is set, the document has a + /// conformance claim and the element writes Helvetica or another Standard 14 font; the save + /// reports it as . + /// public Heading(string text, TextStyle? style = null) { ArgumentNullException.ThrowIfNull(text); diff --git a/src/VellumPdf.Layout/Elements/ListElement.cs b/src/VellumPdf.Layout/Elements/ListElement.cs index c5e8c3f37..771500133 100644 --- a/src/VellumPdf.Layout/Elements/ListElement.cs +++ b/src/VellumPdf.Layout/Elements/ListElement.cs @@ -136,6 +136,15 @@ public sealed class ListElement /// Used by a top-level item with no style of its own, and through that item by its children. /// Null means . Refusals on size, leading, font and text colour /// are on and are raised from the save. + /// A list with no default style does not take ; its + /// items, and the marker of each, take , so an item is reported + /// twice. The font is then Helvetica, which is not embedded. While + /// is not + /// the save reports the element as + /// in and + /// still saves; only refuses it. Do not leave the + /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded + /// font. A later major version refuses it always. /// /// /// @@ -143,6 +152,12 @@ public sealed class ListElement /// from this property, when text in this style holds an unpaired surrogate and is measured in /// an embedded font; see . /// + /// + /// Raised from and the other save overloads, not + /// from here, when is set, the document has a + /// conformance claim and the element writes Helvetica or another Standard 14 font; the save + /// reports it as . + /// public TextStyle? DefaultStyle { get; init; } /// Creates a list with the given marker style and optional initial items. diff --git a/src/VellumPdf.Layout/Elements/ListItem.cs b/src/VellumPdf.Layout/Elements/ListItem.cs index ec934a27b..03923c2b7 100644 --- a/src/VellumPdf.Layout/Elements/ListItem.cs +++ b/src/VellumPdf.Layout/Elements/ListItem.cs @@ -36,6 +36,14 @@ public sealed class ListItem /// . On a child, null means the parent item's style after that /// same fallback. Refusals on size, leading, font and text colour are on /// and are raised from the save. + /// An item that resolves to no style of its own does not take + /// . The font is then Helvetica, which is not embedded. + /// While is not + /// the save reports the element as + /// in and + /// still saves; only refuses it. Do not leave the + /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded + /// font. A later major version refuses it always. /// /// /// Raised from and the other save overloads, not @@ -57,6 +65,12 @@ public sealed class ListItem /// an embedded font; see . /// It is not raised for an item reached only as a child of a child. /// + /// + /// Raised from and the other save overloads, not + /// from here, when is set, the document has a + /// conformance claim and the element writes Helvetica or another Standard 14 font; the save + /// reports it as . + /// public TextStyle? Style { get; init; } /// diff --git a/src/VellumPdf.Layout/Elements/Paragraph.cs b/src/VellumPdf.Layout/Elements/Paragraph.cs index d8a3d5855..a2508c452 100644 --- a/src/VellumPdf.Layout/Elements/Paragraph.cs +++ b/src/VellumPdf.Layout/Elements/Paragraph.cs @@ -136,6 +136,15 @@ public sealed class Paragraph /// A null becomes . A null /// is refused here. An empty string is not /// null and is accepted. + /// A null is not the style set with + /// ; only + /// reads that. The font is then Helvetica, which is not embedded. While + /// is not + /// the save reports the element as + /// in and + /// still saves; only refuses it. Do not leave the + /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded + /// font. A later major version refuses it always. /// /// /// is . @@ -157,6 +166,12 @@ public sealed class Paragraph /// the enumeration does not name and the font is selected on a page; see /// . /// + /// + /// Raised from and the other save overloads, not + /// from here, when is set, the document has a + /// conformance claim and the element writes Helvetica or another Standard 14 font; the save + /// reports it as . + /// public Paragraph(string text, TextStyle? style = null) { ArgumentNullException.ThrowIfNull(text); diff --git a/src/VellumPdf.Layout/Elements/RunningBand.cs b/src/VellumPdf.Layout/Elements/RunningBand.cs index c78866628..b0e7553e1 100644 --- a/src/VellumPdf.Layout/Elements/RunningBand.cs +++ b/src/VellumPdf.Layout/Elements/RunningBand.cs @@ -137,11 +137,19 @@ public sealed class RunningBand /// Creates a running band from a text template, with optional style and alignment (defaults to centered). /// - /// A null becomes . A null + /// A null becomes , not the style set + /// with . A null /// is stored, and refuses it where the band is /// drawn, with . It is not refused earlier, because a band /// that is replaced before the save never reaches . Do not pass a /// null template: 3.0 refuses it here. An empty template is not null and is accepted. + /// The font of a band with no style is Helvetica, which is not embedded. While + /// is not + /// the save reports the element as + /// in and + /// still saves; only refuses it. Do not leave the + /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded + /// font. A later major version refuses it always. /// /// /// Raised from and the other save overloads, not from @@ -168,6 +176,12 @@ public sealed class RunningBand /// the enumeration does not name and the font is selected on a page; see /// . /// + /// + /// Raised from and the other save overloads, not + /// from here, when is set, the document has a + /// conformance claim and the element writes Helvetica or another Standard 14 font; the save + /// reports it as . + /// public RunningBand(string template, TextStyle? style = null, HorizontalAlignment alignment = HorizontalAlignment.Center) { Template = template; diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 37de770d7..62a9aaa10 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -23,7 +23,9 @@ public sealed class Cell /// between characters. A line feed, carriage return or tab is not a break. In a standard-14 /// font each is written into the cell as it is; in an embedded font each is drawn as whatever /// glyph the font's character map gives it, which is .notdef (glyph 0) when the map has no - /// entry. + /// entry. The save lists each such character as + /// , and + /// refuses it; see . /// /// public string Content { get; } @@ -98,9 +100,24 @@ public sealed class Cell /// . Refusals on size, leading, font and text colour are on /// and are raised from the save. A in /// it is ignored (#475). + /// A cell with no style, in a table with no , + /// does not take ; it takes + /// . An empty cell reaches this too. The font is then Helvetica, + /// which is not embedded. While is not + /// the save reports the element as + /// in and + /// still saves; only refuses it. Do not leave the + /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded + /// font. A later major version refuses it always. /// /// /// + /// + /// Raised from and the other save overloads, not + /// from here, when is set, the document has a + /// conformance claim and the element writes Helvetica or another Standard 14 font; the save + /// reports it as . + /// public TextStyle? Style { get; init; } /// Inner padding between the cell border and its content. diff --git a/src/VellumPdf.Layout/Elements/Table/TableElement.cs b/src/VellumPdf.Layout/Elements/Table/TableElement.cs index ffbdc51f3..5ebdbd04a 100644 --- a/src/VellumPdf.Layout/Elements/Table/TableElement.cs +++ b/src/VellumPdf.Layout/Elements/Table/TableElement.cs @@ -36,9 +36,23 @@ public TableElement() { } /// Null means for cells that have no style of their own. /// Refusals on size, leading, font and text colour are on and are /// raised from the save. A in it is ignored. + /// A table with no default cell style does not take + /// ; its cells take . The + /// font is then Helvetica, which is not embedded. While is + /// not the save reports the element as + /// in and + /// still saves; only refuses it. Do not leave the + /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded + /// font. A later major version refuses it always. /// /// /// + /// + /// Raised from and the other save overloads, not + /// from here, when is set, the document has a + /// conformance claim and the element writes Helvetica or another Standard 14 font; the save + /// reports it as . + /// public TextStyle? DefaultCellStyle { get; init; } /// Width of the table border lines, in points. diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index 95b1e926b..6590ebe6d 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -22,10 +22,10 @@ namespace VellumPdf.Layout; public enum LayoutDiagnosticCode { // Reserved, not defined here, so that later members do not collide: - // 102 NotdefGlyph, 104 PreformattedLineWrapped (Warning), 105 SymbolFontMeasuredAsZero + // 104 PreformattedLineWrapped (Warning), 105 SymbolFontMeasuredAsZero // (Error), 203 ListIndentClamped, 204 ListDepthCapped, 205 ListEntriesCapped, 206 // ListEntrySkipped (all Error), 301 ControlCharacterInCell (Warning), 302 SurplusCell - // (Error), 402 UnknownBandToken, 601 UnembeddedFont, one 7xx member for a link dropped from + // (Error), 402 UnknownBandToken, one 7xx member for a link dropped from // a cell or band under a PDF/UA claim, and the 8xx block for pagination reports. /// @@ -41,6 +41,34 @@ public enum LayoutDiagnosticCode /// NullTextRunStyle = 101, + /// + /// A character that an embedded font has no glyph for was written as glyph 0, the + /// .notdef glyph. Each distinct character in each font is one item, whose + /// is the number of times it was written, and whose + /// message names the character and the font. + /// + /// + /// Strict mode refuses it. Under a PDF/A claim the item's + /// is ISO 19005-2:2011, 6.2.11.8, which forbids a + /// reference to the .notdef glyph from any text-showing operator, and under PDF/UA-1 it + /// is ISO 14289-1:2014, 7.21.8. With no claim the clause is null, because plain PDF + /// permits showing glyph 0 and the item is still reported. The save writes the glyph anyway, + /// and the font's ToUnicode map gives glyph 0 one entry, U+FFFD. + /// The built-in elements, running bands and list markers report the character. A custom + /// renderer that writes glyph ids with + /// on the + /// document's canvas is reported with the character unknown, named by the resource name of the + /// last font it selected. Glyph 0 written to a canvas that is not the document's, or by a + /// renderer's own bytes on the page, is not seen. Text a font draws through a stand-in glyph, + /// such as U+202F in a font without it, is not glyph 0 and is not reported. Characters in a + /// Standard 14 font are never glyph 0; those the font cannot encode are + /// . + /// What is drawn is whatever the font's .notdef glyph holds. Do not pass + /// text the font cannot draw to a PDF/A or PDF/UA document; give the element a font that covers + /// it. + /// + NotdefGlyph = 102, + /// /// A character that the font's encoding cannot represent was written as ?. That is a /// character outside WinAnsiEncoding in Standard 14 text, and in text a custom renderer passes @@ -102,6 +130,34 @@ public enum LayoutDiagnosticCode /// BandTruncated = 401, + /// + /// An element wrote a font selection for a named Standard 14 font while + /// is not + /// , so the file refers to a font that is + /// not embedded. Each distinct element and font is one item, and + /// is the number of font selections the element wrote in + /// that font, which is not the number of runs or lines. + /// + /// + /// Strict mode refuses it. The item's is ISO + /// 19005-2:2011, 6.2.11.4.1 under a PDF/A claim and ISO 14289-1:2014, 7.21.4.1 under + /// PDF/UA-1; both require the font programs of every font used for rendering to be embedded, + /// and neither exempts the Standard 14. The save writes the file as it always has. + /// applies only to + /// with a string, so a paragraph, heading, + /// list, table or running band without its own embedded style reaches this. + /// A selection is reported when the font operator is written, whether or not any text + /// follows it, so an empty table cell in Helvetica is reported. Not reported: a Standard 14 + /// font that a custom renderer selects on the canvas itself, or fetches with + /// and never selects, a + /// you construct, and a + /// value the enumeration does not name, which makes the save throw + /// as before. Do not pass a style with a Standard + /// 14 font to an element of a PDF/A or PDF/UA document, and set the style of lists, tables and + /// running bands yourself. + /// + UnembeddedFont = 601, + /// /// The save dropped reports because the channel holds at most 1,000 distinct items. /// is the number of occurrences dropped, not the number of diff --git a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt index 24a53bd27..dfeb9daef 100644 --- a/src/VellumPdf.Layout/PublicAPI.Unshipped.txt +++ b/src/VellumPdf.Layout/PublicAPI.Unshipped.txt @@ -41,3 +41,5 @@ override VellumPdf.Layout.LayoutDiagnostic.ToString() -> string! VellumPdf.Layout.Core.DrawContext.AddOutlineEntry(string! title, int level, double layoutY, bool expanded) -> void VellumPdf.Layout.Elements.Heading.BookmarkExpanded.get -> bool VellumPdf.Layout.Elements.Heading.BookmarkExpanded.init -> void +VellumPdf.Layout.LayoutDiagnosticCode.NotdefGlyph = 102 -> VellumPdf.Layout.LayoutDiagnosticCode +VellumPdf.Layout.LayoutDiagnosticCode.UnembeddedFont = 601 -> VellumPdf.Layout.LayoutDiagnosticCode diff --git a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs index e759309c8..4d0c7ad31 100644 --- a/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/DocumentRenderer.cs @@ -853,6 +853,7 @@ private void DrawRenderer(IRenderer renderer) // Reports come from this pass only. The page counting pass lays out without drawing, and a // wrap is cached per renderer, so a report raised from Layout could run twice. _sink.CurrentPage = _pdf.Pages.Count; + _sink.Conformance = _pdf.Conformance; try { renderer.Draw(ctx); @@ -877,6 +878,7 @@ private void DrawRunningBands( var pageBounds = new LayoutBox(0, 0, _pageSize.Width, _pageSize.Height); var ctx = new DrawContext(canvas, pageBounds, rendererCtx, _pdf, page) { Diagnostics = _sink }; _sink.CurrentPage = pageNumber; + _sink.Conformance = _pdf.Conformance; _sink.CurrentIndex = null; if (Header is not null) @@ -982,25 +984,11 @@ private void DrawBandText( // untagged real content. if (ctx.Tagged) canvas.BeginArtifactMarkedContent(); canvas.BeginText(); - if (style.FontRef.IsEmbedded) - { - var resourceName = ctx.UseEmbeddedFont(style.FontRef.Embedded); - canvas.SetFontByName(resourceName, style.FontSize); - canvas.SetFillColorRgb(style.Color.R, style.Color.G, style.Color.B); - // Show using glyph IDs - var gids = new ushort[drawn.Length]; - var count = style.FontRef.Embedded.GetGlyphIds(drawn, gids); - canvas.SetTextMatrix(1, 0, 0, 1, x, pdfY); - canvas.ShowGlyphs(gids.AsSpan(0, count)); - } - else - { - var fontResource = ctx.GetFont(style.Font); - canvas.SetFont(fontResource, style.FontSize); - canvas.SetFillColorRgb(style.Color.R, style.Color.G, style.Color.B); - canvas.SetTextMatrix(1, 0, 0, 1, x, pdfY); - canvas.ShowText(drawn); - } + FontReference? bandFont = null; + TextEmitter.SelectFont(ctx, canvas, style, ref bandFont); + canvas.SetFillColorRgb(style.Color.R, style.Color.G, style.Color.B); + canvas.SetTextMatrix(1, 0, 0, 1, x, pdfY); + TextEmitter.Show(canvas, style, drawn); canvas.EndText(); if (ctx.Tagged) canvas.EndMarkedContent(); } diff --git a/src/VellumPdf.Layout/Rendering/LayoutDiagnosticSink.cs b/src/VellumPdf.Layout/Rendering/LayoutDiagnosticSink.cs index da083623a..7e6ee81da 100644 --- a/src/VellumPdf.Layout/Rendering/LayoutDiagnosticSink.cs +++ b/src/VellumPdf.Layout/Rendering/LayoutDiagnosticSink.cs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 using VellumPdf.Canvas; +using VellumPdf.Document; namespace VellumPdf.Layout.Rendering; @@ -39,6 +40,20 @@ internal sealed class LayoutDiagnosticSink private PdfCanvas? _syncedCanvas; private int _syncedCount; + // The glyph-0 entries of that canvas already accounted for: the count read for each entry by + // index, the dropped count, and the tally's total of occurrences, which is what tells a page + // that wrote none from one that did. + private readonly List _notdefCounts = []; + private int _notdefDropped; + private int _notdefTotal; + private Dictionary? _fontOrdinals; + + /// + /// The claim of the document being drawn. Assigned where the document's draw context is made, + /// so a context a caller constructs has none and reports no conformance item. + /// + internal PdfConformance Conformance { get; set; } + /// The location the next report is attributed to, set by the renderer that drives the /// layout. internal LayoutElementKind CurrentKind { get; set; } = LayoutElementKind.Document; @@ -66,8 +81,9 @@ internal void Report( long subject, string message, int count = 1, - bool perElement = false) => - ReportCore(code, subject, message, null, count, perElement); + bool perElement = false, + string? clause = null) => + ReportCore(code, subject, message, null, count, perElement, clause); /// /// runs only when the subject is new, so a repeat allocates nothing @@ -78,8 +94,9 @@ internal void Report( long subject, Func message, int count = 1, - bool perElement = false) => - ReportCore(code, subject, null, message, count, perElement); + bool perElement = false, + string? clause = null) => + ReportCore(code, subject, null, message, count, perElement, clause); private void ReportCore( LayoutDiagnosticCode code, @@ -87,7 +104,8 @@ private void ReportCore( string? text, Func? textFor, int count, - bool perElement) + bool perElement, + string? clause) { var isError = LayoutDiagnostic.SeverityOf(code) == LayoutDiagnosticSeverity.Error; if (isError) ErrorReports = Saturate(ErrorReports, count); @@ -109,15 +127,17 @@ private void ReportCore( } var item = new LayoutDiagnostic( - code, text ?? textFor!(subject), null, CurrentKind, CurrentIndex, CurrentPage, count); + code, text ?? textFor!(subject), clause, CurrentKind, CurrentIndex, CurrentPage, count); (_byKey ??= []).Add(key, item); (_items ??= []).Add(item); } /// - /// Accounts for the characters the canvas has substituted since the last call. With - /// false they are skipped: text the library wrote itself, such as a - /// list marker, is not the caller's and is not listed. + /// Accounts for what the canvas has written since the last call. The characters it substituted + /// with '?' are skipped when is false: text the library wrote itself, + /// such as a list marker, is not the caller's and is not listed. A glyph 0 is reported whatever + /// says, because the file fails the same clause however the character + /// got there and the caller chose the font. /// internal void SyncEncodingWarnings(PdfCanvas canvas, bool report) { @@ -125,6 +145,9 @@ internal void SyncEncodingWarnings(PdfCanvas canvas, bool report) { _syncedCanvas = canvas; _syncedCount = 0; + _notdefCounts.Clear(); + _notdefDropped = 0; + _notdefTotal = 0; } var warnings = canvas.TextEncodingWarnings; @@ -138,8 +161,91 @@ internal void SyncEncodingWarnings(PdfCanvas canvas, bool report) System.Globalization.CultureInfo.InvariantCulture, $"U+{codePoint:X4} is not in WinAnsiEncoding and is written as '?' for each UTF-16 code unit.")); } + + SyncNotdefGlyphs(canvas); } + // One comparison for a page that wrote no glyph 0, or none since the last read. + private void SyncNotdefGlyphs(PdfCanvas canvas) + { + if (canvas.NotdefTally is not { } tally || tally.Total == _notdefTotal) return; + _notdefTotal = tally.Total; + + var entries = tally.Entries; + for (var i = 0; i < entries.Count; i++) + { + var entry = entries[i]; + var seen = i < _notdefCounts.Count ? _notdefCounts[i] : 0; + var increase = entry.Count - seen; + if (i < _notdefCounts.Count) _notdefCounts[i] = entry.Count; + else _notdefCounts.Add(entry.Count); + if (increase <= 0) continue; + + var codePoint = NotdefGlyphTally.CodePointOf(entry.Character); + var subject = ((long)FontOrdinal(entry.FontResourceName) << 32) | (uint)codePoint; + Report( + LayoutDiagnosticCode.NotdefGlyph, + subject, + _ => NotdefMessage(entry), + increase, + perElement: false, + clause: ClauseFor(LayoutDiagnosticCode.NotdefGlyph, Conformance)); + } + + var dropped = tally.Dropped - _notdefDropped; + if (dropped > 0) + { + _notdefDropped = tally.Dropped; + AddDropped(dropped); + } + } + + private int FontOrdinal(string? resource) + { + _fontOrdinals ??= new(StringComparer.Ordinal); + var key = resource ?? ""; + if (!_fontOrdinals.TryGetValue(key, out var ordinal)) + _fontOrdinals[key] = ordinal = _fontOrdinals.Count; + return ordinal; + } + + private static string NotdefMessage(NotdefGlyphWarning entry) => + entry.Character is { } rune + ? string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"U+{rune.Value:X4} has no glyph in {entry.FontName} ({entry.FontResourceName}) and is drawn as glyph 0 (.notdef).") + : string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"Glyph 0 (.notdef) was drawn in font {entry.FontResourceName ?? "(none selected)"} from glyph ids passed to PdfCanvas.ShowGlyphs, so the character is not known."); + + /// + /// Counts error occurrences the canvas could not store, so + /// appears and strict mode refuses the + /// save. + /// + internal void AddDropped(int count) + { + ErrorReports = Saturate(ErrorReports, count); + _dropped = Saturate(_dropped, count); + } + + /// + /// The clause a report breaks under the claim, in the format the conformance package cites, or + /// null when no standard forbids it: plain PDF permits showing glyph 0, and a document with no + /// claim has no embedding requirement. + /// + internal static string? ClauseFor(LayoutDiagnosticCode code, PdfConformance conformance) => + (code, conformance) switch + { + (LayoutDiagnosticCode.NotdefGlyph, PdfConformance.None) => null, + (LayoutDiagnosticCode.NotdefGlyph, PdfConformance.PdfUA1) => "ISO 14289-1:2014, 7.21.8", + (LayoutDiagnosticCode.NotdefGlyph, _) => "ISO 19005-2:2011, 6.2.11.8", + (LayoutDiagnosticCode.UnembeddedFont, PdfConformance.None) => null, + (LayoutDiagnosticCode.UnembeddedFont, PdfConformance.PdfUA1) => "ISO 14289-1:2014, 7.21.4.1", + (LayoutDiagnosticCode.UnembeddedFont, _) => "ISO 19005-2:2011, 6.2.11.4.1", + _ => null, + }; + /// The stored items in first-occurrence order, then the sentinel when anything was /// dropped. internal List Snapshot() diff --git a/src/VellumPdf.Layout/Rendering/ParagraphRenderer.cs b/src/VellumPdf.Layout/Rendering/ParagraphRenderer.cs index f8040af54..2082a5c4a 100644 --- a/src/VellumPdf.Layout/Rendering/ParagraphRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/ParagraphRenderer.cs @@ -372,11 +372,11 @@ public void Draw(DrawContext ctx) var linkStartX = curX; foreach (var frag in fragments) { - SwitchFont(canvas, ctx, frag.Style, ref currentFont); + TextEmitter.SelectFont(ctx, canvas, frag.Style, ref currentFont); SwitchColor(canvas, frag.Style, ref currentColor); canvas.SetTextMatrix(1, 0, 0, 1, curX, linePdfY); - ShowText(canvas, frag.Style, frag.Text); + TextEmitter.Show(canvas, frag.Style, frag.Text); // Tw widens every space the fragment holds, so the fragment is drawn that much // wider than the width it was measured at. The next fragment starts after the @@ -470,10 +470,10 @@ private static void DrawJustifiedEmbeddedLine( for (var t = 0; t < tokens.Count; t++) { var (text, style, width) = tokens[t]; - SwitchFont(canvas, ctx, style, ref currentFont); + TextEmitter.SelectFont(ctx, canvas, style, ref currentFont); SwitchColor(canvas, style, ref currentColor); canvas.SetTextMatrix(1, 0, 0, 1, curX, linePdfY); - ShowText(canvas, style, text); + TextEmitter.Show(canvas, style, text); curX += width; // Add extra spacing after this token if there's a gap before the next @@ -484,24 +484,6 @@ private static void DrawJustifiedEmbeddedLine( // ── Font / colour switching helpers ────────────────────────────────────── - private static void SwitchFont(PdfCanvas canvas, DrawContext ctx, TextStyle style, ref FontReference? current) - { - if (current.HasValue && FontRefEqual(current.Value, style.FontRef)) - return; - - if (style.FontRef.IsEmbedded) - { - var resourceName = ctx.UseEmbeddedFont(style.FontRef.Embedded); - canvas.SetFontByName(resourceName, style.FontSize); - } - else - { - var fontResource = ctx.GetFont(style.Font); - canvas.SetFont(fontResource, style.FontSize); - } - current = style.FontRef; - } - private static void SwitchColor(PdfCanvas canvas, TextStyle style, ref ColorRgb? current) { if (current.HasValue && current.Value == style.Color) @@ -510,31 +492,6 @@ private static void SwitchColor(PdfCanvas canvas, TextStyle style, ref ColorRgb? current = style.Color; } - private static bool FontRefEqual(FontReference a, FontReference b) - { - if (a.IsEmbedded != b.IsEmbedded) return false; - return a.IsEmbedded - ? ReferenceEquals(a.Embedded, b.Embedded) - : a.Standard14 == b.Standard14; - } - - // ── Text emission ───────────────────────────────────────────────────────── - - private static void ShowText(PdfCanvas canvas, TextStyle style, string text) - { - if (style.FontRef.IsEmbedded) - ShowEmbeddedText(canvas, style.FontRef.Embedded, text); - else - canvas.ShowText(text); - } - - private static void ShowEmbeddedText(PdfCanvas canvas, EmbeddedFontHandle handle, string text) - { - var gids = new ushort[text.Length]; - var count = handle.GetGlyphIds(text, gids); - canvas.ShowGlyphs(gids.AsSpan(0, count)); - } - // ── Word-gap / word-token helpers (shared by measure and draw) ─────────── /// diff --git a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs index 1a9daf94c..5dc82e5a0 100644 --- a/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs +++ b/src/VellumPdf.Layout/Rendering/Table/TableRenderer.cs @@ -461,17 +461,9 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, var canvas = ctx.Canvas.BeginText(); - if (cs.FontRef.IsEmbedded) - { - var handle = cs.FontRef.Embedded; - var resourceName = ctx.UseEmbeddedFont(handle); - canvas.SetFontByName(resourceName, cs.FontSize); - } - else - { - var cf = ctx.GetFont(cs.Font); - canvas.SetFont(cf, cs.FontSize); - } + // A fresh reference, so the font operator is written for every cell. + FontReference? cellFont = null; + TextEmitter.SelectFont(ctx, canvas, cs, ref cellFont); // Where the text colour is written, so a cell that is never drawn is not refused for it. // The font size is checked in Layout. @@ -506,10 +498,7 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, var pdfTextY = ctx.ToPdfY(innerBox.Y + cs.FontSize + lineIdx * lineHeight); canvas.SetTextMatrix(1, 0, 0, 1, innerBox.X + txOffset, pdfTextY); - if (cs.FontRef.IsEmbedded) - ShowEmbeddedText(canvas, cs.FontRef.Embedded, line); - else - canvas.ShowText(line); + TextEmitter.Show(canvas, cs, line); } canvas.EndText(); @@ -536,15 +525,6 @@ private void DrawCell(DrawContext ctx, Cell cell, Row row, int colIdx, } } - /// Maps every code point to a glyph id and emits a single hex glyph run. - private static void ShowEmbeddedText(PdfCanvas canvas, EmbeddedFontHandle handle, string text) - { - // Allocate conservatively: one glyph per char (surrogate pairs → 1 glyph each). - var gids = new ushort[text.Length]; - var count = handle.GetGlyphIds(text, gids); - canvas.ShowGlyphs(gids.AsSpan(0, count)); - } - /// /// Returns the indices of the leading contiguous run of header rows. The two loops in /// partition the rows whenever this list is a prefix of them, and the diff --git a/src/VellumPdf.Layout/Rendering/TextEmitter.cs b/src/VellumPdf.Layout/Rendering/TextEmitter.cs new file mode 100644 index 000000000..b8e4da78a --- /dev/null +++ b/src/VellumPdf.Layout/Rendering/TextEmitter.cs @@ -0,0 +1,76 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using VellumPdf.Canvas; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; + +namespace VellumPdf.Layout.Rendering; + +/// +/// Selects a font and shows text for the three places that draw text: paragraphs (and the headings +/// and list text built on them), table cells and running bands. Each keeps its own text object, +/// colour and text matrix, and the order of them; only the font selection and the text operator are +/// shared, so a report made here covers every built-in element. +/// +internal static class TextEmitter +{ + /// + /// Writes the Tf operator for , unless + /// already holds the same font reference. The comparison is on the + /// font only, not the size, so a later run in the same font at another size is drawn at the + /// size of the first. A caller that passes a fresh null writes a Tf every time. + /// + /// + /// Under a conformance claim, a named Standard 14 font that is selected is reported as + /// , once per Tf written. The report + /// follows the write, so a size the canvas refuses reports nothing, and a value the enumeration + /// does not name is never reported: reading its name is what makes the save throw, and the + /// report would turn that exception into the strict refusal. + /// + internal static void SelectFont(DrawContext ctx, PdfCanvas canvas, TextStyle style, ref FontReference? current) + { + if (current.HasValue && FontRefEqual(current.Value, style.FontRef)) + return; + + if (style.FontRef.IsEmbedded) + { + var resourceName = ctx.UseEmbeddedFont(style.FontRef.Embedded); + canvas.SetFontByName(resourceName, style.FontSize); + } + else + { + var fontResource = ctx.GetFont(style.Font); + canvas.SetFont(fontResource, style.FontSize); + if (ctx.Diagnostics is { } sink && sink.Conformance != PdfConformance.None && Enum.IsDefined(style.Font)) + sink.Report( + LayoutDiagnosticCode.UnembeddedFont, + (long)style.Font, + $"{fontResource.BaseFontName} is a Standard 14 font and is not embedded. Give this element a style with an embedded font; SetDefaultFont applies only to Document.Add(string).", + perElement: true, + clause: LayoutDiagnosticSink.ClauseFor(LayoutDiagnosticCode.UnembeddedFont, sink.Conformance)); + } + current = style.FontRef; + } + + /// + /// Shows in the style's font: an embedded font as a glyph run that the + /// canvas lists glyph 0 for, a Standard 14 font as a WinAnsi string. + /// + internal static void Show(PdfCanvas canvas, TextStyle style, string text) + { + if (style.FontRef.IsEmbedded) + canvas.ShowEmbeddedText(style.FontRef.Embedded, text); + else + canvas.ShowText(text); + } + + private static bool FontRefEqual(FontReference a, FontReference b) + { + if (a.IsEmbedded != b.IsEmbedded) return false; + return a.IsEmbedded + ? ReferenceEquals(a.Embedded, b.Embedded) + : a.Standard14 == b.Standard14; + } +} diff --git a/tests/VellumPdf.Layout.Tests/FontReportByteIdentityTests.cs b/tests/VellumPdf.Layout.Tests/FontReportByteIdentityTests.cs new file mode 100644 index 000000000..2edec9f2d --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/FontReportByteIdentityTests.cs @@ -0,0 +1,166 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Elements.Table; +using static VellumPdf.Layout.Tests.FontReportSupport; +using static VellumPdf.Layout.Tests.PlacementLoopSupport; + +namespace VellumPdf.Layout.Tests; + +/// +/// The reports for glyph 0 and for an unembedded font add diagnostics and one ToUnicode entry; they +/// do not change what the save writes otherwise (#592, #593). These pin the bytes of documents that +/// reach the changed drawing sites, hashed after the same normalisation the placement-loop pins +/// use. The hashes were taken before the change. +/// +public sealed class FontReportByteIdentityTests +{ + private static void Pin(string expected, byte[] pdf) => + Assert.True(expected == NormalisedSha256(pdf), $"computed {NormalisedSha256(pdf)}"); + + private static Document Embedded(PdfConformance c, out TextStyle style, double size = 11) + { + var doc = NewDocument(c); + style = new TextStyle { FontRef = doc.UseTrueTypeFont(DejaVuBytes), FontSize = size }; + return doc; + } + + // A claim, a default style, and a list and a table that do not use it. + private static byte[] G3() + { + using var doc = Embedded(PdfConformance.PdfA2u, out var style); + doc.SetDefaultFont(style); + doc.Add("Hello"); + var list = new ListElement(); + list.Add("item"); + doc.Add(list); + var table = new TableElement(); + table.AddRow().AddCell("cell"); + doc.Add(table); + return Save(doc); + } + + // The same, with an unstyled paragraph, heading and footer too. + private static byte[] B593() + { + using var doc = Embedded(PdfConformance.PdfA2u, out var style); + doc.SetDefaultFont(style); + doc.Add("Hello"); + doc.Add(new Paragraph("para")); + doc.Add(new Heading("head")); + var list = new ListElement(); + list.Add("item"); + doc.Add(list); + var table = new TableElement(); + table.AddRow().AddCell("cell"); + doc.Add(table); + doc.SetFooter("foot"); + return Save(doc); + } + + // An empty cell in the default font. + private static byte[] B3() + { + using var doc = Embedded(PdfConformance.PdfA2u, out var style, 12); + doc.Add(new Paragraph("x", style)); + var table = new TableElement(); + table.AddRow().AddCell(""); + doc.Add(table); + return Save(doc); + } + + // Two runs of one font at two sizes: the second is drawn at the size of the first. + private static byte[] Sizes() + { + using var doc = NewDocument(PdfConformance.None); + var font = doc.UseTrueTypeFont(DejaVuBytes); + var p = new Paragraph("ten ", new TextStyle { FontRef = font, FontSize = 10 }); + p.Add("twenty", new TextStyle { FontRef = font, FontSize = 20 }); + doc.Add(p); + return Save(doc); + } + + // No claim; Standard 14 and embedded text in every kind of element and in both bands. + private static byte[] Mixed() + { + using var doc = NewDocument(PdfConformance.None); + var font = doc.UseTrueTypeFont(DejaVuBytes); + var embedded = new TextStyle { FontRef = font, FontSize = 11 }; + var times = new TextStyle { Font = Standard14.TimesRoman, FontSize = 10 }; + var p = new Paragraph("Standard ", times); + p.Add("embedded ", embedded); + p.Add("standard again", times); + doc.Add(p); + doc.Add(new Heading("Heading", embedded)); + doc.Add(new Heading("Plain heading")); + var list = new ListElement { DefaultStyle = embedded }; + list.Add("embedded item"); + doc.Add(list); + var plainList = new ListElement(); + plainList.Add("plain item"); + doc.Add(plainList); + var table = new TableElement { DefaultCellStyle = embedded }; + var row = table.AddRow(); + row.AddCell("embedded cell"); + row.AddCell(new Cell("styled cell") { Style = times }); + doc.Add(table); + doc.SetHeader("header", embedded); + doc.SetFooter("footer {page}", times); + return Save(doc); + } + + [Fact] + public void G3_pinsBytes() => Pin("017D92FAF138AA27AA9017AA0E14A3FD74A6A492E81D17BF8B1F2EE4A6BB583E", G3()); + + [Fact] + public void B593_pinsBytes() => Pin("2734A24F2D1468EE6595743EF9DCC2AF8710E7E27A58254103572BC682D534E8", B593()); + + [Fact] + public void B3_pinsBytes() => Pin("DC5A7C047A27937AE8831209F13C63C3D199C30670AE38288BB05E7CFD7C661D", B3()); + + [Fact] + public void Sizes_pinsBytes_andWritesOneFontOperator() + { + var pdf = Sizes(); + + Assert.Equal(["/TT1 10 Tf"], TfLines(pdf)); + Pin("1176E8A54DA85123D336594E0DFB5BD7BB4461DE3AF0F83FE24E64B9BF522E53", pdf); + } + + [Fact] + public void MixedNoClaimDocument_pinsBytes() => Pin("48AEBB1188593377629E948FCA1E73363BC6AE47B6A27493DC3E005B8A5C974F", Mixed()); + + // The ToUnicode stream is the one place the change moves a byte for a document that draws a + // missing character, so a projection without it is what must equal the file from before. + private static readonly Regex ToUnicodeStream = new( + @"(?\d+ 0 obj\n<<(?:(?!>>).)*?/Length )\d+(?(?:(?!>>).)*>>\nstream\n)/CIDInit.*?(?\nendstream)", + RegexOptions.Singleline | RegexOptions.CultureInvariant); + + private static string ProjectionWithoutToUnicode(byte[] pdf) + { + var text = ToUnicodeStream.Replace( + Normalise(pdf), m => m.Groups["head"].Value + "0" + m.Groups["mid"].Value + m.Groups["tail"].Value); + Assert.DoesNotContain("begincmap", text, StringComparison.Ordinal); + return Convert.ToHexString(SHA256.HashData(Encoding.Latin1.GetBytes(text))); + } + + [Fact] + public void AMissingCharacterDocument_differsOnlyInItsToUnicodeStream() + { + using var doc = NewDocument(PdfConformance.PdfA2u); + var font = doc.UseTrueTypeFont(DejaVuBytes); + doc.Add(new Paragraph("A ⚹ B \U0001F31F C", new TextStyle { FontRef = font })); + + var pdf = Save(doc); + + Assert.Contains("<0000> ", BfcharLines(pdf)); + Assert.True("E0FA95F4D77D310F8359CBF807FA884EA934D40132B2F00B1090D6078031E92C" == ProjectionWithoutToUnicode(pdf), $"computed {ProjectionWithoutToUnicode(pdf)}"); + } +} diff --git a/tests/VellumPdf.Layout.Tests/FontReportSupport.cs b/tests/VellumPdf.Layout.Tests/FontReportSupport.cs new file mode 100644 index 000000000..17f9fadd0 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/FontReportSupport.cs @@ -0,0 +1,113 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using System.Text.RegularExpressions; +using VellumPdf.Document; +using VellumPdf.Layout.Core; +using VellumPdf.TestSupport; + +namespace VellumPdf.Layout.Tests; + +/// +/// Shared by the tests of the glyph-0 and unembedded-font reports (#592, #593): documents with +/// pinned identity, the in-tree fonts, and readers for the two things those tests assert against, +/// the content stream's text operators and the ToUnicode map's entries. +/// +internal static class FontReportSupport +{ + internal static readonly string FontsDir = Path.Combine(AppContext.BaseDirectory, "Fonts"); + + internal static byte[] DejaVuBytes => File.ReadAllBytes(Path.Combine(FontsDir, "DejaVuSans.ttf")); + internal static byte[] LiberationMonoBytes => File.ReadAllBytes(Path.Combine(FontsDir, "LiberationMono-Regular.ttf")); + + internal static Document NewDocument(PdfConformance conformance) + { + var doc = new Document + { + Conformance = conformance, + Timestamp = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero), + DocumentId = new byte[16], + }; + if (conformance is PdfConformance.PdfA2u or PdfConformance.PdfA2b or PdfConformance.PdfA2a) + doc.SetPdfAOutputIntent(IccProfiles.Srgb, 3, "sRGB"); + if (conformance is PdfConformance.PdfUA1) + { + doc.Info.Title = "Font report"; + doc.Language = "en-US"; + } + return doc; + } + + internal static byte[] Save(Document doc) + { + using var ms = new MemoryStream(); + doc.Save(ms); + return ms.ToArray(); + } + + /// The text-showing lines of the page content, one per operator. + internal static List ShowLines(byte[] pdf) => + [.. Lines(pdf).Where(l => l.EndsWith(" Tj", StringComparison.Ordinal))]; + + /// The font-selection lines of the page content, one per operator. + internal static List TfLines(byte[] pdf) => + [.. Lines(pdf).Where(l => l.EndsWith(" Tf", StringComparison.Ordinal))]; + + /// The beginbfchar headers and the entries of every ToUnicode map, in file + /// order. + internal static List BfcharLines(byte[] pdf) => + [.. Lines(pdf).Where(l => Regex.IsMatch(l, @"^(\d+ beginbfchar|<[0-9A-F]{4}> <[0-9A-F]{4,8}>)$") && l != "<0000> ")]; + + private static IEnumerable Lines(byte[] pdf) => + PdfTestUtil.DecompressAllFlatStreams(pdf).Split('\n').Select(l => l.TrimEnd('\r')); + + /// The failed rules of a veraPDF report as clause-testNumber, in report + /// order. + internal static List FailedRules(string report) => + [.. Regex.Matches(report, " $"{m.Groups[1].Value}-{m.Groups[2].Value}")]; + + /// Runs veraPDF on and returns its report. + internal static string VeraPdf(string flavour, byte[] pdf) + { + using var dir = new TempDir(); + var path = dir.Path("subject.pdf"); + File.WriteAllBytes(path, pdf); + ExternalTool.TryRun("verapdf", ["--flavour", flavour, path], + out var exit, out var report, out var stderr, out var timedOut, timeoutMs: 120_000); + Assert.False(timedOut, $"veraPDF timed out.\nstderr:\n{stderr}"); + Assert.True(exit is 0 or 1, $"veraPDF exited {exit}: {VeraPdfExitCode.Describe(exit)}\n{report}\n{stderr}"); + return report; + } + + internal sealed class TempDir : IDisposable + { + // Not CreateTempSubdirectory (mode 0700): the Docker veraPDF on CI runs as another user. + private readonly string _root = Directory.CreateDirectory( + System.IO.Path.Combine(System.IO.Path.GetTempPath(), "vellum-fontreport-" + Guid.NewGuid().ToString("N"))).FullName; + + public string Path(string name) => System.IO.Path.Combine(_root, name); + + public void Dispose() + { + try { Directory.Delete(_root, recursive: true); } + catch (IOException) { /* best-effort cleanup */ } + catch (UnauthorizedAccessException) { /* best-effort cleanup */ } + } + } + + /// Draws glyph ids it is given with ShowGlyphs, as a renderer that does not go + /// through a style does. + internal sealed class GlyphIdRenderer(Fonts.EmbeddedFontHandle font, ushort[] ids) : IRenderer + { + public LayoutResult Layout(LayoutContext context) => LayoutResult.Full(context.Area.WithHeight(20)); + + public void Draw(DrawContext ctx) + { + var name = ctx.UseEmbeddedFont(font); + ctx.Canvas.BeginText().SetFontByName(name, 12).SetTextMatrix(1, 0, 0, 1, 72, 600); + ctx.Canvas.ShowGlyphs(ids); + ctx.Canvas.EndText(); + } + } +} diff --git a/tests/VellumPdf.Layout.Tests/NotdefGlyphReportTests.cs b/tests/VellumPdf.Layout.Tests/NotdefGlyphReportTests.cs new file mode 100644 index 000000000..4f47e5148 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/NotdefGlyphReportTests.cs @@ -0,0 +1,401 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using VellumPdf.Canvas; +using VellumPdf.Document; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Elements.Table; +using VellumPdf.Layout.Rendering; +using static VellumPdf.Layout.Tests.FontReportSupport; + +namespace VellumPdf.Layout.Tests; + +/// +/// A character the embedded font has no glyph for is written as glyph 0, and the save reports it as +/// (#592). DejaVu Sans lacks U+26B9 and U+1F31F; +/// Liberation Mono lacks U+2609 and U+FFFD but has the glyph for U+00A0, which stands in for +/// U+202F. +/// +public sealed class NotdefGlyphReportTests +{ + private const string Clause2u = "ISO 19005-2:2011, 6.2.11.8"; + private const string ClauseUa = "ISO 14289-1:2014, 7.21.8"; + private const string Text = "A \u26B9 B \U0001F31F C"; + + private static Document Build(PdfConformance conformance, string text = Text, bool strict = false) + { + var doc = NewDocument(conformance); + doc.StrictDiagnostics = strict; + var font = doc.UseTrueTypeFont(DejaVuBytes); + doc.Add(new Paragraph(text, new TextStyle { FontRef = font })); + return doc; + } + + private static void AssertItem( + LayoutDiagnostic item, string message, string? clause, LayoutElementKind kind, int? index, int count) + { + Assert.Equal(LayoutDiagnosticCode.NotdefGlyph, item.Code); + Assert.Equal(LayoutDiagnosticSeverity.Error, item.Severity); + Assert.Equal(message, item.Message); + Assert.Equal(clause, item.Clause); + Assert.Equal(kind, item.ElementKind); + Assert.Equal(index, item.ElementIndex); + Assert.Equal(1, item.PageNumber); + Assert.Equal(count, item.Count); + } + + private const string MessageStar = "U+26B9 has no glyph in DejaVuSans (TT1) and is drawn as glyph 0 (.notdef)."; + private const string MessageSun = "U+1F31F has no glyph in DejaVuSans (TT1) and is drawn as glyph 0 (.notdef)."; + + // \u2500\u2500 The report, the content stream and the ToUnicode map \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 + + [Fact] + public void MissingCharacters_areReportedOnceEach_andTheContentIsUnchanged() + { + using var doc = Build(PdfConformance.PdfA2u); + + var pdf = Save(doc); + + // The glyph ids are written as they were: glyph 0 for each missing character. + Assert.Equal(["<002400030000000300250003000000030026> Tj"], ShowLines(pdf)); + // Glyph 0 has the one entry U+FFFD, and no entry names a missing character. + Assert.Equal( + ["5 beginbfchar", "<0000> ", "<0003> <0020>", "<0024> <0041>", "<0025> <0042>", "<0026> <0043>"], + BfcharLines(pdf)); + Assert.Equal(2, doc.Diagnostics.Count); + AssertItem(doc.Diagnostics[0], MessageStar, Clause2u, LayoutElementKind.Paragraph, 0, 1); + AssertItem(doc.Diagnostics[1], MessageSun, Clause2u, LayoutElementKind.Paragraph, 0, 1); + } + + [Theory] + [InlineData(PdfConformance.None, null)] + [InlineData(PdfConformance.PdfA2b, Clause2u)] + [InlineData(PdfConformance.PdfA2a, Clause2u)] + [InlineData(PdfConformance.PdfUA1, ClauseUa)] + public void TheClause_followsTheClaim(PdfConformance conformance, string? clause) + { + using var doc = Build(conformance); + + Save(doc); + + Assert.Equal(2, doc.Diagnostics.Count); + AssertItem(doc.Diagnostics[0], MessageStar, clause, LayoutElementKind.Paragraph, 0, 1); + AssertItem(doc.Diagnostics[1], MessageSun, clause, LayoutElementKind.Paragraph, 0, 1); + } + + [Fact] + public void AValueTheEnumerationDoesNotName_isReportedUnderThePdfAClause() + { + using var doc = Build((PdfConformance)99); + + Save(doc); + + Assert.Equal(2, doc.Diagnostics.Count); + Assert.Equal(Clause2u, doc.Diagnostics[0].Clause); + } + + [Fact] + public void StrictMode_refusesTheSave_naming_theFirstItem_andWritesNothing() + { + using var doc = Build(PdfConformance.PdfA2u, strict: true); + using var ms = new MemoryStream(); + + var ex = Assert.Throws(() => doc.Save(ms)); + + Assert.Equal( + "StrictDiagnostics refused the save: NotdefGlyph (ISO 19005-2:2011, 6.2.11.8) in Paragraph 0, page 1: " + + MessageStar + " 1 further error item(s).", + ex.Message); + Assert.Equal(0, ms.Length); + } + + [Fact] + public void ManyOccurrences_areOneItemEach_withTheirCounts() + { + using var doc = Build(PdfConformance.None, string.Join(' ', Enumerable.Repeat("\u26B9", 100_000))); + Save(doc); + var one = Assert.Single(doc.Diagnostics); + AssertItem(one, MessageStar, null, LayoutElementKind.Paragraph, 0, 100_000); + + using var mono = NewDocument(PdfConformance.None); + var font = mono.UseTrueTypeFont(LiberationMonoBytes); + mono.Add(new Paragraph(string.Join(' ', Enumerable.Repeat("\u26B9\u2609", 50_000)), new TextStyle { FontRef = font })); + Save(mono); + + Assert.Equal(2, mono.Diagnostics.Count); + AssertItem(mono.Diagnostics[0], "U+26B9 has no glyph in LiberationMono (TT1) and is drawn as glyph 0 (.notdef).", + null, LayoutElementKind.Paragraph, 0, 50_000); + AssertItem(mono.Diagnostics[1], "U+2609 has no glyph in LiberationMono (TT1) and is drawn as glyph 0 (.notdef).", + null, LayoutElementKind.Paragraph, 0, 50_000); + } + + [Fact] + public void ACharacterTheFontLacks_isReportedWithTheFontItWasDrawnIn() + { + using var doc = NewDocument(PdfConformance.None); + var font = doc.UseTrueTypeFont(LiberationMonoBytes); + doc.Add(new Paragraph("a\u2609b", new TextStyle { FontRef = font })); + + var pdf = Save(doc); + + var item = Assert.Single(doc.Diagnostics); + Assert.Equal("U+2609 has no glyph in LiberationMono (TT1) and is drawn as glyph 0 (.notdef).", item.Message); + Assert.Equal(["<004400000045> Tj"], ShowLines(pdf)); + } + + [Fact] + public void AStandInGlyph_isNotGlyphZero_andIsNotReported() + { + using var doc = NewDocument(PdfConformance.None); + var font = doc.UseTrueTypeFont(LiberationMonoBytes); + doc.Add(new Paragraph("1\u202F000", new TextStyle { FontRef = font })); + + var pdf = Save(doc); + + Assert.Empty(doc.Diagnostics); + Assert.Equal(["<00140062001300130013> Tj"], ShowLines(pdf)); + Assert.DoesNotContain(BfcharLines(pdf), l => l.StartsWith("<0000>", StringComparison.Ordinal)); + } + + // \u2500\u2500 One document per drawing site, so a site that stops reporting changes the item list \u2500\u2500\u2500\u2500 + + private static Document SiteDocument(Action add) + { + var doc = NewDocument(PdfConformance.None); + var style = new TextStyle { FontRef = doc.UseTrueTypeFont(DejaVuBytes) }; + add(doc, style); + return doc; + } + + private static void AssertSite(Document doc, LayoutElementKind kind, int? index) + { + Save(doc); + var item = Assert.Single(doc.Diagnostics); + AssertItem(item, MessageStar, null, kind, index, 1); + } + + [Fact] + public void ATableCell_isReported() + { + using var doc = SiteDocument((d, style) => + { + var table = new TableElement { DefaultCellStyle = style }; + table.AddRow().AddCell("x\u26B9y"); + d.Add(table); + }); + + AssertSite(doc, LayoutElementKind.Table, 0); + } + + [Fact] + public void AHeaderBand_isReported() => + AssertSiteDispose(SiteDocument((d, style) => d.Add("body", style).SetHeader("h\u26B9", style)), LayoutElementKind.Header, null); + + [Fact] + public void AFooterBand_isReported() => + AssertSiteDispose(SiteDocument((d, style) => d.Add("body", style).SetFooter("f\u26B9", style)), LayoutElementKind.Footer, null); + + [Fact] + public void AListItem_isReported() + { + using var doc = SiteDocument((d, style) => + { + var list = new ListElement { DefaultStyle = style }; + list.Add("\u26B9"); + d.Add(list); + }); + + AssertSite(doc, LayoutElementKind.List, 0); + } + + private static void AssertSiteDispose(Document doc, LayoutElementKind kind, int? index) + { + using (doc) AssertSite(doc, kind, index); + } + + // \u2500\u2500 A custom renderer, and the sink on its own \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 + + [Fact] + public void AnIdPassedToShowGlyphs_isReportedWithTheCharacterUnknown_andStrictRefusesIt() + { + foreach (var strict in new[] { false, true }) + { + using var doc = NewDocument(PdfConformance.PdfA2u); + doc.StrictDiagnostics = strict; + var font = doc.UseTrueTypeFont(DejaVuBytes); + doc.Add(new Paragraph("A", new TextStyle { FontRef = font })); + doc.Add(new GlyphIdRenderer(font, [0, 36])); + using var ms = new MemoryStream(); + + if (strict) + { + var ex = Assert.Throws(() => doc.Save(ms)); + Assert.Equal( + "StrictDiagnostics refused the save: NotdefGlyph (ISO 19005-2:2011, 6.2.11.8) in Custom 1, page 1: " + + "Glyph 0 (.notdef) was drawn in font TT1 from glyph ids passed to PdfCanvas.ShowGlyphs, so the character is not known.", + ex.Message); + continue; + } + + doc.Save(ms); + var item = Assert.Single(doc.Diagnostics); + AssertItem( + item, + "Glyph 0 (.notdef) was drawn in font TT1 from glyph ids passed to PdfCanvas.ShowGlyphs, so the character is not known.", + Clause2u, LayoutElementKind.Custom, 1, 1); + } + } + + [Fact] + public void TheSink_reportsGlyphZeroWhateverReportSays_asAListMarkerNeeds() + { + using var pdf = new PdfDocument(); + var handle = pdf.UseTrueTypeFont(DejaVuBytes); + var canvas = new PdfCanvas(pdf.AddPage()); + var sink = new LayoutDiagnosticSink { CurrentKind = LayoutElementKind.List, CurrentIndex = 0, CurrentPage = 1 }; + + canvas.BeginText().SetFontByName(handle.ResourceName, 12); + TextEmitter.Show(canvas, new TextStyle { FontRef = handle }, "\u26B9"); + sink.SyncEncodingWarnings(canvas, report: false); + + var item = Assert.Single(sink.Snapshot()); + Assert.Equal(LayoutDiagnosticCode.NotdefGlyph, item.Code); + Assert.Equal(MessageStar, item.Message); + Assert.Equal(1, item.Count); + } + + [Fact] + public void TheSink_countsWhatTheCanvasDropped_andReadsItOnce() + { + var canvas = new PdfCanvas(new PdfPage(new PdfRectangle(0, 0, 100, 100))); + canvas.BeginText(); + for (var i = 1; i <= 1003; i++) canvas.SetFontByName($"X{i}", 12).ShowGlyphs([0]); + var sink = new LayoutDiagnosticSink(); + + sink.SyncEncodingWarnings(canvas, report: true); + var first = sink.Snapshot(); + sink.SyncEncodingWarnings(canvas, report: true); + var second = sink.Snapshot(); + + var last = first[^1]; + Assert.Equal(LayoutDiagnosticCode.DiagnosticsDropped, last.Code); + Assert.Equal(3, last.Count); + Assert.True(sink.HasErrors); + Assert.Equal(1001, first.Count); + Assert.Equal(first.Select(i => i.Count), second.Select(i => i.Count)); + Assert.Equal(1003, sink.ErrorReports); + } + + // \u2500\u2500 The same data through the Kernel list \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 + + [Fact] + public void ThroughADocumentRenderer_theKernelListHoldsTheSameEntries() + { + var pdf = PlacementLoopSupport.NewPdf(); + var font = pdf.UseTrueTypeFont(DejaVuBytes); + var renderer = new DocumentRenderer(pdf, PlacementLoopSupport.Page, PlacementLoopSupport.Margins); + renderer.Add(new ParagraphRenderer(new Paragraph(Text, new TextStyle { FontRef = font }))); + + PlacementLoopSupport.Render(renderer); + + Assert.Equal( + [("\u26B9", "TT1", "DejaVuSans", 1), ("\U0001F31F", "TT1", "DejaVuSans", 1)], + pdf.NotdefGlyphs.Select(e => ((string?)e.Character?.ToString(), e.FontResourceName, e.FontName, e.Count))); + Assert.Equal(0, pdf.NotdefGlyphsDropped); + Assert.Equal(2, renderer.Diagnostics.Count); + Assert.Equal(pdf.NotdefGlyphs.Select(e => e.Count), renderer.Diagnostics.Select(i => i.Count)); + } + + [Fact] + public void AHelveticaParagraph_reportsTheUnencodableCharacters_andNoGlyphZero() + { + using var doc = NewDocument(PdfConformance.None); + doc.Add(new Paragraph("A \u26B9 B \u2609 C")); + + Save(doc); + + Assert.Equal( + [LayoutDiagnosticCode.UnencodableCharacter, LayoutDiagnosticCode.UnencodableCharacter], + doc.Diagnostics.Select(i => i.Code)); + Assert.Equal( + ["U+26B9 is not in WinAnsiEncoding and is written as '?' for each UTF-16 code unit.", + "U+2609 is not in WinAnsiEncoding and is written as '?' for each UTF-16 code unit."], + doc.Diagnostics.Select(i => i.Message)); + } + + // \u2500\u2500 What byte-identity means here: only the ToUnicode map moves \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 + + [Fact] + public void TheMissingCharacterDocument_differsFromOneWithoutThemOnlyInItsToUnicodeMap() + { + using var doc = Build(PdfConformance.PdfA2u); + var pdf = Save(doc); + + Assert.Contains("<0000> ", BfcharLines(pdf)); + Assert.DoesNotContain("<0000> <26B9>", BfcharLines(pdf)); + Assert.DoesNotContain("<0000> ", BfcharLines(pdf)); + } + + // \u2500\u2500 Oracles \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 + + [Fact] + public void VeraPdf_failsOnlyTheNotdefRule_andNotTheToUnicodeRule() + { + var pdf = Save(Build(PdfConformance.PdfA2u)); + Assert.Contains("<0000> ", BfcharLines(pdf)); + Assert.DoesNotContain("<0000> <26B9>", BfcharLines(pdf)); + + var failed = FailedRules(VeraPdf("2u", pdf)); + + Assert.Equal(["6.2.11.8-1"], failed); + } + + [Fact] + public void VeraPdf_ua1_failsTheNotdefRule_andNotTheUnicodeValueRule() + { + var pdf = Save(Build(PdfConformance.PdfUA1)); + Assert.Contains("<0000> ", BfcharLines(pdf)); + + var failed = FailedRules(VeraPdf("ua1", pdf)); + + Assert.Contains("7.21.8-1", failed); + Assert.DoesNotContain("7.21.7-1", failed); + } + + [Fact] + public void Poppler_extractsTheReplacementCharacterForEachMissingOne() + { + var pdf = Save(Build(PdfConformance.PdfA2u)); + Assert.Contains("<0000> ", BfcharLines(pdf)); + using var dir = new TempDir(); + var path = dir.Path("subject.pdf"); + File.WriteAllBytes(path, pdf); + + VellumPdf.TestSupport.ExternalTool.TryRun("pdftotext", ["-enc", "UTF-8", path, "-"], + out var exit, out var text, out var stderr, out var timedOut); + + Assert.False(timedOut); + Assert.True(exit == 0, $"pdftotext exit {exit}\n{stderr}"); + Assert.Equal(2, text.Count(c => c == '\uFFFD')); + Assert.DoesNotContain("\u26B9", text, StringComparison.Ordinal); + Assert.DoesNotContain("\U0001F31F", text, StringComparison.Ordinal); + } + + [Fact] + public void Qpdf_checksTheFile_clean() + { + var pdf = Save(Build(PdfConformance.PdfA2u)); + Assert.Contains("<0000> ", BfcharLines(pdf)); + using var dir = new TempDir(); + var path = dir.Path("subject.pdf"); + File.WriteAllBytes(path, pdf); + + VellumPdf.TestSupport.ExternalTool.TryRun("qpdf", ["--check", path], + out var exit, out var stdout, out var stderr, out var timedOut); + + Assert.False(timedOut); + Assert.True(exit == 0, $"qpdf --check exit {exit}\n{stdout}\n{stderr}"); + Assert.Contains("No syntax or stream encoding errors found", stdout, StringComparison.Ordinal); + } +} diff --git a/tests/VellumPdf.Layout.Tests/UnembeddedFontReportTests.cs b/tests/VellumPdf.Layout.Tests/UnembeddedFontReportTests.cs new file mode 100644 index 000000000..67fdfaff6 --- /dev/null +++ b/tests/VellumPdf.Layout.Tests/UnembeddedFontReportTests.cs @@ -0,0 +1,324 @@ +// Copyright © Timothy van der Ham (@Tim81) +// SPDX-License-Identifier: Apache-2.0 + +using VellumPdf.Document; +using VellumPdf.Fonts; +using VellumPdf.Layout.Core; +using VellumPdf.Layout.Elements; +using VellumPdf.Layout.Elements.Table; +using static VellumPdf.Layout.Tests.FontReportSupport; + +namespace VellumPdf.Layout.Tests; + +/// +/// An element that selects a Standard 14 font while the document carries a conformance claim is +/// reported as , once per element and font, +/// counting the font operators written (#593). Nothing about the file changes; the byte pins are in +/// . +/// +public sealed class UnembeddedFontReportTests +{ + private const string Clause2u = "ISO 19005-2:2011, 6.2.11.4.1"; + private const string ClauseUa = "ISO 14289-1:2014, 7.21.4.1"; + + private static string Message(string font) => + $"{font} is a Standard 14 font and is not embedded. Give this element a style with an embedded font; " + + "SetDefaultFont applies only to Document.Add(string)."; + + private static void AssertItem( + LayoutDiagnostic item, string font, string clause, LayoutElementKind kind, int? index, int count) + { + Assert.Equal(LayoutDiagnosticCode.UnembeddedFont, item.Code); + Assert.Equal(LayoutDiagnosticSeverity.Error, item.Severity); + Assert.Equal(Message(font), item.Message); + Assert.Equal(clause, item.Clause); + Assert.Equal(kind, item.ElementKind); + Assert.Equal(index, item.ElementIndex); + Assert.Equal(1, item.PageNumber); + Assert.Equal(count, item.Count); + } + + // A claim and a default style that only Document.Add(string) reads. + private static Document DefaultFontDocument(PdfConformance conformance, bool strict = false) + { + var doc = NewDocument(conformance); + doc.StrictDiagnostics = strict; + var style = new TextStyle { FontRef = doc.UseTrueTypeFont(DejaVuBytes), FontSize = 11 }; + doc.SetDefaultFont(style); + doc.Add("Hello"); + var list = new ListElement(); + list.Add("item"); + doc.Add(list); + var table = new TableElement(); + table.AddRow().AddCell("cell"); + doc.Add(table); + return doc; + } + + [Fact] + public void AListAndATableThatIgnoreTheDefaultFont_areReported_withTheirFontSelectionCounts() + { + using var doc = DefaultFontDocument(PdfConformance.PdfA2u); + + var pdf = Save(doc); + + // The list draws its marker and its item text, two paragraphs, so two selections. + Assert.Equal(2, doc.Diagnostics.Count); + AssertItem(doc.Diagnostics[0], "Helvetica", Clause2u, LayoutElementKind.List, 1, 2); + AssertItem(doc.Diagnostics[1], "Helvetica", Clause2u, LayoutElementKind.Table, 2, 1); + Assert.Equal(["/TT1 11 Tf", "/F1 12 Tf", "/F1 12 Tf", "/F1 12 Tf"], TfLines(pdf)); + } + + [Fact] + public void StrictMode_refusesTheSave_namingTheListAndTheFurtherItem_andWritesNothing() + { + using var doc = DefaultFontDocument(PdfConformance.PdfA2u, strict: true); + using var ms = new MemoryStream(); + + var ex = Assert.Throws(() => doc.Save(ms)); + + Assert.Equal( + "StrictDiagnostics refused the save: UnembeddedFont (ISO 19005-2:2011, 6.2.11.4.1) in List 1, page 1: " + + Message("Helvetica") + " 1 further error item(s).", + ex.Message); + Assert.Equal(0, ms.Length); + } + + [Fact] + public void EmbeddedStylesOnTheListAndTheTable_reportNothing_andSaveUnderStrictMode() + { + using var doc = NewDocument(PdfConformance.PdfA2u); + doc.StrictDiagnostics = true; + var style = new TextStyle { FontRef = doc.UseTrueTypeFont(DejaVuBytes) }; + doc.Add("Hello", style); + var list = new ListElement { DefaultStyle = style }; + list.Add("item"); + doc.Add(list); + var table = new TableElement { DefaultCellStyle = style }; + table.AddRow().AddCell("cell"); + doc.Add(table); + + var pdf = Save(doc); + + Assert.Empty(doc.Diagnostics); + Assert.DoesNotContain(TfLines(pdf), l => l.StartsWith("/F", StringComparison.Ordinal)); + } + + [Fact] + public void WithNoClaim_nothingIsReported() + { + using var doc = DefaultFontDocument(PdfConformance.None, strict: true); + + Save(doc); + + Assert.Empty(doc.Diagnostics); + } + + [Fact] + public void EveryKindOfElementAndTheFooter_isReportedInOrder() + { + using var doc = NewDocument(PdfConformance.PdfA2u); + doc.SetDefaultFont(new TextStyle { FontRef = doc.UseTrueTypeFont(DejaVuBytes), FontSize = 11 }); + doc.Add("Hello"); + doc.Add(new Paragraph("para")); + doc.Add(new Heading("head")); + var list = new ListElement(); + list.Add("item"); + doc.Add(list); + var table = new TableElement(); + table.AddRow().AddCell("cell"); + doc.Add(table); + doc.SetFooter("foot"); + + Save(doc); + + Assert.Equal(5, doc.Diagnostics.Count); + AssertItem(doc.Diagnostics[0], "Helvetica", Clause2u, LayoutElementKind.Paragraph, 1, 1); + AssertItem(doc.Diagnostics[1], "Helvetica", Clause2u, LayoutElementKind.Heading, 2, 1); + AssertItem(doc.Diagnostics[2], "Helvetica", Clause2u, LayoutElementKind.List, 3, 2); + AssertItem(doc.Diagnostics[3], "Helvetica", Clause2u, LayoutElementKind.Table, 4, 1); + AssertItem(doc.Diagnostics[4], "Helvetica", Clause2u, LayoutElementKind.Footer, null, 1); + } + + [Fact] + public void AnEmptyCell_isReported_becauseTheFontOperatorIsWritten() + { + using var doc = NewDocument(PdfConformance.PdfA2u); + var style = new TextStyle { FontRef = doc.UseTrueTypeFont(DejaVuBytes) }; + doc.Add(new Paragraph("x", style)); + var table = new TableElement(); + table.AddRow().AddCell(""); + doc.Add(table); + + var pdf = Save(doc); + + var item = Assert.Single(doc.Diagnostics); + AssertItem(item, "Helvetica", Clause2u, LayoutElementKind.Table, 1, 1); + Assert.Equal(["/TT1 12 Tf", "/F1 12 Tf"], TfLines(pdf)); + } + + [Fact] + public void AnExplicitStandard14Style_underPdfUa_isReportedUnderThePdfUaClause() + { + using var doc = NewDocument(PdfConformance.PdfUA1); + doc.Add(new Paragraph("text", new TextStyle { Font = Standard14.TimesRoman })); + + Save(doc); + + var item = Assert.Single(doc.Diagnostics); + AssertItem(item, "Times-Roman", ClauseUa, LayoutElementKind.Paragraph, 0, 1); + } + + [Fact] + public void TwoRunsInOneFontAtTwoSizes_countOneFontOperator() + { + using var doc = NewDocument(PdfConformance.PdfA2u); + var paragraph = new Paragraph("ten ", new TextStyle { Font = Standard14.Helvetica, FontSize = 10 }); + paragraph.Add("twelve", new TextStyle { Font = Standard14.Helvetica, FontSize = 12 }); + doc.Add(paragraph); + + var pdf = Save(doc); + + var item = Assert.Single(doc.Diagnostics); + AssertItem(item, "Helvetica", Clause2u, LayoutElementKind.Paragraph, 0, 1); + Assert.Equal(["/F1 10 Tf"], TfLines(pdf)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AStandard14ValueTheEnumerationDoesNotName_isNotReported_andTheSaveThrowsAsBefore(bool strict) + { + using var doc = NewDocument(PdfConformance.PdfA2u); + doc.StrictDiagnostics = strict; + doc.Add(new Paragraph("x", new TextStyle { Font = (Standard14)99 })); + using var ms = new MemoryStream(); + + var ex = Assert.Throws(() => doc.Save(ms)); + + // The write raises it, after the layout and after the strict check. A report would read the + // font's name during the layout and throw from there, or turn it into the strict refusal. + Assert.Contains("RegisterStandard14Fonts", ex.StackTrace, StringComparison.Ordinal); + Assert.DoesNotContain("TextEmitter", ex.StackTrace, StringComparison.Ordinal); + Assert.Empty(doc.Diagnostics); + } + + // ── One document per drawing site ──────────────────────────────────────── + + private static LayoutDiagnostic OnlyItem(Document doc) + { + using (doc) Save(doc); + return Assert.Single(doc.Diagnostics); + } + + private static Document Helvetica(Action add) + { + var doc = NewDocument(PdfConformance.PdfA2u); + var style = new TextStyle { Font = Standard14.Helvetica }; + add(doc, style); + return doc; + } + + [Fact] + public void AParagraph_isReported() => + AssertItem(OnlyItem(Helvetica((d, s) => d.Add(new Paragraph("text", s)))), + "Helvetica", Clause2u, LayoutElementKind.Paragraph, 0, 1); + + [Fact] + public void ATableCell_isReported() => + AssertItem(OnlyItem(Helvetica((d, s) => + { + var table = new TableElement { DefaultCellStyle = s }; + table.AddRow().AddCell("cell"); + d.Add(table); + })), "Helvetica", Clause2u, LayoutElementKind.Table, 0, 1); + + [Fact] + public void AHeaderBand_isReported() => + AssertItem(OnlyItem(Helvetica((d, s) => + { + d.Add(new Paragraph("body", new TextStyle { FontRef = d.UseTrueTypeFont(DejaVuBytes) })); + d.SetHeader("head", s); + })), "Helvetica", Clause2u, LayoutElementKind.Header, null, 1); + + [Fact] + public void AFooterBand_isReported() => + AssertItem(OnlyItem(Helvetica((d, s) => + { + d.Add(new Paragraph("body", new TextStyle { FontRef = d.UseTrueTypeFont(DejaVuBytes) })); + d.SetFooter("foot", s); + })), "Helvetica", Clause2u, LayoutElementKind.Footer, null, 1); + + // ── Oracles ────────────────────────────────────────────────────────────── + + [Fact] + public void VeraPdf_failsOnlyTheEmbeddingRule_forTheDefaultFontDocument_andForTheEmptyCell() + { + var g3 = Save(DefaultFontDocument(PdfConformance.PdfA2u)); + Assert.Contains(PdfFontsNames(g3), n => n.StartsWith("Helvetica", StringComparison.Ordinal)); + + Assert.Equal(["6.2.11.4.1-1"], FailedRules(VeraPdf("2u", g3))); + + using var empty = NewDocument(PdfConformance.PdfA2u); + empty.Add(new Paragraph("x", new TextStyle { FontRef = empty.UseTrueTypeFont(DejaVuBytes) })); + var table = new TableElement(); + table.AddRow().AddCell(""); + empty.Add(table); + Assert.Equal(["6.2.11.4.1-1"], FailedRules(VeraPdf("2u", Save(empty)))); + } + + [Fact] + public void VeraPdf_passesTheDocumentWhoseStylesAreEmbedded() + { + using var doc = NewDocument(PdfConformance.PdfA2u); + var style = new TextStyle { FontRef = doc.UseTrueTypeFont(DejaVuBytes) }; + doc.Add("Hello", style); + var list = new ListElement { DefaultStyle = style }; + list.Add("item"); + doc.Add(list); + var table = new TableElement { DefaultCellStyle = style }; + table.AddRow().AddCell("cell"); + doc.Add(table); + var pdf = Save(doc); + + Assert.DoesNotContain(PdfFontsRows(pdf), r => !r.Embedded); + Assert.Empty(FailedRules(VeraPdf("2u", pdf))); + } + + [Fact] + public void Qpdf_checksTheDefaultFontDocument_clean() + { + var pdf = Save(DefaultFontDocument(PdfConformance.PdfA2u)); + using var dir = new TempDir(); + var path = dir.Path("subject.pdf"); + File.WriteAllBytes(path, pdf); + + VellumPdf.TestSupport.ExternalTool.TryRun("qpdf", ["--check", path], + out var exit, out var stdout, out var stderr, out var timedOut); + + Assert.False(timedOut); + Assert.True(exit == 0, $"qpdf --check exit {exit}\n{stdout}\n{stderr}"); + Assert.Contains("No syntax or stream encoding errors found", stdout, StringComparison.Ordinal); + } + + // pdffonts prints fixed-width columns under a header that names them. The embedded flag is read + // at the header's "emb" column, so the parse does not depend on how many words a type has. + private static List<(string Name, bool Embedded)> PdfFontsRows(byte[] pdf) + { + using var dir = new TempDir(); + var path = dir.Path("subject.pdf"); + File.WriteAllBytes(path, pdf); + VellumPdf.TestSupport.ExternalTool.TryRun("pdffonts", [path], + out var exit, out var stdout, out var stderr, out var timedOut); + Assert.False(timedOut); + Assert.True(exit == 0, $"pdffonts exit {exit}\n{stderr}"); + var lines = stdout.Split('\n').Select(l => l.TrimEnd('\r')).ToList(); + var emb = lines[0].IndexOf("emb", StringComparison.Ordinal); + Assert.True(emb > 0, $"No emb column in the pdffonts header: {lines[0]}"); + return [.. lines.Skip(2).Where(l => l.Length > emb + 3) + .Select(l => (l.Split(' ')[0], l.Substring(emb, 3).Trim() == "yes"))]; + } + + private static List PdfFontsNames(byte[] pdf) => + [.. PdfFontsRows(pdf).Where(r => !r.Embedded).Select(r => r.Name)]; +} diff --git a/tests/VellumPdf.Layout.Tests/VellumPdf.Layout.Tests.csproj b/tests/VellumPdf.Layout.Tests/VellumPdf.Layout.Tests.csproj index 02072fb74..bb0d992cb 100644 --- a/tests/VellumPdf.Layout.Tests/VellumPdf.Layout.Tests.csproj +++ b/tests/VellumPdf.Layout.Tests/VellumPdf.Layout.Tests.csproj @@ -32,6 +32,7 @@ + diff --git a/tests/VellumPdf.TestSupport/ExternalTool.cs b/tests/VellumPdf.TestSupport/ExternalTool.cs index 9829aa3ba..27885971c 100644 --- a/tests/VellumPdf.TestSupport/ExternalTool.cs +++ b/tests/VellumPdf.TestSupport/ExternalTool.cs @@ -726,7 +726,8 @@ private static string FirstLine(string text) private readonly record struct Launcher(string File, string[] Prefix, bool ViaCmd, string? UnresolvedHomeDetail); /// - /// Resolves the launcher for a known oracle tool. qpdf, pdftotext, pdftoppm and pdfsig are + /// Resolves the launcher for a known oracle tool. qpdf, pdftotext, pdftoppm, pdfsig and + /// pdffonts are /// always resolved through an explicit *_HOME environment variable first — never a bare /// name as the primary answer, because PATH order alone already picks the wrong /// pdftotext depending on which shell launched the test host (see the type doc). @@ -750,7 +751,7 @@ private static string FirstLine(string text) { "verapdf" => ResolveBatViaHome("VERAPDF_HOME", "verapdf.bat", fallback: "verapdf"), "qpdf" => ResolveExeViaHome("QPDF_HOME", "qpdf"), - "pdftotext" or "pdftoppm" or "pdfsig" => ResolveExeViaHome("POPPLER_HOME", tool), + "pdftotext" or "pdftoppm" or "pdfsig" or "pdffonts" => ResolveExeViaHome("POPPLER_HOME", tool), // Deliberately just a bare name for anything else, with no identity probe over it in // ProbeIdentity. The barcode decode oracle's "python" is the one caller that reaches this From 0c6338102d15c3b50e1b61ea30da37057f4853c6 Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sat, 21 Nov 2026 13:16:16 +0100 Subject: [PATCH 3/4] fix(kernel,layout): settle review findings on the glyph-0 and unembedded-font reports (#592, #593) State where each list and report stops, name the validator-versus-clause difference for a font selected with no glyph shown, say why the single U+FFFD entry exists and when it is written, and name the cases the reports do not see (one-dimensional barcode text, control characters in Standard 14 text). Build the 601 message only for a new subject, make the tally copy self-consistent, resolve pdffonts through the same identity probe as the other poppler tools, and pin the grouping and counting rules, the measured-only and raw-id ToUnicode cases and the refused SaveAsync and PrepareForSigning cases with tests. Re-pin the byte-identity hashes that the font bounding box change moved. --- CHANGELOG.md | 27 ++++-- src/VellumPdf.Barcodes/Barcode1D.cs | 7 ++ .../Canvas/NotdefGlyphTally.cs | 11 ++- .../Canvas/NotdefGlyphWarning.cs | 15 +-- src/VellumPdf.Kernel/Canvas/PdfCanvas.cs | 9 +- src/VellumPdf.Kernel/Document/PdfDocument.cs | 3 +- .../Fonts/EmbeddedFontHandle.cs | 6 +- .../Fonts/TrueTypeFontEmbedder.cs | 11 ++- src/VellumPdf.Layout/Core/TextStyle.cs | 5 +- src/VellumPdf.Layout/Document.cs | 50 +++++++--- src/VellumPdf.Layout/Elements/Heading.cs | 11 ++- src/VellumPdf.Layout/Elements/ListElement.cs | 16 ++-- src/VellumPdf.Layout/Elements/ListItem.cs | 11 ++- src/VellumPdf.Layout/Elements/Paragraph.cs | 11 ++- src/VellumPdf.Layout/Elements/RunningBand.cs | 11 ++- src/VellumPdf.Layout/Elements/Table/Cell.cs | 11 ++- .../Elements/Table/TableElement.cs | 11 ++- src/VellumPdf.Layout/LayoutDiagnosticCode.cs | 22 +++-- src/VellumPdf.Layout/Rendering/TextEmitter.cs | 4 +- .../GlyphZeroToUnicodeTests.cs | 32 +++++-- .../NoBreakSpaceBundledFontTests.cs | 5 +- .../Oracle/ExternalToolResolutionTests.cs | 1 + .../NotdefGlyphTests.cs | 91 ++++++++++++++++++- .../FontReportByteIdentityTests.cs | 27 +++--- .../NotdefGlyphReportTests.cs | 40 ++++++-- .../UnembeddedFontReportTests.cs | 48 +++++++++- tests/VellumPdf.TestSupport/ExternalTool.cs | 26 +++--- 27 files changed, 393 insertions(+), 129 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a20cb2c5..a380394da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -96,11 +96,18 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). claim and ISO 14289-1:2014, 7.21.8 under PDF/UA-1; it is null with no claim. The save still succeeds. `StrictDiagnostics` refuses it. - **`LayoutDiagnosticCode.UnembeddedFont` (#593).** While `Document.Conformance` is not `None`, - each element that selects a named Standard 14 font is reported once per element and font, with - the number of font operators it wrote. A list, table, heading, paragraph or running band - without a style of its own reaches this, because `SetDefaultFont` still applies only to - `Document.Add(string)`. The clause is ISO 19005-2:2011, 6.2.11.4.1 or ISO 14289-1:2014, - 7.21.4.1. The save still succeeds, and `StrictDiagnostics` refuses it. + each paragraph, heading, list, table cell or running band that selects a named Standard 14 font + is reported once per element and font, with the number of font operators it wrote. A list, + table, heading, paragraph or running band without a style of its own reaches this, because + `SetDefaultFont` still applies only to `Document.Add(string)`. The clause is ISO + 19005-2:2011, 6.2.11.4.1 or ISO 14289-1:2014, 7.21.4.1. The save still succeeds, and + `StrictDiagnostics` refuses it. + + **Attention:** the report follows the font operator, so an empty table cell in Helvetica is + reported. That matches veraPDF, which fails 6.2.11.4.1 on it, while ISO 14289-1, 7.21.4.1, + counts a font as used only when a glyph is referenced. The human-readable text of a + one-dimensional barcode, set in `Barcode1D.TextFont` (Helvetica by default), selects its font + without the diagnostics channel and is not reported. - **Internal name tree and number tree writers (#241).** `NameTreeWriter` and `NumberTreeWriter` in `VellumPdf.Kernel` build the structures ISO 32000-2, 7.9.6 and 7.9.7 define, which the catalog's `/Names` and `/PageLabels` entries, and later named destinations and embedded files, @@ -404,9 +411,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). OpenType CFF program is a `/FontFile3` stream and carries no `/Length1`, as before. - **The ToUnicode map no longer lists a code point against glyph 0 (#592).** A font whose subset used glyph 0 wrote one `<0000> <...>` line per missing character. On a test file with - U+26B9 and U+1F31F, pdftotext (poppler 26.08) extracted U+1F31F for both. The map now has one entry for glyph 0, - `<0000> `, and no other. A document that draws no glyph 0 is unchanged byte for byte. A - document that does changes only in that stream; the content stream still shows glyph 0. + U+26B9 and U+1F31F, pdftotext (poppler 26.08) extracted U+1F31F for both. The map now has one + entry for glyph 0, `<0000> `, and no other. The entry exists because glyph 0 is itself + what ISO 19005-2, 6.2.11.8, and ISO 14289-1, 7.21.8, refuse, and U+FFFD satisfies the value + rule of 7.21.7. A document in which no character was mapped to glyph 0, drawn or only + measured, is unchanged. One in which a character was mapped to it changes only in that + stream, and the content stream still shows glyph 0. Glyph ids passed straight to + `PdfCanvas.ShowGlyphs` add no entry. **Attention:** the file still references `.notdef`, so veraPDF still fails ISO 19005-2, 6.2.11.8 and ISO 14289-1, 7.21.8. The reports above are how to find it. diff --git a/src/VellumPdf.Barcodes/Barcode1D.cs b/src/VellumPdf.Barcodes/Barcode1D.cs index f29171463..adfc6e9a3 100644 --- a/src/VellumPdf.Barcodes/Barcode1D.cs +++ b/src/VellumPdf.Barcodes/Barcode1D.cs @@ -20,6 +20,13 @@ private protected Barcode1D() public bool ShowText { get; init; } = true; /// The Standard-14 font used for the HRI text. Defaults to . + /// + /// The font is not embedded. A document with a PDF/A or PDF/UA conformance claim that draws + /// this text is not told so by VellumPdf.Layout: the barcode selects the font without + /// its diagnostics channel, so no UnembeddedFont item is reported for it. Do not + /// rely on an empty Document.Diagnostics to show that every font in such a document + /// is embedded; set to false or draw the text yourself. + /// public Standard14 TextFont { get; init; } = Standard14.Helvetica; /// The HRI text size, in points. Zero (the default) sizes it automatically from . diff --git a/src/VellumPdf.Kernel/Canvas/NotdefGlyphTally.cs b/src/VellumPdf.Kernel/Canvas/NotdefGlyphTally.cs index fc930e5a4..b3c679b79 100644 --- a/src/VellumPdf.Kernel/Canvas/NotdefGlyphTally.cs +++ b/src/VellumPdf.Kernel/Canvas/NotdefGlyphTally.cs @@ -23,14 +23,19 @@ internal sealed class NotdefGlyphTally internal const int UnknownCodePoint = 0x110000; private readonly List _entries = []; - private readonly Dictionary<(int CodePoint, string? Resource), int>? _index; + private readonly Dictionary<(int CodePoint, string? Resource), int> _index = []; - internal NotdefGlyphTally() => _index = []; + internal NotdefGlyphTally() + { + } private NotdefGlyphTally(NotdefGlyphTally source) { foreach (var e in source._entries) + { + _index[(CodePointOf(e.Character), e.FontResourceName)] = _entries.Count; _entries.Add(new NotdefGlyphWarning(e.Character, e.FontResourceName, e.FontName, e.Count)); + } Dropped = source.Dropped; Total = source.Total; } @@ -49,7 +54,7 @@ internal void Add(Rune? character, string? resource, string? fontName, int count { Total = Saturate(Total, count); var key = (CodePointOf(character), resource); - if (_index!.TryGetValue(key, out var at)) + if (_index.TryGetValue(key, out var at)) { var entry = _entries[at]; entry.Count = Saturate(entry.Count, count); diff --git a/src/VellumPdf.Kernel/Canvas/NotdefGlyphWarning.cs b/src/VellumPdf.Kernel/Canvas/NotdefGlyphWarning.cs index 35642687e..125140298 100644 --- a/src/VellumPdf.Kernel/Canvas/NotdefGlyphWarning.cs +++ b/src/VellumPdf.Kernel/Canvas/NotdefGlyphWarning.cs @@ -16,13 +16,14 @@ namespace VellumPdf.Canvas; /// getters, so it takes no input that could be wrong. ISO 19005-2, 6.2.11.8, and ISO 14289-1, /// 7.21.8, forbid a reference to the .notdef glyph in a PDF/A-2 or PDF/UA-1 file; this /// type reports that a canvas wrote one and leaves the decision to the caller. -/// An entry exists for every glyph id 0 the canvas wrote through -/// and through the library's own -/// text drawing. It does not exist for content bytes set directly on a -/// , for a canvas whose has -/// not run, or for entries past the 1,000 the list holds; -/// counts those. Do not read an empty list as -/// proof that the file holds no glyph 0. +/// lists an entry at once for every glyph id 0 the +/// canvas writes through and +/// through the library's own text drawing, past the 1,000 entries it holds; +/// counts the occurrences of those. It has none for +/// content bytes set directly on a . +/// lists only what each page's last +/// stored, so a canvas whose Finish has not run adds +/// nothing there. Do not read an empty list as proof that the file holds no glyph 0. /// Reading an entry while another thread draws on the canvas that holds it is not /// supported. /// diff --git a/src/VellumPdf.Kernel/Canvas/PdfCanvas.cs b/src/VellumPdf.Kernel/Canvas/PdfCanvas.cs index e14e447bd..98c99e799 100644 --- a/src/VellumPdf.Kernel/Canvas/PdfCanvas.cs +++ b/src/VellumPdf.Kernel/Canvas/PdfCanvas.cs @@ -86,7 +86,8 @@ public sealed class PdfCanvas /// /// /// Nothing here is refused and nothing throws. The list takes no input, and the canvas - /// writes glyph 0 as it always has. ISO 19005-2, 6.2.11.8, and ISO 14289-1, 7.21.8, forbid a + /// writes glyph 0 whatever the list says. ISO 19005-2, 6.2.11.8, and ISO 14289-1, 7.21.8, + /// forbid a /// reference to .notdef in a PDF/A-2 or PDF/UA-1 file, so this list is how a caller of /// the Kernel finds out. It is separate from , which lists /// characters that wrote as '?'; glyph 0 is not listed there. @@ -110,7 +111,8 @@ public sealed class PdfCanvas /// /// Nothing here is refused and nothing throws. A write for an entry already in the list /// is counted in that entry, not here. Do not read zero as proof that the list is - /// complete for content written some other way; see . + /// complete for content written some other way; see . Reading it + /// while another thread draws on this canvas is not supported. /// public int NotdefGlyphsDropped => _notdef?.Dropped ?? 0; @@ -859,7 +861,8 @@ public PdfCanvas DoXObject(string resourceName) /// /// Records the fonts used on this page (materialised as shared indirect objects by /// ) and stores the accumulated operator bytes - /// as the page content. Call exactly once when the page is complete. + /// as the page content. Call it when the page is complete; a later call replaces the content + /// and the glyph-0 snapshot with the canvas's state at that call. /// /// /// Also stores a snapshot of and diff --git a/src/VellumPdf.Kernel/Document/PdfDocument.cs b/src/VellumPdf.Kernel/Document/PdfDocument.cs index a52037fd0..3512ed257 100644 --- a/src/VellumPdf.Kernel/Document/PdfDocument.cs +++ b/src/VellumPdf.Kernel/Document/PdfDocument.cs @@ -263,7 +263,8 @@ public PdfPage AddPage(PdfRectangle size) /// /// Nothing here is refused and nothing throws. The value is computed on each read, like /// , and has the same boundary. Do not read zero as proof that - /// the file holds no glyph 0 the list does not see. + /// the file holds no glyph 0 the list does not see. Reading it while another thread calls + /// on one of the document's pages is not supported. /// public int NotdefGlyphsDropped => GatherNotdefGlyphs().Dropped; diff --git a/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs b/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs index 1c58f5e9c..bc05df806 100644 --- a/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs +++ b/src/VellumPdf.Kernel/Fonts/EmbeddedFontHandle.cs @@ -66,8 +66,10 @@ public double MeasureString(string text, double pointSize) => /// Nothing here is refused and nothing throws. A 0 is not an error at this call, /// but writes /// it as CID 0, which ISO 19005-2, 6.2.11.8, and ISO 14289-1, 7.21.8, forbid in a PDF/A-2 or - /// PDF/UA-1 file. The font's ToUnicode CMap maps glyph 0 to U+FFFD. A Kernel caller sees the - /// write in , without the character. Do + /// PDF/UA-1 file. Asking for a character that gives 0 is enough for the font's ToUnicode CMap + /// to list glyph 0 once, as U+FFFD, whether or not it is drawn; the entry is there because + /// glyph 0 is itself refused by those clauses. A Kernel caller sees a write in + /// , without the character. Do /// not pass a code point this method answers 0 for to ShowGlyphs under either /// claim. /// diff --git a/src/VellumPdf.Kernel/Fonts/TrueTypeFontEmbedder.cs b/src/VellumPdf.Kernel/Fonts/TrueTypeFontEmbedder.cs index e90793b58..e600aa019 100644 --- a/src/VellumPdf.Kernel/Fonts/TrueTypeFontEmbedder.cs +++ b/src/VellumPdf.Kernel/Fonts/TrueTypeFontEmbedder.cs @@ -450,9 +450,14 @@ public Core.PdfStream BuildFontFileStream() /// project, so this member does not claim that a carriage return and line feed pair is /// invalid; the single form keeps the output reproducible. The compressed bytes can still /// differ between .NET runtimes. This member refuses no input and throws nothing. - /// Glyph 0 gets one entry, <0000> <FFFD>, when any code point was - /// assigned glyph 0, and no code point is listed against it; every other glyph gets the code - /// point or points that were assigned to it, as before. + /// Glyph 0 gets one entry, <0000> <FFFD>, when any character was + /// mapped to it, whether the character was drawn or only measured, and no character is listed + /// against it; every other glyph gets the character or characters mapped to it. The entry is + /// there because glyph 0 is itself what ISO 14289-1, 7.21.8, and ISO 19005-2, 6.2.11.8, + /// refuse, so there is no character to name, and U+FFFD satisfies the value rule of ISO + /// 14289-1, 7.21.7. Glyph ids passed straight to + /// add no + /// entry. /// public Core.PdfStream BuildToUnicodeCMap() { diff --git a/src/VellumPdf.Layout/Core/TextStyle.cs b/src/VellumPdf.Layout/Core/TextStyle.cs index 28010e35a..c00b729e0 100644 --- a/src/VellumPdf.Layout/Core/TextStyle.cs +++ b/src/VellumPdf.Layout/Core/TextStyle.cs @@ -62,7 +62,8 @@ public TextStyle() { } /// , with the clause that /// forbids it under a PDF/A or PDF/UA claim, and still saves. The font's ToUnicode map gives /// glyph 0 the one entry U+FFFD. Do not pass text the font cannot draw to such a - /// document. A later major version refuses it always. + /// document. A later major version refuses text the font cannot draw, and a Standard 14 font, + /// under either claim. /// A Standard 14 font is not embedded. While /// is not /// , each element whose style selects one @@ -71,7 +72,7 @@ public TextStyle() { } /// font, and the save still succeeds. With /// set, either report refuses the /// save. Do not pass a Standard 14 font under either claim. A later major version - /// refuses it always. + /// refuses text the font cannot draw, and a Standard 14 font, under either claim. /// /// /// Raised from and the other diff --git a/src/VellumPdf.Layout/Document.cs b/src/VellumPdf.Layout/Document.cs index 15a6b27b3..b340580ae 100644 --- a/src/VellumPdf.Layout/Document.cs +++ b/src/VellumPdf.Layout/Document.cs @@ -136,7 +136,8 @@ public Document() { } /// fetches with and never selects /// is not reported, and neither is one that a renderer selects with its own /// call. Callers of - /// the Kernel alone have no channel, and + /// the Kernel alone have no channel except + /// for glyph 0, and /// exposes /// none. /// Input that is refused is thrown, not listed. Do not read an empty list as proof that @@ -267,7 +268,8 @@ public PdfRectangle PageSize /// is set; see . /// does not reach those elements. Do not pass a style with /// a Standard 14 font, or text the font cannot draw, to a PDF/A or PDF/UA document. A later - /// major version refuses it always. + /// major version refuses text the font cannot draw, and a Standard 14 font, under either + /// claim. /// /// /// Raised from and the other save overloads, when @@ -506,7 +508,8 @@ public byte[]? DocumentId /// in and /// still saves; only refuses it. Do not leave the /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded - /// font. A later major version refuses it always. + /// font. A later major version refuses an element that falls back to Helvetica under either + /// claim. /// A null style is stored. A later then uses /// . /// The style is not checked here. Its refusals are raised from the save, for the text @@ -531,9 +534,11 @@ public byte[]? DocumentId /// /// /// Raised from and the other save overloads, not - /// from here, when is set, the document has a - /// conformance claim and the element writes Helvetica or another Standard 14 font; the save - /// reports it as . + /// from here, when is set and text of the element is + /// written as glyph 0, or the document has a conformance claim and the element writes Helvetica + /// or another Standard 14 font; the save reports them as + /// and + /// . /// public Document SetDefaultFont(TextStyle style) { _defaultStyle = style; return this; } @@ -555,7 +560,8 @@ public byte[]? DocumentId /// in and /// still saves; only refuses it. Do not leave the /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded - /// font. A later major version refuses it always. + /// font. A later major version refuses an element that falls back to Helvetica under either + /// claim. /// /// /// is . @@ -563,9 +569,11 @@ public byte[]? DocumentId /// /// /// Raised from and the other save overloads, not - /// from here, when is set, the document has a - /// conformance claim and the element writes Helvetica or another Standard 14 font; the save - /// reports it as . + /// from here, when is set and text of the element is + /// written as glyph 0, or the document has a conformance claim and the element writes Helvetica + /// or another Standard 14 font; the save reports them as + /// and + /// . /// public Document SetHeader(string template, TextStyle? style = null, HorizontalAlignment alignment = HorizontalAlignment.Center) { @@ -591,7 +599,8 @@ public Document SetHeader(string template, TextStyle? style = null, HorizontalAl /// in and /// still saves; only refuses it. Do not leave the /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded - /// font. A later major version refuses it always. + /// font. A later major version refuses an element that falls back to Helvetica under either + /// claim. /// /// /// is . @@ -599,9 +608,11 @@ public Document SetHeader(string template, TextStyle? style = null, HorizontalAl /// /// /// Raised from and the other save overloads, not - /// from here, when is set, the document has a - /// conformance claim and the element writes Helvetica or another Standard 14 font; the save - /// reports it as . + /// from here, when is set and text of the element is + /// written as glyph 0, or the document has a conformance claim and the element writes Helvetica + /// or another Standard 14 font; the save reports them as + /// and + /// . /// public Document SetFooter(string template, TextStyle? style = null, HorizontalAlignment alignment = HorizontalAlignment.Center) { @@ -992,7 +1003,8 @@ public Document Add(PageBreak pageBreak) /// in and /// still saves; only refuses it. Do not leave the /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded - /// font. A later major version refuses it always. + /// font. A later major version refuses text the font cannot draw, and a Standard 14 font, under + /// either claim. /// /// /// is . @@ -1009,6 +1021,14 @@ public Document Add(PageBreak pageBreak) /// enumeration does not name and the font is selected on a page; see /// . /// + /// + /// Raised from and the other save overloads, not + /// from here, when is set and text of the paragraph + /// is written as glyph 0, or the document has a conformance claim and the paragraph writes + /// Helvetica or another Standard 14 font; the save reports them as + /// and + /// . + /// public Document Add(string text, TextStyle? style = null) => Add(new Paragraph(text, style ?? _defaultStyle)); diff --git a/src/VellumPdf.Layout/Elements/Heading.cs b/src/VellumPdf.Layout/Elements/Heading.cs index fb492a3ac..19eea75e1 100644 --- a/src/VellumPdf.Layout/Elements/Heading.cs +++ b/src/VellumPdf.Layout/Elements/Heading.cs @@ -172,7 +172,8 @@ public PageBreakMode BreakBefore /// in and /// still saves; only refuses it. Do not leave the /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded - /// font. A later major version refuses it always. + /// font. A later major version refuses an element that falls back to Helvetica under either + /// claim. /// /// /// is . @@ -180,9 +181,11 @@ public PageBreakMode BreakBefore /// /// /// Raised from and the other save overloads, not - /// from here, when is set, the document has a - /// conformance claim and the element writes Helvetica or another Standard 14 font; the save - /// reports it as . + /// from here, when is set and text of the element is + /// written as glyph 0, or the document has a conformance claim and the element writes Helvetica + /// or another Standard 14 font; the save reports them as + /// and + /// . /// public Heading(string text, TextStyle? style = null) { diff --git a/src/VellumPdf.Layout/Elements/ListElement.cs b/src/VellumPdf.Layout/Elements/ListElement.cs index 189a366ce..51c6eeaea 100644 --- a/src/VellumPdf.Layout/Elements/ListElement.cs +++ b/src/VellumPdf.Layout/Elements/ListElement.cs @@ -164,14 +164,16 @@ public PageBreakMode BreakBefore /// Null means . Refusals on size, leading, font and text colour /// are on and are raised from the save. /// A list with no default style does not take ; its - /// items, and the marker of each, take , so an item is reported - /// twice. The font is then Helvetica, which is not embedded. While + /// items, and the marker of each, take , so each item adds two + /// font selections, one for its marker and one for its text, to the list's single report. The + /// font is then Helvetica, which is not embedded. While /// is not /// the save reports the element as /// in and /// still saves; only refuses it. Do not leave the /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded - /// font. A later major version refuses it always. + /// font. A later major version refuses an element that falls back to Helvetica under either + /// claim. /// /// /// @@ -181,9 +183,11 @@ public PageBreakMode BreakBefore /// /// /// Raised from and the other save overloads, not - /// from here, when is set, the document has a - /// conformance claim and the element writes Helvetica or another Standard 14 font; the save - /// reports it as . + /// from here, when is set and text of the element is + /// written as glyph 0, or the document has a conformance claim and the element writes Helvetica + /// or another Standard 14 font; the save reports them as + /// and + /// . /// public TextStyle? DefaultStyle { get; init; } diff --git a/src/VellumPdf.Layout/Elements/ListItem.cs b/src/VellumPdf.Layout/Elements/ListItem.cs index 2120eb449..52456aca8 100644 --- a/src/VellumPdf.Layout/Elements/ListItem.cs +++ b/src/VellumPdf.Layout/Elements/ListItem.cs @@ -52,7 +52,8 @@ public sealed class ListItem /// in and /// still saves; only refuses it. Do not leave the /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded - /// font. A later major version refuses it always. + /// font. A later major version refuses an element that falls back to Helvetica under either + /// claim. /// On an item built from runs this styles the marker and the children that set no style /// of their own, and none of this item's runs, because each run has its own style. The /// marker of a child item takes its own style, or its parent's. A run is a link only through @@ -81,9 +82,11 @@ public sealed class ListItem /// /// /// Raised from and the other save overloads, not - /// from here, when is set, the document has a - /// conformance claim and the element writes Helvetica or another Standard 14 font; the save - /// reports it as . + /// from here, when is set and text of the element is + /// written as glyph 0, or the document has a conformance claim and the element writes Helvetica + /// or another Standard 14 font; the save reports them as + /// and + /// . /// public TextStyle? Style { get; init; } diff --git a/src/VellumPdf.Layout/Elements/Paragraph.cs b/src/VellumPdf.Layout/Elements/Paragraph.cs index 57113855e..29ccf239f 100644 --- a/src/VellumPdf.Layout/Elements/Paragraph.cs +++ b/src/VellumPdf.Layout/Elements/Paragraph.cs @@ -171,7 +171,8 @@ public PageBreakMode BreakBefore /// in and /// still saves; only refuses it. Do not leave the /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded - /// font. A later major version refuses it always. + /// font. A later major version refuses an element that falls back to Helvetica under either + /// claim. /// /// /// is . @@ -195,9 +196,11 @@ public PageBreakMode BreakBefore /// /// /// Raised from and the other save overloads, not - /// from here, when is set, the document has a - /// conformance claim and the element writes Helvetica or another Standard 14 font; the save - /// reports it as . + /// from here, when is set and text of the element is + /// written as glyph 0, or the document has a conformance claim and the element writes Helvetica + /// or another Standard 14 font; the save reports them as + /// and + /// . /// public Paragraph(string text, TextStyle? style = null) { diff --git a/src/VellumPdf.Layout/Elements/RunningBand.cs b/src/VellumPdf.Layout/Elements/RunningBand.cs index b0e7553e1..2f4faba1a 100644 --- a/src/VellumPdf.Layout/Elements/RunningBand.cs +++ b/src/VellumPdf.Layout/Elements/RunningBand.cs @@ -149,7 +149,8 @@ public sealed class RunningBand /// in and /// still saves; only refuses it. Do not leave the /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded - /// font. A later major version refuses it always. + /// font. A later major version refuses an element that falls back to Helvetica under either + /// claim. /// /// /// Raised from and the other save overloads, not from @@ -178,9 +179,11 @@ public sealed class RunningBand /// /// /// Raised from and the other save overloads, not - /// from here, when is set, the document has a - /// conformance claim and the element writes Helvetica or another Standard 14 font; the save - /// reports it as . + /// from here, when is set and text of the element is + /// written as glyph 0, or the document has a conformance claim and the element writes Helvetica + /// or another Standard 14 font; the save reports them as + /// and + /// . /// public RunningBand(string template, TextStyle? style = null, HorizontalAlignment alignment = HorizontalAlignment.Center) { diff --git a/src/VellumPdf.Layout/Elements/Table/Cell.cs b/src/VellumPdf.Layout/Elements/Table/Cell.cs index 687d2eb03..632f7d243 100644 --- a/src/VellumPdf.Layout/Elements/Table/Cell.cs +++ b/src/VellumPdf.Layout/Elements/Table/Cell.cs @@ -109,15 +109,18 @@ public sealed class Cell /// in and /// still saves; only refuses it. Do not leave the /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded - /// font. A later major version refuses it always. + /// font. A later major version refuses text the font cannot draw, and a Standard 14 font, under + /// either claim. /// /// /// /// /// Raised from and the other save overloads, not - /// from here, when is set, the document has a - /// conformance claim and the element writes Helvetica or another Standard 14 font; the save - /// reports it as . + /// from here, when is set and text of the element is + /// written as glyph 0, or the document has a conformance claim and the element writes Helvetica + /// or another Standard 14 font; the save reports them as + /// and + /// . /// public TextStyle? Style { get; init; } diff --git a/src/VellumPdf.Layout/Elements/Table/TableElement.cs b/src/VellumPdf.Layout/Elements/Table/TableElement.cs index bccfb9084..b492aa254 100644 --- a/src/VellumPdf.Layout/Elements/Table/TableElement.cs +++ b/src/VellumPdf.Layout/Elements/Table/TableElement.cs @@ -43,15 +43,18 @@ public TableElement() { } /// in and /// still saves; only refuses it. Do not leave the /// style out of an element in a PDF/A or PDF/UA document; give it a style with an embedded - /// font. A later major version refuses it always. + /// font. A later major version refuses an element that falls back to Helvetica under either + /// claim. /// /// /// /// /// Raised from and the other save overloads, not - /// from here, when is set, the document has a - /// conformance claim and the element writes Helvetica or another Standard 14 font; the save - /// reports it as . + /// from here, when is set and text of the element is + /// written as glyph 0, or the document has a conformance claim and the element writes Helvetica + /// or another Standard 14 font; the save reports them as + /// and + /// . /// public TextStyle? DefaultCellStyle { get; init; } diff --git a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs index 6590ebe6d..5b1098e7b 100644 --- a/src/VellumPdf.Layout/LayoutDiagnosticCode.cs +++ b/src/VellumPdf.Layout/LayoutDiagnosticCode.cs @@ -53,16 +53,19 @@ public enum LayoutDiagnosticCode /// reference to the .notdef glyph from any text-showing operator, and under PDF/UA-1 it /// is ISO 14289-1:2014, 7.21.8. With no claim the clause is null, because plain PDF /// permits showing glyph 0 and the item is still reported. The save writes the glyph anyway, - /// and the font's ToUnicode map gives glyph 0 one entry, U+FFFD. + /// and the font's ToUnicode map lists glyph 0 once, as U+FFFD, when a character was mapped to + /// it. The entry is there because glyph 0 is itself what those clauses refuse; glyph ids a + /// renderer passes itself add none. /// The built-in elements, running bands and list markers report the character. A custom /// renderer that writes glyph ids with /// on the /// document's canvas is reported with the character unknown, named by the resource name of the /// last font it selected. Glyph 0 written to a canvas that is not the document's, or by a /// renderer's own bytes on the page, is not seen. Text a font draws through a stand-in glyph, - /// such as U+202F in a font without it, is not glyph 0 and is not reported. Characters in a - /// Standard 14 font are never glyph 0; those the font cannot encode are - /// . + /// such as U+202F in a font without it, is not glyph 0 and is not reported. A Standard 14 + /// font has no glyph ids here: a character it cannot encode is + /// , and a control character such as a tab is written as + /// its WinAnsi code, which the font has no glyph for and which is not reported. /// What is drawn is whatever the font's .notdef glyph holds. Do not pass /// text the font cannot draw to a PDF/A or PDF/UA document; give the element a font that covers /// it. @@ -142,17 +145,22 @@ public enum LayoutDiagnosticCode /// Strict mode refuses it. The item's is ISO /// 19005-2:2011, 6.2.11.4.1 under a PDF/A claim and ISO 14289-1:2014, 7.21.4.1 under /// PDF/UA-1; both require the font programs of every font used for rendering to be embedded, - /// and neither exempts the Standard 14. The save writes the file as it always has. + /// and neither exempts the Standard 14. The save writes the file unchanged. /// applies only to /// with a string, so a paragraph, heading, /// list, table or running band without its own embedded style reaches this. /// A selection is reported when the font operator is written, whether or not any text - /// follows it, so an empty table cell in Helvetica is reported. Not reported: a Standard 14 + /// follows it, so an empty table cell in Helvetica is reported. That follows the validator, + /// which flags a selected font even when no glyph is shown; ISO 14289-1, 7.21.4.1, counts a + /// font as used only when a glyph is referenced from a content stream. Not reported: a Standard + /// 14 /// font that a custom renderer selects on the canvas itself, or fetches with /// and never selects, a /// you construct, and a /// value the enumeration does not name, which makes the save throw - /// as before. Do not pass a style with a Standard + /// , and the human-readable text of a one-dimensional + /// barcode, which is set in Barcode1D.TextFont (Helvetica by default) and selected + /// without this channel. Do not pass a style with a Standard /// 14 font to an element of a PDF/A or PDF/UA document, and set the style of lists, tables and /// running bands yourself. /// diff --git a/src/VellumPdf.Layout/Rendering/TextEmitter.cs b/src/VellumPdf.Layout/Rendering/TextEmitter.cs index b8e4da78a..5d82af110 100644 --- a/src/VellumPdf.Layout/Rendering/TextEmitter.cs +++ b/src/VellumPdf.Layout/Rendering/TextEmitter.cs @@ -47,7 +47,9 @@ internal static void SelectFont(DrawContext ctx, PdfCanvas canvas, TextStyle sty sink.Report( LayoutDiagnosticCode.UnembeddedFont, (long)style.Font, - $"{fontResource.BaseFontName} is a Standard 14 font and is not embedded. Give this element a style with an embedded font; SetDefaultFont applies only to Document.Add(string).", + static font => new PdfFontResource((Standard14)font, "F").BaseFontName + + " is a Standard 14 font and is not embedded. Give this element a style with an embedded" + + " font; SetDefaultFont applies only to Document.Add(string).", perElement: true, clause: LayoutDiagnosticSink.ClauseFor(LayoutDiagnosticCode.UnembeddedFont, sink.Conformance)); } diff --git a/tests/VellumPdf.Conformance.Tests/GlyphZeroToUnicodeTests.cs b/tests/VellumPdf.Conformance.Tests/GlyphZeroToUnicodeTests.cs index 414d2daf9..7ad067568 100644 --- a/tests/VellumPdf.Conformance.Tests/GlyphZeroToUnicodeTests.cs +++ b/tests/VellumPdf.Conformance.Tests/GlyphZeroToUnicodeTests.cs @@ -10,18 +10,21 @@ namespace VellumPdf.Conformance.Tests; /// /// The ToUnicode map maps glyph 0 to U+FFFD, which the Unicode value rule accepts (ISO 14289-1, -/// 7.21.7), so a file that draws a missing character fails the .notdef rule and only that one (#592). +/// 7.21.7), so a file that draws a missing character fails the .notdef rule and not the +/// ToUnicode rules (#592). /// public sealed class GlyphZeroToUnicodeTests { - private static byte[] DocumentDrawingAMissingCharacter() + private static byte[] DocumentDrawingAMissingCharacter(VellumPdf.Document.PdfConformance claim) { using var doc = new PdfDocument { - Conformance = VellumPdf.Document.PdfConformance.PdfA2u, + Conformance = claim, Timestamp = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero), DocumentId = new byte[16], }; + doc.Info.Title = "Glyph zero"; + doc.Language = "en-US"; var page = doc.AddPage(); var font = doc.UseTrueTypeFont(CmapFormat12Tests.LoadAsset("DejaVuSans.ttf")); doc.RegisterEmbeddedFontUsage(page, font); @@ -36,17 +39,34 @@ private static byte[] DocumentDrawingAMissingCharacter() return ms.ToArray(); } - [Fact] - public void AMissingCharacter_failsTheNotdefRule_andNotTheToUnicodeRule() + private static void AssertFixtureHoldsTheChange(byte[] pdf) { - var pdf = DocumentDrawingAMissingCharacter(); var text = System.Text.Encoding.Latin1.GetString(CmapFormat12Tests.Inflated(pdf)); Assert.Contains("<0000> ", text, StringComparison.Ordinal); Assert.DoesNotContain("<0000> <26B9>", text, StringComparison.Ordinal); + } + + [Fact] + public void PdfA_aMissingCharacter_failsTheNotdefRule_andNotTheToUnicodeRule() + { + var pdf = DocumentDrawingAMissingCharacter(VellumPdf.Document.PdfConformance.PdfA2u); + AssertFixtureHoldsTheChange(pdf); var ids = PdfPreflight.Validate(pdf, PdfConformance.PdfA2U).Assertions.Select(a => a.RuleId).ToList(); Assert.Contains("ISO19005-2:6.2.11.8-notdef", ids); Assert.DoesNotContain("ISO19005-2:6.2.11.7.2-tounicode", ids); } + + [Fact] + public void PdfUa_aMissingCharacter_failsTheNotdefRule_andNotTheToUnicodeValueRule() + { + var pdf = DocumentDrawingAMissingCharacter(VellumPdf.Document.PdfConformance.PdfUA1); + AssertFixtureHoldsTheChange(pdf); + + var ids = PdfPreflight.Validate(pdf, PdfConformance.PdfUA1).Assertions.Select(a => a.RuleId).ToList(); + + Assert.Contains("ISO14289-1:7.21.8-1", ids); + Assert.DoesNotContain("ISO14289-1:7.21.7-2", ids); + } } diff --git a/tests/VellumPdf.Conformance.Tests/NoBreakSpaceBundledFontTests.cs b/tests/VellumPdf.Conformance.Tests/NoBreakSpaceBundledFontTests.cs index 28a8483bc..86e0083f5 100644 --- a/tests/VellumPdf.Conformance.Tests/NoBreakSpaceBundledFontTests.cs +++ b/tests/VellumPdf.Conformance.Tests/NoBreakSpaceBundledFontTests.cs @@ -135,7 +135,10 @@ public void LiberationMono_toUnicode_aStandInAloneStillNamesItsGlyph() Assert.Contains((narrow, NarrowNoBreakSpace), entries); } - /// Characters the font lacks that are not one of the two spaces get no stand-in, so they stay glyph 0, and the CMap maps glyph 0 to U+FFFD once instead of listing each of them. + /// + /// Characters the font lacks that are not one of the two spaces get no stand-in, so they stay + /// glyph 0, and the CMap maps glyph 0 to U+FFFD once instead of listing each of them. + /// [Fact] public void LiberationMono_toUnicode_missingCharactersThatAreNotSpacesShareOneReplacementEntryForGlyphZero() { diff --git a/tests/VellumPdf.Conformance.Tests/Oracle/ExternalToolResolutionTests.cs b/tests/VellumPdf.Conformance.Tests/Oracle/ExternalToolResolutionTests.cs index 6d75bfc14..b76b8ab1d 100644 --- a/tests/VellumPdf.Conformance.Tests/Oracle/ExternalToolResolutionTests.cs +++ b/tests/VellumPdf.Conformance.Tests/Oracle/ExternalToolResolutionTests.cs @@ -49,6 +49,7 @@ public sealed class ExternalToolResolutionTests ["pdftotext"], ["pdftoppm"], ["pdfsig"], + ["pdffonts"], ["verapdf"], ]; diff --git a/tests/VellumPdf.Kernel.Tests/NotdefGlyphTests.cs b/tests/VellumPdf.Kernel.Tests/NotdefGlyphTests.cs index 2df98780e..1c82485a1 100644 --- a/tests/VellumPdf.Kernel.Tests/NotdefGlyphTests.cs +++ b/tests/VellumPdf.Kernel.Tests/NotdefGlyphTests.cs @@ -31,7 +31,6 @@ public sealed class NotdefGlyphTests IReadOnlyList list) => [.. list.Select(e => (e.Character?.ToString(), e.FontResourceName, e.FontName, e.Count))]; - // \u2500\u2500 The ToUnicode CMap \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 private static List BfcharLines(string map) => [.. map.Split('\n').Where(l => l.StartsWith("<", StringComparison.Ordinal) && l != "<0000> ")]; @@ -110,7 +109,6 @@ public void KernelDocument_drawingAMissingCharacter_mapsGlyphZeroToReplacementCh Assert.Equal(["<0000> ", "<0024> <0041>"], BfcharLines(map)); } - // \u2500\u2500 The canvas list \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 [Fact] public void ShowEmbeddedText_writesTheBytesGetGlyphIdsAndShowGlyphsWrite_andListsEachCharacter() @@ -258,7 +256,6 @@ public void Counts_saturateAtIntMaxValue() Assert.Equal(int.MaxValue, tally.Dropped); } - // \u2500\u2500 The page and the document \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 private static PdfPage FinishedPage(PdfDocument doc, params string[] resources) { @@ -404,4 +401,92 @@ public void PrepareForSigning_leavesTheDocumentListAsItWas() Assert.Equal(expected, Project(doc.NotdefGlyphs)); } + + + [Fact] + public void TheSameCharacterInTwoFonts_isTwoEntries() + { + using var doc = NewDocument(); + var dejaVu = doc.UseTrueTypeFont(Font("DejaVuSans.ttf")); + var mono = doc.UseTrueTypeFont(Font("LiberationMono-Regular.ttf")); + var canvas = new PdfCanvas(doc.AddPage()); + canvas.BeginText(); + canvas.SetFontByName(dejaVu.ResourceName, 12).ShowEmbeddedText(dejaVu, "\u26B9"); + canvas.SetFontByName(mono.ResourceName, 12).ShowEmbeddedText(mono, "\u26B9"); + canvas.EndText(); + + Assert.Equal( + [("\u26B9", "TT1", "DejaVuSans", 1), ("\u26B9", "TT2", "LiberationMono", 1)], + Project(canvas.NotdefGlyphs)); + } + + [Fact] + public void ACharacterThatWasOnlyMeasuredAsGlyphZero_getsTheToUnicodeEntry_andNoWrite() + { + using var doc = NewDocument(); + var page = doc.AddPage(); + var handle = doc.UseTrueTypeFont(Font("DejaVuSans.ttf")); + doc.RegisterEmbeddedFontUsage(page, handle); + handle.MeasureString("\u26B9", 12); + var canvas = new PdfCanvas(page); + canvas.BeginText().SetFontByName(handle.ResourceName, 12).ShowEmbeddedText(handle, "A").EndText(); + canvas.Finish(); + using var ms = new MemoryStream(); + doc.Save(ms); + + var map = Encoding.ASCII.GetString(Assert.Single(ToUnicodeLineEndTests.ToUnicodeMaps(ms.ToArray()))); + + Assert.Equal(["<0000> ", "<0024> <0041>"], BfcharLines(map)); + Assert.Empty(canvas.NotdefGlyphs); + Assert.Empty(doc.NotdefGlyphs); + } + + [Fact] + public void GlyphIdsPassedStraightToShowGlyphs_addNoToUnicodeEntryForGlyphZero() + { + using var doc = NewDocument(); + var page = doc.AddPage(); + var handle = doc.UseTrueTypeFont(Font("DejaVuSans.ttf")); + doc.RegisterEmbeddedFontUsage(page, handle); + var ids = new ushort[1]; + handle.GetGlyphIds("A", ids); + var canvas = new PdfCanvas(page); + canvas.BeginText().SetFontByName(handle.ResourceName, 12).ShowGlyphs([0, ids[0]]).EndText(); + canvas.Finish(); + using var ms = new MemoryStream(); + doc.Save(ms); + + var map = Encoding.ASCII.GetString(Assert.Single(ToUnicodeLineEndTests.ToUnicodeMaps(ms.ToArray()))); + + Assert.Equal(["<0024> <0041>"], BfcharLines(map)); + Assert.Equal([(null, "TT1", null, 1)], Project(canvas.NotdefGlyphs)); + } + + [Fact] + public async Task ARefusedSaveAsync_leavesTheDocumentListAsItWas() + { + var (doc, expected) = DocumentWithOneEntry(); + using var _ = doc; + var closed = new MemoryStream(); + closed.Dispose(); + + await Assert.ThrowsAnyAsync(() => doc.SaveAsync(closed, TestContext.Current.CancellationToken)); + + Assert.Equal(expected, Project(doc.NotdefGlyphs)); + } + + [Fact] + public void ARefusedPrepareForSigning_leavesTheDocumentListAsItWas() + { + var (doc, expected) = DocumentWithOneEntry(); + using var _ = doc; + + Assert.ThrowsAny(() => doc.PrepareForSigning(new SignaturePlaceholderOptions + { + SignaturePage = -1, + SigningTime = new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero), + })); + + Assert.Equal(expected, Project(doc.NotdefGlyphs)); + } } diff --git a/tests/VellumPdf.Layout.Tests/FontReportByteIdentityTests.cs b/tests/VellumPdf.Layout.Tests/FontReportByteIdentityTests.cs index 2edec9f2d..ce7b1d66b 100644 --- a/tests/VellumPdf.Layout.Tests/FontReportByteIdentityTests.cs +++ b/tests/VellumPdf.Layout.Tests/FontReportByteIdentityTests.cs @@ -18,7 +18,8 @@ namespace VellumPdf.Layout.Tests; /// The reports for glyph 0 and for an unembedded font add diagnostics and one ToUnicode entry; they /// do not change what the save writes otherwise (#592, #593). These pin the bytes of documents that /// reach the changed drawing sites, hashed after the same normalisation the placement-loop pins -/// use. The hashes were taken before the change. +/// use. The hashes are those of a build without the reports, so they move when a change to the +/// library alters what it writes for these documents. /// public sealed class FontReportByteIdentityTests { @@ -33,7 +34,7 @@ private static Document Embedded(PdfConformance c, out TextStyle style, double s } // A claim, a default style, and a list and a table that do not use it. - private static byte[] G3() + private static byte[] DefaultFontWithUnstyledListAndTable() { using var doc = Embedded(PdfConformance.PdfA2u, out var style); doc.SetDefaultFont(style); @@ -48,7 +49,7 @@ private static byte[] G3() } // The same, with an unstyled paragraph, heading and footer too. - private static byte[] B593() + private static byte[] UnstyledElementsAndFooterUnderAClaim() { using var doc = Embedded(PdfConformance.PdfA2u, out var style); doc.SetDefaultFont(style); @@ -66,7 +67,7 @@ private static byte[] B593() } // An empty cell in the default font. - private static byte[] B3() + private static byte[] EmptyUnstyledCell() { using var doc = Embedded(PdfConformance.PdfA2u, out var style, 12); doc.Add(new Paragraph("x", style)); @@ -77,7 +78,7 @@ private static byte[] B3() } // Two runs of one font at two sizes: the second is drawn at the size of the first. - private static byte[] Sizes() + private static byte[] TwoSizesOfOneFont() { using var doc = NewDocument(PdfConformance.None); var font = doc.UseTrueTypeFont(DejaVuBytes); @@ -117,25 +118,25 @@ private static byte[] Mixed() } [Fact] - public void G3_pinsBytes() => Pin("017D92FAF138AA27AA9017AA0E14A3FD74A6A492E81D17BF8B1F2EE4A6BB583E", G3()); + public void DefaultFontWithUnstyledListAndTable_pinsBytes() => Pin("AA73683C89C619860C1C6F8186CBC71627EA9DF9536F8842BDF5C61A17062624", DefaultFontWithUnstyledListAndTable()); [Fact] - public void B593_pinsBytes() => Pin("2734A24F2D1468EE6595743EF9DCC2AF8710E7E27A58254103572BC682D534E8", B593()); + public void UnstyledElementsAndFooterUnderAClaim_pinsBytes() => Pin("75D28BEF643ED0314FBFA1BD2BAF650323D5C1C49991149DEE87DA9D03B25EC1", UnstyledElementsAndFooterUnderAClaim()); [Fact] - public void B3_pinsBytes() => Pin("DC5A7C047A27937AE8831209F13C63C3D199C30670AE38288BB05E7CFD7C661D", B3()); + public void EmptyUnstyledCell_pinsBytes() => Pin("4E8A3E5ED673875A32D725DFA2580A780458527DA36CE7C10D2EED34873F19F3", EmptyUnstyledCell()); [Fact] - public void Sizes_pinsBytes_andWritesOneFontOperator() + public void TwoSizesOfOneFont_pinsBytes_andWritesOneFontOperator() { - var pdf = Sizes(); + var pdf = TwoSizesOfOneFont(); Assert.Equal(["/TT1 10 Tf"], TfLines(pdf)); - Pin("1176E8A54DA85123D336594E0DFB5BD7BB4461DE3AF0F83FE24E64B9BF522E53", pdf); + Pin("F43A4C9947E3A4630FC0A7F3AF69141EFEC37C1F6295FE2727B2AB37E57588D0", pdf); } [Fact] - public void MixedNoClaimDocument_pinsBytes() => Pin("48AEBB1188593377629E948FCA1E73363BC6AE47B6A27493DC3E005B8A5C974F", Mixed()); + public void MixedNoClaimDocument_pinsBytes() => Pin("55AE9646D345D4F18987546EEF5A862346A8E1C800B826286F6266C4464E9681", Mixed()); // The ToUnicode stream is the one place the change moves a byte for a document that draws a // missing character, so a projection without it is what must equal the file from before. @@ -161,6 +162,6 @@ public void AMissingCharacterDocument_differsOnlyInItsToUnicodeStream() var pdf = Save(doc); Assert.Contains("<0000> ", BfcharLines(pdf)); - Assert.True("E0FA95F4D77D310F8359CBF807FA884EA934D40132B2F00B1090D6078031E92C" == ProjectionWithoutToUnicode(pdf), $"computed {ProjectionWithoutToUnicode(pdf)}"); + Assert.True("418EEEA4A3F947CB0DDAB22D49AE6AE9993B24796C377E384E953CC14A8FBF71" == ProjectionWithoutToUnicode(pdf), $"computed {ProjectionWithoutToUnicode(pdf)}"); } } diff --git a/tests/VellumPdf.Layout.Tests/NotdefGlyphReportTests.cs b/tests/VellumPdf.Layout.Tests/NotdefGlyphReportTests.cs index 4f47e5148..d078e3053 100644 --- a/tests/VellumPdf.Layout.Tests/NotdefGlyphReportTests.cs +++ b/tests/VellumPdf.Layout.Tests/NotdefGlyphReportTests.cs @@ -48,7 +48,6 @@ private static void AssertItem( private const string MessageStar = "U+26B9 has no glyph in DejaVuSans (TT1) and is drawn as glyph 0 (.notdef)."; private const string MessageSun = "U+1F31F has no glyph in DejaVuSans (TT1) and is drawn as glyph 0 (.notdef)."; - // \u2500\u2500 The report, the content stream and the ToUnicode map \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 [Fact] public void MissingCharacters_areReportedOnceEach_andTheContentIsUnchanged() @@ -158,7 +157,6 @@ public void AStandInGlyph_isNotGlyphZero_andIsNotReported() Assert.DoesNotContain(BfcharLines(pdf), l => l.StartsWith("<0000>", StringComparison.Ordinal)); } - // \u2500\u2500 One document per drawing site, so a site that stops reporting changes the item list \u2500\u2500\u2500\u2500 private static Document SiteDocument(Action add) { @@ -214,7 +212,6 @@ private static void AssertSiteDispose(Document doc, LayoutElementKind kind, int? using (doc) AssertSite(doc, kind, index); } - // \u2500\u2500 A custom renderer, and the sink on its own \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 [Fact] public void AnIdPassedToShowGlyphs_isReportedWithTheCharacterUnknown_andStrictRefusesIt() @@ -287,7 +284,6 @@ public void TheSink_countsWhatTheCanvasDropped_andReadsItOnce() Assert.Equal(1003, sink.ErrorReports); } - // \u2500\u2500 The same data through the Kernel list \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 [Fact] public void ThroughADocumentRenderer_theKernelListHoldsTheSameEntries() @@ -324,7 +320,6 @@ public void AHelveticaParagraph_reportsTheUnencodableCharacters_andNoGlyphZero() doc.Diagnostics.Select(i => i.Message)); } - // \u2500\u2500 What byte-identity means here: only the ToUnicode map moves \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 [Fact] public void TheMissingCharacterDocument_differsFromOneWithoutThemOnlyInItsToUnicodeMap() @@ -337,7 +332,6 @@ public void TheMissingCharacterDocument_differsFromOneWithoutThemOnlyInItsToUnic Assert.DoesNotContain("<0000> ", BfcharLines(pdf)); } - // \u2500\u2500 Oracles \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 [Fact] public void VeraPdf_failsOnlyTheNotdefRule_andNotTheToUnicodeRule() @@ -398,4 +392,38 @@ public void Qpdf_checksTheFile_clean() Assert.True(exit == 0, $"qpdf --check exit {exit}\n{stdout}\n{stderr}"); Assert.Contains("No syntax or stream encoding errors found", stdout, StringComparison.Ordinal); } + + + [Fact] + public void TheSameCharacter_isOneItemPerFont_countedAcrossElements() + { + using var doc = NewDocument(PdfConformance.None); + var dejaVu = new TextStyle { FontRef = doc.UseTrueTypeFont(DejaVuBytes) }; + var mono = new TextStyle { FontRef = doc.UseTrueTypeFont(LiberationMonoBytes) }; + doc.Add(new Paragraph("a\u26B9", dejaVu)); + doc.Add(new Paragraph("b\u26B9", dejaVu)); + doc.Add(new Paragraph("c\u26B9", mono)); + + Save(doc); + + Assert.Equal(2, doc.Diagnostics.Count); + AssertItem(doc.Diagnostics[0], MessageStar, null, LayoutElementKind.Paragraph, 0, 2); + AssertItem( + doc.Diagnostics[1], + "U+26B9 has no glyph in LiberationMono (TT2) and is drawn as glyph 0 (.notdef).", + null, LayoutElementKind.Paragraph, 2, 1); + } + + [Fact] + public void ARendererThatPassesIds_addsNoToUnicodeEntryForGlyphZero() + { + using var doc = NewDocument(PdfConformance.PdfA2u); + var font = doc.UseTrueTypeFont(DejaVuBytes); + doc.Add(new Paragraph("A", new TextStyle { FontRef = font })); + doc.Add(new GlyphIdRenderer(font, [0, 36])); + + var pdf = Save(doc); + + Assert.DoesNotContain(BfcharLines(pdf), l => l.StartsWith("<0000>", StringComparison.Ordinal)); + } } diff --git a/tests/VellumPdf.Layout.Tests/UnembeddedFontReportTests.cs b/tests/VellumPdf.Layout.Tests/UnembeddedFontReportTests.cs index 67fdfaff6..95c63b9a1 100644 --- a/tests/VellumPdf.Layout.Tests/UnembeddedFontReportTests.cs +++ b/tests/VellumPdf.Layout.Tests/UnembeddedFontReportTests.cs @@ -203,7 +203,6 @@ public void AStandard14ValueTheEnumerationDoesNotName_isNotReported_andTheSaveTh Assert.Empty(doc.Diagnostics); } - // ── One document per drawing site ──────────────────────────────────────── private static LayoutDiagnostic OnlyItem(Document doc) { @@ -249,7 +248,6 @@ public void AFooterBand_isReported() => d.SetFooter("foot", s); })), "Helvetica", Clause2u, LayoutElementKind.Footer, null, 1); - // ── Oracles ────────────────────────────────────────────────────────────── [Fact] public void VeraPdf_failsOnlyTheEmbeddingRule_forTheDefaultFontDocument_andForTheEmptyCell() @@ -264,7 +262,10 @@ public void VeraPdf_failsOnlyTheEmbeddingRule_forTheDefaultFontDocument_andForTh var table = new TableElement(); table.AddRow().AddCell(""); empty.Add(table); - Assert.Equal(["6.2.11.4.1-1"], FailedRules(VeraPdf("2u", Save(empty)))); + var emptyPdf = Save(empty); + Assert.Equal(["/TT1 12 Tf", "/F1 12 Tf"], TfLines(emptyPdf)); + Assert.Contains(PdfFontsNames(emptyPdf), n => n.StartsWith("Helvetica", StringComparison.Ordinal)); + Assert.Equal(["6.2.11.4.1-1"], FailedRules(VeraPdf("2u", emptyPdf))); } [Fact] @@ -281,14 +282,19 @@ public void VeraPdf_passesTheDocumentWhoseStylesAreEmbedded() doc.Add(table); var pdf = Save(doc); - Assert.DoesNotContain(PdfFontsRows(pdf), r => !r.Embedded); - Assert.Empty(FailedRules(VeraPdf("2u", pdf))); + var rows = PdfFontsRows(pdf); + Assert.Single(rows, r => r.Name.EndsWith("DejaVuSans", StringComparison.Ordinal) && r.Embedded); + Assert.DoesNotContain(rows, r => !r.Embedded); + var report = VeraPdf("2u", pdf); + Assert.Contains("isCompliant=" + '"' + "true" + '"', report, StringComparison.Ordinal); + Assert.Empty(FailedRules(report)); } [Fact] public void Qpdf_checksTheDefaultFontDocument_clean() { var pdf = Save(DefaultFontDocument(PdfConformance.PdfA2u)); + Assert.Contains("/F1 12 Tf", TfLines(pdf)); using var dir = new TempDir(); var path = dir.Path("subject.pdf"); File.WriteAllBytes(path, pdf); @@ -321,4 +327,36 @@ public void Qpdf_checksTheDefaultFontDocument_clean() private static List PdfFontsNames(byte[] pdf) => [.. PdfFontsRows(pdf).Where(r => !r.Embedded).Select(r => r.Name)]; + + + [Fact] + public void TwoStandard14FontsInOneParagraph_areTwoItems() + { + using var doc = NewDocument(PdfConformance.PdfA2u); + var paragraph = new Paragraph("helv ", new TextStyle { Font = Standard14.Helvetica }); + paragraph.Add("times", new TextStyle { Font = Standard14.TimesRoman }); + doc.Add(paragraph); + + Save(doc); + + Assert.Equal(2, doc.Diagnostics.Count); + AssertItem(doc.Diagnostics[0], "Helvetica", Clause2u, LayoutElementKind.Paragraph, 0, 1); + AssertItem(doc.Diagnostics[1], "Times-Roman", Clause2u, LayoutElementKind.Paragraph, 0, 1); + } + + [Fact] + public void AListOfThreeItems_isOneItemWhoseCountIsSix() + { + using var doc = NewDocument(PdfConformance.PdfA2u); + var list = new ListElement(); + list.Add("one"); + list.Add("two"); + list.Add("three"); + doc.Add(list); + + Save(doc); + + var item = Assert.Single(doc.Diagnostics); + AssertItem(item, "Helvetica", Clause2u, LayoutElementKind.List, 0, 6); + } } diff --git a/tests/VellumPdf.TestSupport/ExternalTool.cs b/tests/VellumPdf.TestSupport/ExternalTool.cs index 27885971c..3c3e58dce 100644 --- a/tests/VellumPdf.TestSupport/ExternalTool.cs +++ b/tests/VellumPdf.TestSupport/ExternalTool.cs @@ -10,8 +10,8 @@ namespace VellumPdf.TestSupport; /// -/// Runs an external oracle CLI — qpdf, pdftotext, pdftoppm, pdfsig, or veraPDF — and captures its -/// output. Consolidates six process runners duplicated across the tree (#198): five +/// Runs an external oracle CLI — qpdf, pdftotext, pdftoppm, pdfsig, pdffonts, or veraPDF — and +/// captures its output. Consolidates six process runners duplicated across the tree (#198): five /// near-identical copies across the Barcodes, Kernel and Layout test projects, plus a sixth of /// its own shape, the conformance suite's own veraPDF runner, which now calls only into this type /// too but never shared the defect below — it already drained with a bounded Wait(5_000). @@ -33,11 +33,11 @@ public static class ExternalTool /// /// Attempts to run with , resolving the - /// executable as described on and, for the five known oracle + /// executable as described on and, for the six known oracle /// tools, verifying its reported identity first (see ). A /// resolution that turns out not to be usable is gated before any output reaches the caller, /// rather than handed back as if it came from the tool the caller asked for. only returns when the tool checks out, so for the five known + /// cref="EnsureUsable(string)"/> only returns when the tool checks out, so for the six known /// tools this method never returns ; a caller-side if /// (!TryRun(...)) guard for one of them is /// unreachable; is only still live for a tool name this type has no @@ -387,7 +387,7 @@ public enum IdentityStatus { Ok, Unusable } /// additionally skips 's escalation under /// CI in favour of , which always skips (see ): a start failure for one of the five known tools is + /// cref="EnsureUsable(IdentityResult)"/>): a start failure for one of the six known tools is /// still a real, actionable absence even though it is not worth caching (#198 review, round /// 4). That leniency is itself bounded: a probe that times out on consecutive attempts is no longer distinguishable @@ -437,7 +437,7 @@ public readonly record struct IdentityResult(IdentityStatus Status, string? Deta private sealed record IdentityProbe(string[] VersionArgs, string ExpectedBannerPrefix, string HomeVariable); // veraPDF is a JVM process launched fresh for every probe, so its startup cost dwarfs the - // other four tools' — all native executables with no comparable cost — even before CI adds a + // other five tools' — all native executables with no comparable cost — even before CI adds a // container on top (ci.yml installs a `/bin/sh` shim around `docker run verapdf/cli`; the // Windows `.bat` launcher below is a separate, developer-machine path that ResolveBatViaHome // only takes under OperatingSystem.IsWindows() and CI does not use). The old, shared @@ -503,7 +503,7 @@ private static int EffectiveVeraPdfProbeTimeoutMs /// /// Verifies that resolves to what it claims to be, caching a - /// definitive verdict for the lifetime of the process — each of the five known oracle tools is + /// definitive verdict for the lifetime of the process — each of the six known oracle tools is /// probed with its own version flag at most once per test run in the common case, the pattern /// the conformance suite's own VeraPdf.IsAvailable uses for a single tool. as the cached value (rather than a plain @@ -621,6 +621,7 @@ private static IdentityResult ProbeIdentityCore(string tool) "pdftotext" => new IdentityProbe(["-v"], "pdftotext version ", "POPPLER_HOME"), "pdftoppm" => new IdentityProbe(["-v"], "pdftoppm version ", "POPPLER_HOME"), "pdfsig" => new IdentityProbe(["-v"], "pdfsig version ", "POPPLER_HOME"), + "pdffonts" => new IdentityProbe(["-v"], "pdffonts version ", "POPPLER_HOME"), "verapdf" => new IdentityProbe(["--version"], "veraPDF ", "VERAPDF_HOME"), _ => null, }; @@ -727,16 +728,15 @@ private static string FirstLine(string text) /// /// Resolves the launcher for a known oracle tool. qpdf, pdftotext, pdftoppm, pdfsig and - /// pdffonts are - /// always resolved through an explicit *_HOME environment variable first — never a bare - /// name as the primary answer, because PATH order alone already picks the wrong + /// pdffonts are always resolved through an explicit *_HOME environment variable first — + /// never a bare name as the primary answer, because PATH order alone already picks the wrong /// pdftotext depending on which shell launched the test host (see the type doc). /// veraPDF only gets that same *_HOME-first treatment on Windows, where it needs one to /// find its .bat launcher at all (see below); on every other platform, including CI's /// ubuntu-latest runner, VERAPDF_HOME is not read here and veraPDF resolves by bare name - /// only, same as an unset *_HOME would for the other four. The bare name remains the + /// only, same as an unset *_HOME would for the other five. The bare name remains the /// fallback when the variable is unset (or not read), which is what a package-manager install - /// already on PATH (CI's case, for all five) needs; when the variable is set but does not + /// already on PATH (CI's case, for all six) needs; when the variable is set but does not /// resolve, is populated instead of silently /// falling back (see ). /// @@ -745,7 +745,7 @@ private static string FirstLine(string text) /// interpreter to run at all, so once resolved it is routed through cmd.exe (anchored /// to rather than resolved bare, since a PATH /// without System32 on it would otherwise make a present veraPDF report as unavailable). The - /// other four ship a ".exe" the runtime can invoke directly. + /// other five ship a ".exe" the runtime can invoke directly. /// private static Launcher ResolveLauncher(string tool) => tool switch { From 166d9c21ddfa2a7ef33853ee5c02437b5a70536e Mon Sep 17 00:00:00 2001 From: Tim81 Date: Sat, 21 Nov 2026 13:41:33 +0100 Subject: [PATCH 4/4] test(layout): re-pin the embedded heading and list digests the font bounding box change moved --- .../VellumPdf.Layout.Tests/RunsHeadingListItemGoldenTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/VellumPdf.Layout.Tests/RunsHeadingListItemGoldenTests.cs b/tests/VellumPdf.Layout.Tests/RunsHeadingListItemGoldenTests.cs index 0260e0cfc..33bc260f8 100644 --- a/tests/VellumPdf.Layout.Tests/RunsHeadingListItemGoldenTests.cs +++ b/tests/VellumPdf.Layout.Tests/RunsHeadingListItemGoldenTests.cs @@ -129,7 +129,7 @@ public void PagedHeadings_pinTheBytes() => [Fact] public void EmbeddedHeadings_pinTheBytes() => - Pin("D1D72594166B30FB73477CE68EAAFC38E5AC2E2445CDE469C94DA20D74AE498B", Hash(EmbeddedHeadings(), fold: true)); + Pin("A14298A33695CED45DF1E66B0640444280DAF3F210C17497B5E63C8EF866EF33", Hash(EmbeddedHeadings(), fold: true)); [Fact] public void Lists_pinTheBytes() => @@ -137,7 +137,7 @@ public void Lists_pinTheBytes() => [Fact] public void EmbeddedLists_pinTheBytes() => - Pin("C487B9DDD09EE2C3E1813913C2831925BC1277906B82BF0E64CCA4FCECED8A2A", Hash(EmbeddedLists(), fold: true)); + Pin("298EABD9F41EF3B0AC352A5A2C9434CFEC09B0E203071C77F735B70E5026A928", Hash(EmbeddedLists(), fold: true)); [Fact] public void NullTextItemAtTheTop_stillThrowsNamingText()