oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package pdf writes PDF files with embedded, subsetted TrueType
2// fonts.
3//
4// It knows nothing about documents, paragraphs or CRDTs — it takes
5// pages, and text placed on them at a position in a face at a size,
6// and produces bytes. internal/export is what turns a document into
7// those calls. The split is deliberate: laying text out and writing a
8// PDF are two jobs, and the one that has to be right about byte
9// offsets and object numbers should not also be the one deciding where
10// a line breaks.
11//
12// # What it emits, and why that shape
13//
14// Text is drawn through a Type0 (composite) font with Identity-H
15// encoding and a CIDFontType2 descendant. That is more machinery than
16// a simple /TrueType font with WinAnsiEncoding, and it buys two things
17// worth the machinery:
18//
19// - Any character the face has a glyph for, not the 224 a single-byte
20// encoding can name. A document with a — or a “ or a café in it is
21// ordinary, and an exporter that mangles them is not usable.
22// - Glyph ids addressed directly, which is what internal/fonts'
23// subsetter produces (it keeps ids where they are), so CIDToGIDMap
24// is /Identity and there is no mapping table to get wrong.
25//
26// The cost is that the text in the content stream is glyph ids, which
27// no longer resemble the words. A /ToUnicode CMap is what gives them
28// back, and it is not optional garnish: without one, selecting and
29// copying text out of the exported PDF yields nonsense, and so does
30// searching it. §11.3 asks for a PDF, and a PDF whose text cannot be
31// copied is a picture.
32package pdf
33
34import (
35 "bytes"
36 "compress/zlib"
37 "fmt"
38 "sort"
39 "strings"
40
41 "github.com/carlosframework/docs/internal/fonts"
42)
43
44// Builder accumulates pages and the fonts they use.
45type Builder struct {
46 Width, Height float64 // points
47 Title string
48
49 pages []*Page
50
51 // used records, per face, which glyphs the document draws and what
52 // each one means in Unicode. Both halves are needed at the end:
53 // the ids to subset with, the runes to write the ToUnicode CMap
54 // from.
55 used map[string]*faceUse
56}
57
58type faceUse struct {
59 face *fonts.Face
60 font *fonts.Font
61 glyphs map[uint16]bool
62 unicode map[uint16]string
63 // resource is the name this face is known by inside a page's
64 // resource dictionary ("F0", "F1", ...).
65 resource string
66}
67
68// Page is one page's content stream, built up as PDF operators.
69type Page struct {
70 b *Builder
71 ops bytes.Buffer
72}
73
74// New starts a document of the given page size, in points (72 to the
75// inch).
76func New(width, height float64) *Builder {
77 return &Builder{Width: width, Height: height, used: map[string]*faceUse{}}
78}
79
80// AddPage appends a page and returns it.
81func (b *Builder) AddPage() *Page {
82 p := &Page{b: b}
83 b.pages = append(b.pages, p)
84 return p
85}
86
87// PageCount is how many pages have been added.
88func (b *Builder) PageCount() int { return len(b.pages) }
89
90func (b *Builder) use(face *fonts.Face) (*faceUse, error) {
91 if u, ok := b.used[face.File]; ok {
92 return u, nil
93 }
94 font, err := face.Parsed()
95 if err != nil {
96 return nil, err
97 }
98 u := &faceUse{
99 face: face,
100 font: font,
101 glyphs: map[uint16]bool{},
102 unicode: map[uint16]string{},
103 resource: fmt.Sprintf("F%d", len(b.used)),
104 }
105 b.used[face.File] = u
106 return u, nil
107}
108
109// Text draws a shaped run with its baseline at (x, y), measured in
110// points from the bottom-left of the page — PDF's own origin, not the
111// top-left the layout above it thinks in. Converting between the two is
112// internal/export's job, done once, rather than a subtraction repeated
113// at every call site here.
114//
115// The run comes from fonts.Shaper, so it is already kerned and ligated:
116// each glyph is drawn by id, and a TJ adjustment moves the pen from the
117// glyph's own advance (the /W array) to the shaped one. That is what
118// makes the PDF's lines the screen's lines.
119//
120// gray is 0 for ordinary black text; a blockquote sets it lighter.
121// A .notdef glyph is still drawn (a visible box, the loud degradation);
122// the caller has the run's Missing runes to report.
123func (p *Page) Text(x, y float64, face *fonts.Face, size, gray float64, run fonts.Run) error {
124 if len(run.Glyphs) == 0 {
125 return nil
126 }
127 u, err := p.b.use(face)
128 if err != nil {
129 return err
130 }
131 upm := float64(u.font.UnitsPerEm)
132
133 var tj strings.Builder
134 tj.WriteByte('[')
135 open := false
136 adjust := func(n float64) {
137 // n is in thousandths of an em, positive moving left: TJ's own
138 // sign. Rounded to the thousandth; anything smaller is below a
139 // printer's resolution at any size a document uses.
140 if n > -0.0005 && n < 0.0005 {
141 return
142 }
143 if open {
144 tj.WriteByte('>')
145 open = false
146 }
147 fmt.Fprintf(&tj, " %s ", num(n))
148 }
149 for _, g := range run.Glyphs {
150 u.glyphs[g.ID] = true
151 // First text wins for a glyph several strings map to (a face may
152 // draw U+00A0 with the space glyph).
153 if _, seen := u.unicode[g.ID]; !seen && g.Text != "" {
154 u.unicode[g.ID] = g.Text
155 }
156 adjust(-g.XOffset * 1000)
157 if !open {
158 tj.WriteByte('<')
159 open = true
160 }
161 fmt.Fprintf(&tj, "%04X", g.ID)
162 nominal := float64(u.font.Advance(g.ID)) / upm
163 adjust((nominal - g.Advance + g.XOffset) * 1000)
164 }
165 if open {
166 tj.WriteByte('>')
167 }
168 tj.WriteByte(']')
169
170 // q/Q around every run so a grey blockquote cannot leak its fill
171 // colour into whatever is drawn next — the operators are a stack,
172 // and the cheapest correct discipline is to leave it as it was
173 // found.
174 fmt.Fprintf(&p.ops, "q %s g BT /%s %s Tf 1 0 0 1 %s %s Tm %s TJ ET Q\n",
175 num(gray), u.resource, num(size), num(x), num(y), tj.String())
176 return nil
177}
178
179// Rule draws a filled rectangle — the one piece of non-text drawing a
180// document needs today, for a blockquote's edge. gray is 0 (black) to
181// 1 (white).
182func (p *Page) Rule(x, y, w, h, gray float64) {
183 fmt.Fprintf(&p.ops, "q %s g %s %s %s %s re f Q\n", num(gray), num(x), num(y), num(w), num(h))
184}
185
186// num formats a coordinate. PDF has no exponent notation, so %g would
187// eventually emit something no reader accepts; and trailing zeros are
188// trimmed because a content stream is most of the file's bytes.
189func num(f float64) string {
190 s := fmt.Sprintf("%.3f", f)
191 s = strings.TrimRight(s, "0")
192 s = strings.TrimSuffix(s, ".")
193 if s == "" || s == "-" {
194 return "0"
195 }
196 return s
197}
198
199// --- serialisation ---
200
201// object is one indirect object, already serialised except for its
202// number.
203type object struct {
204 body []byte
205}
206
207type writer struct {
208 objects []object
209}
210
211// add appends an object and returns its number (1-based, as PDF
212// numbers them).
213func (w *writer) add(body string) int {
214 w.objects = append(w.objects, object{body: []byte(body)})
215 return len(w.objects)
216}
217
218func (w *writer) addStream(dict string, data []byte) int {
219 // Every stream is Flate-compressed. A page of text compresses to
220 // about a third, and an embedded font subset to about half; the
221 // alternative is a file several times larger for no benefit any
222 // reader notices.
223 var buf bytes.Buffer
224 zw := zlib.NewWriter(&buf)
225 // zlib.Writer.Write on a bytes.Buffer cannot fail, and neither can
226 // Close; the errors are checked anyway rather than ignored with a
227 // comment claiming that, because "cannot fail" is a property of
228 // today's implementation and not of the interface.
229 if _, err := zw.Write(data); err != nil {
230 panic("pdf: compressing a stream: " + err.Error())
231 }
232 if err := zw.Close(); err != nil {
233 panic("pdf: closing a compressed stream: " + err.Error())
234 }
235 body := fmt.Sprintf("<< %s /Filter /FlateDecode /Length %d >>\nstream\n", dict, buf.Len())
236 full := append([]byte(body), buf.Bytes()...)
237 full = append(full, []byte("\nendstream")...)
238 w.objects = append(w.objects, object{body: full})
239 return len(w.objects)
240}
241
242// Bytes serialises the document.
243func (b *Builder) Bytes() ([]byte, error) {
244 w := &writer{}
245
246 // Fonts first: a page's resource dictionary has to name them, and
247 // naming an object means knowing its number.
248 fontRefs := map[string]int{}
249 for _, u := range b.sortedUse() {
250 ref, err := b.writeFont(w, u)
251 if err != nil {
252 return nil, err
253 }
254 fontRefs[u.resource] = ref
255 }
256
257 var resources strings.Builder
258 resources.WriteString("<< /Font << ")
259 for _, u := range b.sortedUse() {
260 fmt.Fprintf(&resources, "/%s %d 0 R ", u.resource, fontRefs[u.resource])
261 }
262 resources.WriteString(">> >>")
263
264 // The Pages node has to be numbered before the pages that name it
265 // as /Parent, and it has to list them as /Kids — a chicken and egg
266 // resolved the way PDF itself expects: reserve the number by
267 // adding a placeholder and rewriting its body once the kids exist.
268 pagesRef := w.add("")
269
270 kids := make([]string, 0, len(b.pages))
271 for _, p := range b.pages {
272 contentRef := w.addStream("", p.ops.Bytes())
273 pageRef := w.add(fmt.Sprintf(
274 "<< /Type /Page /Parent %d 0 R /MediaBox [0 0 %s %s] /Resources %s /Contents %d 0 R >>",
275 pagesRef, num(b.Width), num(b.Height), resources.String(), contentRef))
276 kids = append(kids, fmt.Sprintf("%d 0 R", pageRef))
277 }
278 w.objects[pagesRef-1].body = []byte(fmt.Sprintf(
279 "<< /Type /Pages /Kids [%s] /Count %d >>", strings.Join(kids, " "), len(b.pages)))
280
281 catalogRef := w.add(fmt.Sprintf("<< /Type /Catalog /Pages %d 0 R >>", pagesRef))
282
283 infoRef := w.add(fmt.Sprintf("<< /Title %s /Producer (CARLOS Docs) >>", utf16String(b.Title)))
284
285 return w.serialise(catalogRef, infoRef), nil
286}
287
288// sortedUse returns the faces in resource-name order, so a document
289// built twice from the same content produces the same bytes. Go's map
290// iteration order is deliberately random, and an export that differs
291// run to run cannot be tested by comparison.
292func (b *Builder) sortedUse() []*faceUse {
293 out := make([]*faceUse, 0, len(b.used))
294 for _, u := range b.used {
295 out = append(out, u)
296 }
297 sort.Slice(out, func(i, j int) bool { return out[i].resource < out[j].resource })
298 return out
299}
300
301// writeFont emits the four objects one embedded face needs and returns
302// the number of the Type0 font a page's resources point at.
303func (b *Builder) writeFont(w *writer, u *faceUse) (int, error) {
304 font := u.font
305 upm := float64(font.UnitsPerEm)
306 // PDF glyph space is 1000 units to the em regardless of what the
307 // font uses.
308 scale := func(v float64) float64 { return v * 1000 / upm }
309
310 subset, err := font.Subset(u.glyphs)
311 if err != nil {
312 return 0, fmt.Errorf("pdf: subset %s: %w", u.face.File, err)
313 }
314
315 fileRef := w.addStream(fmt.Sprintf("/Length1 %d", len(subset)), subset)
316
317 flags := 32 // Nonsymbolic: the characters are in the standard Latin set
318 if u.face.Family.Serif() {
319 flags |= 2
320 }
321 if u.face.Family.Monospace() {
322 flags |= 1
323 }
324 if u.face.Italic() {
325 flags |= 64
326 }
327 // StemV has no source in a TrueType file and every writer
328 // approximates it. A reader uses it only to synthesise a
329 // substitute face, which cannot happen here because the face is
330 // embedded.
331 stemV := 80
332 if u.face.Bold() {
333 stemV = 140
334 }
335
336 descRef := w.add(fmt.Sprintf(
337 "<< /Type /FontDescriptor /FontName /%s /Flags %d /FontBBox [%s %s %s %s] "+
338 "/ItalicAngle %s /Ascent %s /Descent %s /CapHeight %s /StemV %d /FontFile2 %d 0 R >>",
339 subsetName(u), flags,
340 num(scale(float64(font.BBox[0]))), num(scale(float64(font.BBox[1]))),
341 num(scale(float64(font.BBox[2]))), num(scale(float64(font.BBox[3]))),
342 num(font.ItalicAngle),
343 num(scale(float64(font.Ascender))), num(scale(float64(font.Descender))),
344 num(scale(float64(font.CapHeight))), stemV, fileRef))
345
346 // /W: the advance of every glyph actually drawn. Glyphs not listed
347 // take /DW, which is why /DW is set to something sane rather than
348 // left at PDF's own 1000 default.
349 gids := make([]int, 0, len(u.glyphs))
350 for g := range u.glyphs {
351 gids = append(gids, int(g))
352 }
353 sort.Ints(gids)
354 var widths strings.Builder
355 for _, g := range gids {
356 fmt.Fprintf(&widths, "%d [%s] ", g, num(scale(float64(font.Advance(uint16(g))))))
357 }
358
359 cidRef := w.add(fmt.Sprintf(
360 "<< /Type /Font /Subtype /CIDFontType2 /BaseFont /%s "+
361 "/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> "+
362 "/FontDescriptor %d 0 R /DW %s /W [%s] /CIDToGIDMap /Identity >>",
363 subsetName(u), descRef, num(scale(float64(font.Advance(0)))), widths.String()))
364
365 toUnicodeRef := w.addStream("", []byte(toUnicodeCMap(u)))
366
367 return w.add(fmt.Sprintf(
368 "<< /Type /Font /Subtype /Type0 /BaseFont /%s /Encoding /Identity-H "+
369 "/DescendantFonts [%d 0 R] /ToUnicode %d 0 R >>",
370 subsetName(u), cidRef, toUnicodeRef)), nil
371}
372
373// subsetName is the PDF convention for a subsetted font: six uppercase
374// letters, a plus sign, then the face's own name. The tag is supposed
375// to distinguish two different subsets of one face inside one file,
376// which cannot happen here — one Builder subsets each face once — so
377// it is derived from the resource name rather than randomly generated,
378// keeping the output byte-identical between runs.
379func subsetName(u *faceUse) string {
380 tag := []byte("AAAAAA")
381 n := 0
382 for _, c := range u.resource {
383 n = n*31 + int(c)
384 }
385 for i := 5; i >= 0; i-- {
386 tag[i] = byte('A' + n%26)
387 n /= 26
388 }
389 return string(tag) + "+" + u.face.PostScriptName()
390}
391
392// toUnicodeCMap writes the CMap that lets a reader turn the glyph ids
393// in the content stream back into text for selection and search.
394func toUnicodeCMap(u *faceUse) string {
395 gids := make([]int, 0, len(u.unicode))
396 for g := range u.unicode {
397 gids = append(gids, int(g))
398 }
399 sort.Ints(gids)
400
401 var b strings.Builder
402 b.WriteString("/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n")
403 b.WriteString("/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n")
404 b.WriteString("/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n")
405 b.WriteString("1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n")
406
407 // bfchar sections are capped at 100 entries by the specification.
408 for start := 0; start < len(gids); start += 100 {
409 end := start + 100
410 if end > len(gids) {
411 end = len(gids)
412 }
413 fmt.Fprintf(&b, "%d beginbfchar\n", end-start)
414 for _, g := range gids[start:end] {
415 fmt.Fprintf(&b, "<%04X> <%s>\n", g, utf16BEHexString(u.unicode[uint16(g)]))
416 }
417 b.WriteString("endbfchar\n")
418 }
419 b.WriteString("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n")
420 return b.String()
421}
422
423// utf16BEHex encodes one rune as big-endian UTF-16 hex, surrogate pair
424// included — an emoji in a document is a perfectly ordinary thing to
425// want to copy back out.
426// utf16BEHexString is a ToUnicode destination: a ligature's glyph maps
427// to every character it stands for.
428func utf16BEHexString(s string) string {
429 var b strings.Builder
430 for _, r := range s {
431 b.WriteString(utf16BEHex(r))
432 }
433 return b.String()
434}
435
436func utf16BEHex(r rune) string {
437 if r > 0xFFFF {
438 r -= 0x10000
439 hi := 0xD800 + (r >> 10)
440 lo := 0xDC00 + (r & 0x3FF)
441 return fmt.Sprintf("%04X%04X", hi, lo)
442 }
443 return fmt.Sprintf("%04X", r)
444}
445
446// utf16String encodes a string as a PDF text string. The UTF-16BE form
447// with a byte-order mark is the only one that can carry a title with
448// anything outside PDFDocEncoding in it, and a document title is
449// arbitrary text somebody typed.
450func utf16String(s string) string {
451 var b strings.Builder
452 b.WriteString("<FEFF")
453 for _, r := range s {
454 b.WriteString(utf16BEHex(r))
455 }
456 b.WriteString(">")
457 return b.String()
458}
459
460// serialise writes the header, the objects, the cross-reference table
461// and the trailer.
462func (w *writer) serialise(catalogRef, infoRef int) []byte {
463 var out bytes.Buffer
464 out.WriteString("%PDF-1.7\n")
465 // A comment line of high bytes, which is how a PDF tells the tools
466 // that transfer it that it is binary and must not be newline-
467 // translated.
468 out.Write([]byte{'%', 0xE2, 0xE3, 0xCF, 0xD3, '\n'})
469
470 offsets := make([]int, len(w.objects)+1)
471 for i, o := range w.objects {
472 offsets[i+1] = out.Len()
473 fmt.Fprintf(&out, "%d 0 obj\n", i+1)
474 out.Write(o.body)
475 out.WriteString("\nendobj\n")
476 }
477
478 xref := out.Len()
479 fmt.Fprintf(&out, "xref\n0 %d\n", len(w.objects)+1)
480 // Object 0 is always the head of the free list.
481 out.WriteString("0000000000 65535 f \n")
482 for i := 1; i <= len(w.objects); i++ {
483 fmt.Fprintf(&out, "%010d 00000 n \n", offsets[i])
484 }
485 fmt.Fprintf(&out, "trailer\n<< /Size %d /Root %d 0 R /Info %d 0 R >>\nstartxref\n%d\n%%%%EOF\n",
486 len(w.objects)+1, catalogRef, infoRef, xref)
487 return out.Bytes()
488}
489