oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package export_test
2
3// A small PDF reader, for tests only.
4//
5// The point of it is that a PDF export cannot be checked by comparing
6// bytes — the interesting properties are "a reader can find the
7// objects", "the pages are there", and "the text can be selected and
8// copied back out", and none of those is visible in a byte comparison.
9// This walks the file the way a reader does: through the trailer to
10// the cross-reference table, through the offsets in it to the objects,
11// and through each font's ToUnicode CMap to turn the glyph ids in a
12// content stream back into words.
13//
14// It follows the file's own xref offsets rather than scanning for
15// "obj", which means a wrong offset fails the test rather than being
16// routed around — the offsets are exactly the kind of thing that is
17// silently wrong in a hand-written PDF writer.
18
19import (
20 "bytes"
21 "compress/zlib"
22 "fmt"
23 "io"
24 "regexp"
25 "strconv"
26 "strings"
27 "testing"
28 "unicode/utf16"
29)
30
31type pdfObject struct {
32 dict string
33 stream []byte // already decompressed
34}
35
36type pdfFile struct {
37 objects map[int]pdfObject
38}
39
40func readPDF(t *testing.T, data []byte) pdfFile {
41 t.Helper()
42
43 if !bytes.HasPrefix(data, []byte("%PDF-1.")) {
44 t.Fatalf("not a PDF: starts with %q", firstLine(data))
45 }
46 if !bytes.HasSuffix(bytes.TrimRight(data, "\n"), []byte("%%EOF")) {
47 t.Fatal("file does not end with the end-of-file marker")
48 }
49
50 // startxref, then the offset on the following line.
51 idx := bytes.LastIndex(data, []byte("startxref"))
52 if idx < 0 {
53 t.Fatal("no startxref")
54 }
55 var xrefAt int
56 if _, err := fmt.Sscanf(string(data[idx:]), "startxref\n%d", &xrefAt); err != nil {
57 t.Fatalf("unreadable startxref: %v", err)
58 }
59 if xrefAt <= 0 || xrefAt >= len(data) {
60 t.Fatalf("startxref points outside the file: %d of %d", xrefAt, len(data))
61 }
62
63 var first, count int
64 if _, err := fmt.Sscanf(string(data[xrefAt:]), "xref\n%d %d", &first, &count); err != nil {
65 t.Fatalf("unreadable xref header at %d: %v", xrefAt, err)
66 }
67 if first != 0 {
68 t.Fatalf("xref starts at object %d, want 0", first)
69 }
70
71 // Entries are exactly 20 bytes each, starting after the two header
72 // lines. Finding the entry table by scanning past the header keeps
73 // this honest about the header's own length.
74 entriesAt := xrefAt + strings.Index(string(data[xrefAt:]), "\n") + 1
75 entriesAt += strings.Index(string(data[entriesAt:]), "\n") + 1
76
77 out := pdfFile{objects: map[int]pdfObject{}}
78 for i := 1; i < count; i++ {
79 at := entriesAt + i*20
80 if at+20 > len(data) {
81 t.Fatalf("xref entry %d runs past the end of the file", i)
82 }
83 entry := string(data[at : at+20])
84 off, err := strconv.Atoi(strings.TrimSpace(entry[:10]))
85 if err != nil {
86 t.Fatalf("xref entry %d is not a number: %q", i, entry)
87 }
88 out.objects[i] = readObject(t, data, i, off)
89 }
90 return out
91}
92
93var lengthRe = regexp.MustCompile(`/Length (\d+)`)
94
95func readObject(t *testing.T, data []byte, num, off int) pdfObject {
96 t.Helper()
97 if off <= 0 || off >= len(data) {
98 t.Fatalf("object %d: offset %d is outside the file", num, off)
99 }
100 want := fmt.Sprintf("%d 0 obj\n", num)
101 if !bytes.HasPrefix(data[off:], []byte(want)) {
102 t.Fatalf("object %d: xref points at %q, not %q", num, firstLine(data[off:]), strings.TrimSpace(want))
103 }
104 body := data[off+len(want):]
105
106 streamAt := bytes.Index(body, []byte("stream\n"))
107 endObj := bytes.Index(body, []byte("\nendobj"))
108 if streamAt < 0 || (endObj >= 0 && endObj < streamAt) {
109 if endObj < 0 {
110 t.Fatalf("object %d: no endobj", num)
111 }
112 return pdfObject{dict: string(body[:endObj])}
113 }
114
115 dict := string(body[:streamAt])
116 m := lengthRe.FindStringSubmatch(dict)
117 if m == nil {
118 t.Fatalf("object %d: a stream with no /Length", num)
119 }
120 n, _ := strconv.Atoi(m[1])
121 start := streamAt + len("stream\n")
122 if start+n > len(body) {
123 t.Fatalf("object %d: /Length %d runs past the end of the file", num, n)
124 }
125 raw := body[start : start+n]
126
127 if !strings.Contains(dict, "/FlateDecode") {
128 return pdfObject{dict: dict, stream: raw}
129 }
130 zr, err := zlib.NewReader(bytes.NewReader(raw))
131 if err != nil {
132 t.Fatalf("object %d: stream is not valid zlib: %v", num, err)
133 }
134 plain, err := io.ReadAll(zr)
135 if err != nil {
136 t.Fatalf("object %d: decompressing: %v", num, err)
137 }
138 return pdfObject{dict: dict, stream: plain}
139}
140
141func firstLine(b []byte) string {
142 if i := bytes.IndexByte(b, '\n'); i >= 0 {
143 b = b[:i]
144 }
145 if len(b) > 60 {
146 b = b[:60]
147 }
148 return string(b)
149}
150
151// pages returns every page object's dictionary, in /Kids order.
152func (f pdfFile) pages(t *testing.T) []pdfObject {
153 t.Helper()
154 var pagesDict string
155 for _, o := range f.objects {
156 if strings.Contains(o.dict, "/Type /Pages") {
157 pagesDict = o.dict
158 }
159 }
160 if pagesDict == "" {
161 t.Fatal("no /Type /Pages node")
162 }
163 kids := regexp.MustCompile(`(\d+) 0 R`).FindAllStringSubmatch(
164 betweenBrackets(t, pagesDict, "/Kids ["), -1)
165 var out []pdfObject
166 for _, k := range kids {
167 n, _ := strconv.Atoi(k[1])
168 o, ok := f.objects[n]
169 if !ok {
170 t.Fatalf("/Kids names object %d, which the xref does not list", n)
171 }
172 if !strings.Contains(o.dict, "/Type /Page") {
173 t.Fatalf("object %d is in /Kids but is not a /Page", n)
174 }
175 out = append(out, o)
176 }
177 return out
178}
179
180func betweenBrackets(t *testing.T, s, open string) string {
181 t.Helper()
182 i := strings.Index(s, open)
183 if i < 0 {
184 t.Fatalf("%q not found in %q", open, s)
185 }
186 rest := s[i+len(open):]
187 j := strings.Index(rest, "]")
188 if j < 0 {
189 t.Fatalf("unterminated %q", open)
190 }
191 return rest[:j]
192}
193
194var (
195 fontResRe = regexp.MustCompile(`/(F\d+) (\d+) 0 R`)
196 contentsRe = regexp.MustCompile(`/Contents (\d+) 0 R`)
197 toUnicodeRe = regexp.MustCompile(`/ToUnicode (\d+) 0 R`)
198 bfcharRe = regexp.MustCompile(`<([0-9A-Fa-f]+)> <([0-9A-Fa-f]+)>`)
199 // One drawn run, exactly as internal/pdf's Page.Text writes it:
200 // the text matrix carries the baseline position, so the x and y a
201 // run actually landed at are readable here and nowhere else. The
202 // glyphs are a TJ array: hex strings with kerning adjustments
203 // between them.
204 showRe = regexp.MustCompile(
205 `/(F\d+) [\d.-]+ Tf 1 0 0 1 ([\d.-]+) ([\d.-]+) Tm \[([^\]]*)\] TJ`)
206 tjHexRe = regexp.MustCompile(`<([0-9A-Fa-f]*)>`)
207 // One filled rectangle (Page.Rule) — the blockquote's edge is the
208 // only non-text drawing this exporter does.
209 ruleRe = regexp.MustCompile(`([\d.-]+) ([\d.-]+) ([\d.-]+) ([\d.-]+) re f`)
210)
211
212// run is one drawn piece of text with where it was drawn: x and y are
213// the baseline's own coordinates, in points from the bottom-left of the
214// page, which is PDF's origin and not the layout's.
215type run struct {
216 x, y float64
217 text string
218}
219
220// cmaps maps each font resource named by a page to its own ToUnicode
221// table — the glyph-id-to-rune mapping a reader uses to let a person
222// copy text out.
223func (f pdfFile) cmaps(t *testing.T, page pdfObject) map[string]map[uint16]string {
224 t.Helper()
225 out := map[string]map[uint16]string{}
226 for _, m := range fontResRe.FindAllStringSubmatch(page.dict, -1) {
227 n, _ := strconv.Atoi(m[2])
228 fontObj, ok := f.objects[n]
229 if !ok {
230 t.Fatalf("page resources name font object %d, which does not exist", n)
231 }
232 tu := toUnicodeRe.FindStringSubmatch(fontObj.dict)
233 if tu == nil {
234 t.Fatalf("font %s has no /ToUnicode — its text cannot be copied out", m[1])
235 }
236 tn, _ := strconv.Atoi(tu[1])
237 cmap := map[uint16]string{}
238 for _, e := range bfcharRe.FindAllStringSubmatch(string(f.objects[tn].stream), -1) {
239 gid, _ := strconv.ParseUint(e[1], 16, 16)
240 cmap[uint16(gid)] = decodeUTF16BEString(e[2])
241 }
242 out[m[1]] = cmap
243 }
244 return out
245}
246
247func (f pdfFile) content(t *testing.T, page pdfObject) string {
248 t.Helper()
249 cm := contentsRe.FindStringSubmatch(page.dict)
250 if cm == nil {
251 t.Fatal("page has no /Contents")
252 }
253 cn, _ := strconv.Atoi(cm[1])
254 return string(f.objects[cn].stream)
255}
256
257// runs returns every drawn piece of text on the page WITH its baseline
258// position, in the order the content stream draws them.
259//
260// text below throws the positions away, which is why a whole-page
261// horizontal offset was invisible to every test in this package until
262// this existed: the words all copied back out correctly, they were just
263// drawn in the margin.
264func (f pdfFile) runs(t *testing.T, page pdfObject) []run {
265 t.Helper()
266 cmaps := f.cmaps(t, page)
267
268 var out []run
269 for _, m := range showRe.FindAllStringSubmatch(f.content(t, page), -1) {
270 cmap, ok := cmaps[m[1]]
271 if !ok {
272 t.Fatalf("content stream uses font %s, which the page resources do not declare", m[1])
273 }
274 x, err := strconv.ParseFloat(m[2], 64)
275 if err != nil {
276 t.Fatalf("unreadable x in the text matrix: %q", m[2])
277 }
278 y, err := strconv.ParseFloat(m[3], 64)
279 if err != nil {
280 t.Fatalf("unreadable y in the text matrix: %q", m[3])
281 }
282 var b strings.Builder
283 for _, h := range tjHexRe.FindAllStringSubmatch(m[4], -1) {
284 hex := h[1]
285 for i := 0; i+4 <= len(hex); i += 4 {
286 gid, _ := strconv.ParseUint(hex[i:i+4], 16, 16)
287 r, ok := cmap[uint16(gid)]
288 if !ok {
289 t.Errorf("glyph %d is drawn but has no ToUnicode entry", gid)
290 continue
291 }
292 b.WriteString(r)
293 }
294 }
295 out = append(out, run{x: x, y: y, text: b.String()})
296 }
297 return out
298}
299
300// rect is one filled rectangle, in PDF coordinates.
301type rect struct{ x, y, w, h float64 }
302
303// rules returns every filled rectangle on the page — the blockquote
304// edge, which is drawn at an x of its own and would sit in the margin
305// alongside the text if that x were wrong.
306func (f pdfFile) rules(t *testing.T, page pdfObject) []rect {
307 t.Helper()
308 var out []rect
309 for _, m := range ruleRe.FindAllStringSubmatch(f.content(t, page), -1) {
310 var r rect
311 for i, dst := range []*float64{&r.x, &r.y, &r.w, &r.h} {
312 v, err := strconv.ParseFloat(m[i+1], 64)
313 if err != nil {
314 t.Fatalf("unreadable rectangle coordinate %q", m[i+1])
315 }
316 *dst = v
317 }
318 out = append(out, r)
319 }
320 return out
321}
322
323// text reconstructs what a person would get by selecting everything on
324// the page and copying it: the glyph ids in the content stream, mapped
325// back through each font's own ToUnicode CMap. If that mapping is
326// wrong or missing, this returns mojibake, which is exactly what a
327// reader would show.
328func (f pdfFile) text(t *testing.T, page pdfObject) string {
329 t.Helper()
330 var b strings.Builder
331 for _, r := range f.runs(t, page) {
332 b.WriteString(r.text)
333 }
334 return b.String()
335}
336
337// decodeUTF16BEString decodes a ToUnicode destination, which is several
338// characters for a ligature.
339func decodeUTF16BEString(hex string) string {
340 var units []uint16
341 for i := 0; i+4 <= len(hex); i += 4 {
342 v, _ := strconv.ParseUint(hex[i:i+4], 16, 16)
343 units = append(units, uint16(v))
344 }
345 return string(utf16.Decode(units))
346}
347