feat(avvfill): Unicode glyphs (Identity-H) instead of Windows-1252
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Successful in 9m6s
ci / image (pull_request) Skipped

With WinAnsi encoding, names like "Michał", "Yılmaz" or "Łódź" fell back to "staff fill it in", a path nobody watches yet. The value is now set as glyph ids of the embedded Geist Regular (Type0 / CIDFontType2, Identity-H) with a ToUnicode map, so any character the font has works and the text still extracts as written. Only control characters and characters without a glyph (e.g. CJK) are refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-11-19 11:23:57 +01:00
1 parent 05673defd4
commit c8dd3ba4dc
3 files changed
+111 -56

No files matched your search

+1 -1
View File
@@ -18,7 +18,6 @@ require (
go.opentelemetry.io/otel/trace v1.47.0
golang.org/x/crypto v0.58.0
golang.org/x/image v0.48.0
golang.org/x/text v0.44.0
)
require (
@@ -93,6 +92,7 @@ require (
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/text v0.44.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect
google.golang.org/grpc v1.83.2 // indirect
+88 -46
View File
@@ -34,7 +34,6 @@ import (
"golang.org/x/image/font"
"golang.org/x/image/font/sfnt"
"golang.org/x/image/math/fixed"
"golang.org/x/text/encoding/charmap"
)
// Values are the Verantwortlicher's details, one per blank line.
@@ -52,8 +51,9 @@ var (
ErrEmpty = errors.New("avvfill: empty value")
// ErrTooLong: a value does not fit its line even at the smallest size.
ErrTooLong = errors.New("avvfill: value too long for its line")
// ErrNotEncodable: a value has a character the font encoding lacks.
ErrNotEncodable = errors.New("avvfill: value has a character outside Windows-1252")
// ErrNotEncodable: a value has a control character or one the font has
// no glyph for.
ErrNotEncodable = errors.New("avvfill: value has a character the font cannot set")
)
// Body size as in the master; a value too long for its line is set smaller,
@@ -113,7 +113,9 @@ func Fill(master []byte, v Values) ([]byte, error) {
if err != nil {
return nil, err
}
fontObj, descObj, fileObj := tr.size, tr.size+1, tr.size+2
// New objects from the master's /Size on.
fontObj, cidObj, descObj, fileObj, uniObj := tr.size, tr.size+1, tr.size+2, tr.size+3, tr.size+4
used := map[uint16]rune{} // glyphs set, for the widths and the ToUnicode map
// The content streams, decoded once each.
content := map[int][]byte{}
@@ -129,13 +131,18 @@ func Fill(master []byte, v Values) ([]byte, error) {
if val == "" {
return nil, ErrEmpty
}
enc, err := charmap.Windows1252.NewEncoder().Bytes([]byte(val))
if err != nil || bytes.IndexByte(enc, 0x7f) >= 0 || bytes.IndexFunc(enc, func(r rune) bool { return r < 32 }) >= 0 {
return nil, ErrNotEncodable
gids, width, err := f.encode(val)
if err != nil {
return nil, err
}
enc := make([]byte, 0, 2*len(gids))
for j, g := range gids {
enc = append(enc, byte(g>>8), byte(g))
used[g] = []rune(val)[j]
}
l := lay.lines[i]
size := bodySize
if w := f.width(enc) / 1000; l.x+w*size > l.right {
if w := width / 1000; l.x+w*size > l.right {
size = float64(int((l.right-l.x)/w*100)) / 100 // round down: the text stays inside
if size < minSize {
return nil, ErrTooLong
@@ -159,11 +166,35 @@ func Fill(master []byte, v Values) ([]byte, error) {
return nil, fmt.Errorf("avvfill: unexpected font dictionary %d", lay.fontDict)
}
objs[lay.fontDict] = append(append(append([]byte{}, fontDict[:end]...), fmt.Sprintf("/FAVV %d 0 R", fontObj)...), fontDict[end:]...)
objs[fontObj] = []byte(fmt.Sprintf("<</Type/Font/Subtype/TrueType/BaseFont/Geist-Regular/FirstChar 32/LastChar 255/Widths[%s]/Encoding/WinAnsiEncoding/FontDescriptor %d 0 R>>",
f.widthsArray(), descObj))
// A composite font: glyph ids as two-byte codes (Identity-H), widths for
// the glyphs used, and a ToUnicode map so the text extracts as written.
order := make([]int, 0, len(used))
for g := range used {
order = append(order, int(g))
}
sort.Ints(order)
var w, cmap strings.Builder
for _, g := range order {
fmt.Fprintf(&w, "%d[%d]", g, f.advance(uint16(g)))
}
for k := 0; k < len(order); k += 100 { // at most 100 entries per bfchar block
chunk := order[k:min(k+100, len(order))]
fmt.Fprintf(&cmap, "%d beginbfchar\n", len(chunk))
for _, g := range chunk {
fmt.Fprintf(&cmap, "<%04X> <%s>\n", g, utf16hex(used[uint16(g)]))
}
cmap.WriteString("endbfchar\n")
}
objs[fontObj] = []byte(fmt.Sprintf("<</Type/Font/Subtype/Type0/BaseFont/Geist-Regular/Encoding/Identity-H/DescendantFonts[%d 0 R]/ToUnicode %d 0 R>>", cidObj, uniObj))
objs[cidObj] = []byte(fmt.Sprintf("<</Type/Font/Subtype/CIDFontType2/BaseFont/Geist-Regular/CIDSystemInfo<</Registry(Adobe)/Ordering(Identity)/Supplement 0>>/FontDescriptor %d 0 R/CIDToGIDMap/Identity/DW 600/W[%s]>>",
descObj, w.String()))
objs[descObj] = []byte(fmt.Sprintf("<</Type/FontDescriptor/FontName/Geist-Regular/Flags 32/FontBBox[%s]/ItalicAngle 0/Ascent %d/Descent %d/CapHeight %d/StemV 80/FontFile2 %d 0 R>>",
f.bbox, f.ascent, f.descent, f.capHeight, fileObj))
objs[fileObj] = flateStream(geistTTF, fmt.Sprintf("/Length1 %d", len(geistTTF)))
objs[uniObj] = flateStream([]byte("/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n"+
"/CIDSystemInfo <</Registry (Adobe) /Ordering (UCS) /Supplement 0>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n"+
"1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n"+cmap.String()+
"endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n"), "")
// The update: objects, a cross-reference section for them, the trailer.
out := bytes.NewBuffer(make([]byte, 0, len(master)+len(geistTTF)))
@@ -197,7 +228,7 @@ func Fill(master []byte, v Values) ([]byte, error) {
i = j + 1
}
fmt.Fprintf(out, "trailer\n<</Size %d/Root %s/Info %s/ID %s/Prev %d>>\nstartxref\n%d\n%%%%EOF\n",
fileObj+1, tr.root, tr.info, tr.id, tr.startxref, xref)
uniObj+1, tr.root, tr.info, tr.id, tr.startxref, xref)
return out.Bytes(), nil
}
@@ -350,27 +381,54 @@ func streamData(pdf []byte, n int) ([]byte, error) {
var geistTTF []byte
type fontInfo struct {
widths [224]int // codes 32..255, in 1/1000 em
ft *sfnt.Font
upem fixed.Int26_6
bbox string
ascent, descent, capHeight int
}
func (f *fontInfo) width(enc []byte) float64 {
w := 0
for _, c := range enc {
if c >= 32 {
w += f.widths[c-32]
}
}
return float64(w)
// scale turns font units into 1/1000 em.
func (f *fontInfo) scale(v fixed.Int26_6) int {
return int((int64(v)*1000 + int64(f.upem)/2) / int64(f.upem))
}
func (f *fontInfo) widthsArray() string {
s := make([]string, len(f.widths))
for i, w := range f.widths {
s[i] = strconv.Itoa(w)
// encode maps a value to glyph ids and its width in 1/1000 em. A control
// character or one without a glyph refuses the value.
func (f *fontInfo) encode(val string) ([]uint16, float64, error) {
var buf sfnt.Buffer
var gids []uint16
w := 0
for _, r := range val {
if r < 0x20 || (r >= 0x7f && r < 0xa0) {
return nil, 0, ErrNotEncodable
}
gi, err := f.ft.GlyphIndex(&buf, r)
if err != nil || gi == 0 {
return nil, 0, ErrNotEncodable
}
adv, err := f.ft.GlyphAdvance(&buf, gi, f.upem, font.HintingNone)
if err != nil {
return nil, 0, ErrNotEncodable
}
gids = append(gids, uint16(gi))
w += f.scale(adv)
}
return strings.Join(s, " ")
return gids, float64(w), nil
}
func (f *fontInfo) advance(g uint16) int {
var buf sfnt.Buffer
adv, _ := f.ft.GlyphAdvance(&buf, sfnt.GlyphIndex(g), f.upem, font.HintingNone)
return f.scale(adv)
}
// utf16hex is r in UTF-16BE, as hex (a surrogate pair beyond the BMP).
func utf16hex(r rune) string {
if r < 0x10000 {
return fmt.Sprintf("%04X", r)
}
r -= 0x10000
return fmt.Sprintf("%04X%04X", 0xd800+(r>>10), 0xdc00+(r&0x3ff))
}
var geist = sync.OnceValues(func() (*fontInfo, error) {
@@ -379,33 +437,17 @@ var geist = sync.OnceValues(func() (*fontInfo, error) {
return nil, fmt.Errorf("avvfill: font: %w", err)
}
var buf sfnt.Buffer
upem := fixed.Int26_6(ft.UnitsPerEm())
ppem := upem // advances in font units
scale := func(v fixed.Int26_6) int { return int((int64(v)*1000 + int64(upem)/2) / int64(upem)) }
f := &fontInfo{}
dec := charmap.Windows1252
for c := 32; c <= 255; c++ {
r := dec.DecodeByte(byte(c))
gi, err := ft.GlyphIndex(&buf, r)
if err != nil || gi == 0 {
gi, _ = ft.GlyphIndex(&buf, ' ') // a code the font lacks takes a space's width
}
adv, err := ft.GlyphAdvance(&buf, gi, ppem, font.HintingNone)
if err != nil {
return nil, fmt.Errorf("avvfill: font: %w", err)
}
f.widths[c-32] = scale(adv)
}
b, err := ft.Bounds(&buf, ppem, font.HintingNone)
f := &fontInfo{ft: ft, upem: fixed.Int26_6(ft.UnitsPerEm())}
b, err := ft.Bounds(&buf, f.upem, font.HintingNone)
if err != nil {
return nil, fmt.Errorf("avvfill: font: %w", err)
}
// sfnt's y axis points down; PDF's up.
f.bbox = fmt.Sprintf("%d %d %d %d", scale(b.Min.X), -scale(b.Max.Y), scale(b.Max.X), -scale(b.Min.Y))
m, err := ft.Metrics(&buf, ppem, font.HintingNone)
f.bbox = fmt.Sprintf("%d %d %d %d", f.scale(b.Min.X), -f.scale(b.Max.Y), f.scale(b.Max.X), -f.scale(b.Min.Y))
m, err := ft.Metrics(&buf, f.upem, font.HintingNone)
if err != nil {
return nil, fmt.Errorf("avvfill: font: %w", err)
}
f.ascent, f.descent, f.capHeight = scale(m.Ascent), -scale(m.Descent), scale(m.CapHeight)
f.ascent, f.descent, f.capHeight = f.scale(m.Ascent), -f.scale(m.Descent), f.scale(m.CapHeight)
return f, nil
})
+22 -9
View File
@@ -11,8 +11,6 @@ import (
"strings"
"testing"
"golang.org/x/text/encoding/charmap"
"git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs"
)
@@ -77,7 +75,7 @@ func TestFill_appendsOneUpdateAndKeepsTheMaster(t *testing.T) {
seen++
}
}
if seen != 6 { // two content streams, the font dictionary, font, descriptor, file
if seen != 8 { // two content streams, the font dictionary; Type0 font, CID font, descriptor, file, ToUnicode
t.Errorf("%d updated objects", seen)
}
@@ -89,7 +87,15 @@ func TestFill_appendsOneUpdateAndKeepsTheMaster(t *testing.T) {
if err != nil {
t.Fatal(err)
}
enc, _ := charmap.Windows1252.NewEncoder().Bytes([]byte(val))
f, _ := geist()
gids, _, err := f.encode(val)
if err != nil {
t.Fatal(err)
}
enc := make([]byte, 0, 2*len(gids))
for _, g := range gids {
enc = append(enc, byte(g>>8), byte(g))
}
run := data[bytes.Index(data, []byte(l.run)):]
run = run[:bytes.Index(run, []byte("ET"))]
want := "<01>]TJ/FAVV 10 Tf<" + hex.EncodeToString(enc) + ">Tj"
@@ -97,9 +103,15 @@ func TestFill_appendsOneUpdateAndKeepsTheMaster(t *testing.T) {
t.Errorf("line %d: %s", i, run)
}
}
if !bytes.Contains(upd, []byte("/FAVV 430 0 R")) || !bytes.Contains(upd, []byte("/FontFile2 432 0 R")) {
if !bytes.Contains(upd, []byte("/FAVV 430 0 R")) || !bytes.Contains(upd, []byte("/DescendantFonts[431 0 R]/ToUnicode 434 0 R")) ||
!bytes.Contains(upd, []byte("/FontFile2 433 0 R")) {
t.Error("font not wired in")
}
// The ToUnicode map gives back what was written: "ß" maps to U+00DF.
uni, err := streamData(upd, 434)
if err != nil || !bytes.Contains(uni, []byte("<00DF>\n")) || !bytes.Contains(uni, []byte("/Adobe-Identity-UCS")) {
t.Errorf("ToUnicode: %v %s", err, uni)
}
}
func TestFill_shrinksALongValueAndRefusesWhatDoesNotFit(t *testing.T) {
@@ -121,7 +133,7 @@ func TestFill_shrinksALongValueAndRefusesWhatDoesNotFit(t *testing.T) {
}{
"too long": {Values{sample.Name, sample.Anschrift, sample.Vertreten, strings.Repeat("Geschäftsleitung ", 6)}, ErrTooLong},
"empty": {Values{sample.Name, " ", sample.Vertreten, sample.Weisung}, ErrEmpty},
"not 1252": {Values{"Łódź Sp. z o.o.", sample.Anschrift, sample.Vertreten, sample.Weisung}, ErrNotEncodable},
"no glyph": {Values{"株式会社ムスター", sample.Anschrift, sample.Vertreten, sample.Weisung}, ErrNotEncodable},
"control": {Values{"Muster\x01GmbH", sample.Anschrift, sample.Vertreten, sample.Weisung}, ErrNotEncodable},
} {
if _, err := Fill(m, c.v); !errors.Is(err, c.want) {
@@ -131,9 +143,10 @@ func TestFill_shrinksALongValueAndRefusesWhatDoesNotFit(t *testing.T) {
if _, err := Fill([]byte("%PDF-1.7 other"), sample); !errors.Is(err, ErrNoLayout) {
t.Errorf("other master: %v", err)
}
// Whitespace inside a value is collapsed; Windows-1252 extras pass.
if _, err := Fill(m, Values{"Muster „Café“ GmbH", sample.Anschrift, sample.Vertreten, sample.Weisung}); err != nil {
t.Errorf("1252 extras: %v", err)
// Whitespace inside a value is collapsed; any letter the font has passes,
// not only Windows-1252.
if _, err := Fill(m, Values{"Muster „Café“ Łódź Sp. z o.o.", sample.Anschrift, "Michał Yılmaz und Jiří Dvořák", sample.Weisung}); err != nil {
t.Errorf("latin extended: %v", err)
}
}