Debian Codegraph @

page.go

raw symbols SCIP
1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package pdf
6
7 import (
8 "fmt"
9 "strings"
10 )
11
12 // A Page represent a single page in a PDF file.
13 // The methods interpret a Page dictionary stored in V.
14 type Page struct {
15 V Value
16 }
17
18 // Page returns the page for the given page number.
19 // Page numbers are indexed starting at 1, not 0.
20 // If the page is not found, Page returns a Page with p.V.IsNull().
21 func (r *Reader) Page(num int) Page {
22 num-- // now 0-indexed
23 page := r.Trailer().Key("Root").Key("Pages")
24 Search:
25 for page.Key("Type").Name() == "Pages" {
26 count := int(page.Key("Count").Int64())
27 if count < num {
28 return Page{}
29 }
30 kids := page.Key("Kids")
31 for i := 0; i < kids.Len(); i++ {
32 kid := kids.Index(i)
33 if kid.Key("Type").Name() == "Pages" {
34 c := int(kid.Key("Count").Int64())
35 if num < c {
36 page = kid
37 continue Search
38 }
39 num -= c
40 continue
41 }
42 if kid.Key("Type").Name() == "Page" {
43 if num == 0 {
44 return Page{kid}
45 }
46 num--
47 }
48 }
49 break
50 }
51 return Page{}
52 }
53
54 // NumPage returns the number of pages in the PDF file.
55 func (r *Reader) NumPage() int {
56 return int(r.Trailer().Key("Root").Key("Pages").Key("Count").Int64())
57 }
58
59 func (p Page) findInherited(key string) Value {
60 for v := p.V; !v.IsNull(); v = v.Key("Parent") {
61 if r := v.Key(key); !r.IsNull() {
62 return r
63 }
64 }
65 return Value{}
66 }
67
68 /*
69 func (p Page) MediaBox() Value {
70 return p.findInherited("MediaBox")
71 }
72
73 func (p Page) CropBox() Value {
74 return p.findInherited("CropBox")
75 }
76 */
77
78 // Resources returns the resources dictionary associated with the page.
79 func (p Page) Resources() Value {
80 return p.findInherited("Resources")
81 }
82
83 // Fonts returns a list of the fonts associated with the page.
84 func (p Page) Fonts() []string {
85 return p.Resources().Key("Font").Keys()
86 }
87
88 // Font returns the font with the given name associated with the page.
89 func (p Page) Font(name string) Font {
90 return Font{p.Resources().Key("Font").Key(name)}
91 }
92
93 // A Font represent a font in a PDF file.
94 // The methods interpret a Font dictionary stored in V.
95 type Font struct {
96 V Value
97 }
98
99 // BaseFont returns the font's name (BaseFont property).
100 func (f Font) BaseFont() string {
101 return f.V.Key("BaseFont").Name()
102 }
103
104 // FirstChar returns the code point of the first character in the font.
105 func (f Font) FirstChar() int {
106 return int(f.V.Key("FirstChar").Int64())
107 }
108
109 // LastChar returns the code point of the last character in the font.
110 func (f Font) LastChar() int {
111 return int(f.V.Key("LastChar").Int64())
112 }
113
114 // Widths returns the widths of the glyphs in the font.
115 // In a well-formed PDF, len(f.Widths()) == f.LastChar()+1 - f.FirstChar().
116 func (f Font) Widths() []float64 {
117 x := f.V.Key("Widths")
118 var out []float64
119 for i := 0; i < x.Len(); i++ {
120 out = append(out, x.Index(i).Float64())
121 }
122 return out
123 }
124
125 // Width returns the width of the given code point.
126 func (f Font) Width(code int) float64 {
127 first := f.FirstChar()
128 last := f.LastChar()
129 if code < first || last < code {
130 return 0
131 }
132 return f.V.Key("Widths").Index(code - first).Float64()
133 }
134
135 // Encoder returns the encoding between font code point sequences and UTF-8.
136 func (f Font) Encoder() TextEncoding {
137 enc := f.V.Key("Encoding")
138 switch enc.Kind() {
139 case Name:
140 switch enc.Name() {
141 case "WinAnsiEncoding":
142 return &byteEncoder{&winAnsiEncoding}
143 case "MacRomanEncoding":
144 return &byteEncoder{&macRomanEncoding}
145 case "Identity-H":
146 // TODO: Should be big-endian UCS-2 decoder
147 return &nopEncoder{}
148 default:
149 println("unknown encoding", enc.Name())
150 return &nopEncoder{}
151 }
152 case Dict:
153 return &dictEncoder{enc.Key("Differences")}
154 case Null:
155 // ok, try ToUnicode
156 default:
157 println("unexpected encoding", enc.String())
158 return &nopEncoder{}
159 }
160
161 toUnicode := f.V.Key("ToUnicode")
162 if toUnicode.Kind() == Dict {
163 m := readCmap(toUnicode)
164 if m == nil {
165 return &nopEncoder{}
166 }
167 return m
168 }
169
170 return &byteEncoder{&pdfDocEncoding}
171 }
172
173 type dictEncoder struct {
174 v Value
175 }
176
177 func (e *dictEncoder) Decode(raw string) (text string) {
178 r := make([]rune, 0, len(raw))
179 for i := 0; i < len(raw); i++ {
180 ch := rune(raw[i])
181 n := -1
182 for j := 0; j < e.v.Len(); j++ {
183 x := e.v.Index(j)
184 if x.Kind() == Integer {
185 n = int(x.Int64())
186 continue
187 }
188 if x.Kind() == Name {
189 if int(raw[i]) == n {
190 r := nameToRune[x.Name()]
191 if r != 0 {
192 ch = r
193 break
194 }
195 }
196 n++
197 }
198 }
199 r = append(r, ch)
200 }
201 return string(r)
202 }
203
204 // A TextEncoding represents a mapping between
205 // font code points and UTF-8 text.
206 type TextEncoding interface {
207 // Decode returns the UTF-8 text corresponding to
208 // the sequence of code points in raw.
209 Decode(raw string) (text string)
210 }
211
212 type nopEncoder struct {
213 }
214
215 func (e *nopEncoder) Decode(raw string) (text string) {
216 return raw
217 }
218
219 type byteEncoder struct {
220 table *[256]rune
221 }
222
223 func (e *byteEncoder) Decode(raw string) (text string) {
224 r := make([]rune, 0, len(raw))
225 for i := 0; i < len(raw); i++ {
226 r = append(r, e.table[raw[i]])
227 }
228 return string(r)
229 }
230
231 type cmap struct {
232 space [4][][2]string
233 bfrange []bfrange
234 }
235
236 func (m *cmap) Decode(raw string) (text string) {
237 var r []rune
238 Parse:
239 for len(raw) > 0 {
240 for n := 1; n <= 4 && n <= len(raw); n++ {
241 for _, space := range m.space[n-1] {
242 if space[0] <= raw[:n] && raw[:n] <= space[1] {
243 text := raw[:n]
244 raw = raw[n:]
245 for _, bf := range m.bfrange {
246 if len(bf.lo) == n && bf.lo <= text && text <= bf.hi {
247 if bf.dst.Kind() == String {
248 s := bf.dst.RawString()
249 if bf.lo != text {
250 b := []byte(s)
251 b[len(b)-1] += text[len(text)-1] - bf.lo[len(bf.lo)-1]
252 s = string(b)
253 }
254 r = append(r, []rune(utf16Decode(s))...)
255 continue Parse
256 }
257 if bf.dst.Kind() == Array {
258 fmt.Printf("array %v\n", bf.dst)
259 } else {
260 fmt.Printf("unknown dst %v\n", bf.dst)
261 }
262 r = append(r, noRune)
263 continue Parse
264 }
265 }
266 fmt.Printf("no text for %q", text)
267 r = append(r, noRune)
268 continue Parse
269 }
270 }
271 }
272 println("no code space found")
273 r = append(r, noRune)
274 raw = raw[1:]
275 }
276 return string(r)
277 }
278
279 type bfrange struct {
280 lo string
281 hi string
282 dst Value
283 }
284
285 func readCmap(toUnicode Value) *cmap {
286 n := -1
287 var m cmap
288 ok := true
289 Interpret(toUnicode, func(stk *Stack, op string) {
290 if !ok {
291 return
292 }
293 switch op {
294 case "findresource":
295 category := stk.Pop()
296 key := stk.Pop()
297 fmt.Println("findresource", key, category)
298 stk.Push(newDict())
299 case "begincmap":
300 stk.Push(newDict())
301 case "endcmap":
302 stk.Pop()
303 case "begincodespacerange":
304 n = int(stk.Pop().Int64())
305 case "endcodespacerange":
306 if n < 0 {
307 println("missing begincodespacerange")
308 ok = false
309 return
310 }
311 for i := 0; i < n; i++ {
312 hi, lo := stk.Pop().RawString(), stk.Pop().RawString()
313 if len(lo) == 0 || len(lo) != len(hi) {
314 println("bad codespace range")
315 ok = false
316 return
317 }
318 m.space[len(lo)-1] = append(m.space[len(lo)-1], [2]string{lo, hi})
319 }
320 n = -1
321 case "beginbfrange":
322 n = int(stk.Pop().Int64())
323 case "endbfrange":
324 if n < 0 {
325 panic("missing beginbfrange")
326 }
327 for i := 0; i < n; i++ {
328 dst, srcHi, srcLo := stk.Pop(), stk.Pop().RawString(), stk.Pop().RawString()
329 m.bfrange = append(m.bfrange, bfrange{srcLo, srcHi, dst})
330 }
331 case "defineresource":
332 category := stk.Pop().Name()
333 value := stk.Pop()
334 key := stk.Pop().Name()
335 fmt.Println("defineresource", key, value, category)
336 stk.Push(value)
337 default:
338 println("interp\t", op)
339 }
340 })
341 if !ok {
342 return nil
343 }
344 return &m
345 }
346
347 type matrix [3][3]float64
348
349 var ident = matrix{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}
350
351 func (x matrix) mul(y matrix) matrix {
352 var z matrix
353 for i := 0; i < 3; i++ {
354 for j := 0; j < 3; j++ {
355 for k := 0; k < 3; k++ {
356 z[i][j] += x[i][k] * y[k][j]
357 }
358 }
359 }
360 return z
361 }
362
363 // A Text represents a single piece of text drawn on a page.
364 type Text struct {
365 Font string // the font used
366 FontSize float64 // the font size, in points (1/72 of an inch)
367 X float64 // the X coordinate, in points, increasing left to right
368 Y float64 // the Y coordinate, in points, increasing bottom to top
369 W float64 // the width of the text, in points
370 S string // the actual UTF-8 text
371 }
372
373 // A Rect represents a rectangle.
374 type Rect struct {
375 Min, Max Point
376 }
377
378 // A Point represents an X, Y pair.
379 type Point struct {
380 X float64
381 Y float64
382 }
383
384 // Content describes the basic content on a page: the text and any drawn rectangles.
385 type Content struct {
386 Text []Text
387 Rect []Rect
388 }
389
390 type gstate struct {
391 Tc float64
392 Tw float64
393 Th float64
394 Tl float64
395 Tf Font
396 Tfs float64
397 Tmode int
398 Trise float64
399 Tm matrix
400 Tlm matrix
401 Trm matrix
402 CTM matrix
403 }
404
405 // Content returns the page's content.
406 func (p Page) Content() Content {
407 strm := p.V.Key("Contents")
408 var enc TextEncoding = &nopEncoder{}
409
410 var g = gstate{
411 Th: 1,
412 CTM: ident,
413 }
414
415 var text []Text
416 showText := func(s string) {
417 n := 0
418 for _, ch := range enc.Decode(s) {
419 Trm := matrix{{g.Tfs * g.Th, 0, 0}, {0, g.Tfs, 0}, {0, g.Trise, 1}}.mul(g.Tm).mul(g.CTM)
420 w0 := g.Tf.Width(int(s[n]))
421 n++
422 if ch != ' ' {
423 f := g.Tf.BaseFont()
424 if i := strings.Index(f, "+"); i >= 0 {
425 f = f[i+1:]
426 }
427 text = append(text, Text{f, Trm[0][0], Trm[2][0], Trm[2][1], w0 / 1000 * Trm[0][0], string(ch)})
428 }
429 tx := w0/1000*g.Tfs + g.Tc
430 if ch == ' ' {
431 tx += g.Tw
432 }
433 tx *= g.Th
434 g.Tm = matrix{{1, 0, 0}, {0, 1, 0}, {tx, 0, 1}}.mul(g.Tm)
435 }
436 }
437
438 var rect []Rect
439 var gstack []gstate
440 Interpret(strm, func(stk *Stack, op string) {
441 n := stk.Len()
442 args := make([]Value, n)
443 for i := n - 1; i >= 0; i-- {
444 args[i] = stk.Pop()
445 }
446 switch op {
447 default:
448 //fmt.Println(op, args)
449 return
450
451 case "cm": // update g.CTM
452 if len(args) != 6 {
453 panic("bad g.Tm")
454 }
455 var m matrix
456 for i := 0; i < 6; i++ {
457 m[i/2][i%2] = args[i].Float64()
458 }
459 m[2][2] = 1
460 g.CTM = m.mul(g.CTM)
461
462 case "gs": // set parameters from graphics state resource
463 gs := p.Resources().Key("ExtGState").Key(args[0].Name())
464 font := gs.Key("Font")
465 if font.Kind() == Array && font.Len() == 2 {
466 //fmt.Println("FONT", font)
467 }
468
469 case "f": // fill
470 case "g": // setgray
471 case "l": // lineto
472 case "m": // moveto
473
474 case "cs": // set colorspace non-stroking
475 case "scn": // set color non-stroking
476
477 case "re": // append rectangle to path
478 if len(args) != 4 {
479 panic("bad re")
480 }
481 x, y, w, h := args[0].Float64(), args[1].Float64(), args[2].Float64(), args[3].Float64()
482 rect = append(rect, Rect{Point{x, y}, Point{x + w, y + h}})
483
484 case "q": // save graphics state
485 gstack = append(gstack, g)
486
487 case "Q": // restore graphics state
488 n := len(gstack) - 1
489 g = gstack[n]
490 gstack = gstack[:n]
491
492 case "BT": // begin text (reset text matrix and line matrix)
493 g.Tm = ident
494 g.Tlm = g.Tm
495
496 case "ET": // end text
497
498 case "T*": // move to start of next line
499 x := matrix{{1, 0, 0}, {0, 1, 0}, {0, -g.Tl, 1}}
500 g.Tlm = x.mul(g.Tlm)
501 g.Tm = g.Tlm
502
503 case "Tc": // set character spacing
504 if len(args) != 1 {
505 panic("bad g.Tc")
506 }
507 g.Tc = args[0].Float64()
508
509 case "TD": // move text position and set leading
510 if len(args) != 2 {
511 panic("bad Td")
512 }
513 g.Tl = -args[1].Float64()
514 fallthrough
515 case "Td": // move text position
516 if len(args) != 2 {
517 panic("bad Td")
518 }
519 tx := args[0].Float64()
520 ty := args[1].Float64()
521 x := matrix{{1, 0, 0}, {0, 1, 0}, {tx, ty, 1}}
522 g.Tlm = x.mul(g.Tlm)
523 g.Tm = g.Tlm
524
525 case "Tf": // set text font and size
526 if len(args) != 2 {
527 panic("bad TL")
528 }
529 f := args[0].Name()
530 g.Tf = p.Font(f)
531 enc = g.Tf.Encoder()
532 if enc == nil {
533 println("no cmap for", f)
534 enc = &nopEncoder{}
535 }
536 g.Tfs = args[1].Float64()
537
538 case "\"": // set spacing, move to next line, and show text
539 if len(args) != 3 {
540 panic("bad \" operator")
541 }
542 g.Tw = args[0].Float64()
543 g.Tc = args[1].Float64()
544 args = args[2:]
545 fallthrough
546 case "'": // move to next line and show text
547 if len(args) != 1 {
548 panic("bad ' operator")
549 }
550 x := matrix{{1, 0, 0}, {0, 1, 0}, {0, -g.Tl, 1}}
551 g.Tlm = x.mul(g.Tlm)
552 g.Tm = g.Tlm
553 fallthrough
554 case "Tj": // show text
555 if len(args) != 1 {
556 panic("bad Tj operator")
557 }
558 showText(args[0].RawString())
559
560 case "TJ": // show text, allowing individual glyph positioning
561 v := args[0]
562 for i := 0; i < v.Len(); i++ {
563 x := v.Index(i)
564 if x.Kind() == String {
565 showText(x.RawString())
566 } else {
567 tx := -x.Float64() / 1000 * g.Tfs * g.Th
568 g.Tm = matrix{{1, 0, 0}, {0, 1, 0}, {tx, 0, 1}}.mul(g.Tm)
569 }
570 }
571
572 case "TL": // set text leading
573 if len(args) != 1 {
574 panic("bad TL")
575 }
576 g.Tl = args[0].Float64()
577
578 case "Tm": // set text matrix and line matrix
579 if len(args) != 6 {
580 panic("bad g.Tm")
581 }
582 var m matrix
583 for i := 0; i < 6; i++ {
584 m[i/2][i%2] = args[i].Float64()
585 }
586 m[2][2] = 1
587 g.Tm = m
588 g.Tlm = m
589
590 case "Tr": // set text rendering mode
591 if len(args) != 1 {
592 panic("bad Tr")
593 }
594 g.Tmode = int(args[0].Int64())
595
596 case "Ts": // set text rise
597 if len(args) != 1 {
598 panic("bad Ts")
599 }
600 g.Trise = args[0].Float64()
601
602 case "Tw": // set word spacing
603 if len(args) != 1 {
604 panic("bad g.Tw")
605 }
606 g.Tw = args[0].Float64()
607
608 case "Tz": // set horizontal text scaling
609 if len(args) != 1 {
610 panic("bad Tz")
611 }
612 g.Th = args[0].Float64() / 100
613 }
614 })
615 return Content{text, rect}
616 }
617
618 // TextVertical implements sort.Interface for sorting
619 // a slice of Text values in vertical order, top to bottom,
620 // and then left to right within a line.
621 type TextVertical []Text
622
623 func (x TextVertical) Len() int { return len(x) }
624 func (x TextVertical) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
625 func (x TextVertical) Less(i, j int) bool {
626 if x[i].Y != x[j].Y {
627 return x[i].Y > x[j].Y
628 }
629 return x[i].X < x[j].X
630 }
631
632 // TextHorizontal implements sort.Interface for sorting
633 // a slice of Text values in horizontal order, left to right,
634 // and then top to bottom within a column.
635 type TextHorizontal []Text
636
637 func (x TextHorizontal) Len() int { return len(x) }
638 func (x TextHorizontal) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
639 func (x TextHorizontal) Less(i, j int) bool {
640 if x[i].X != x[j].X {
641 return x[i].X < x[j].X
642 }
643 return x[i].Y > x[j].Y
644 }
645
646 // An Outline is a tree describing the outline (also known as the table of contents)
647 // of a document.
648 type Outline struct {
649 Title string // title for this element
650 Child []Outline // child elements
651 }
652
653 // Outline returns the document outline.
654 // The Outline returned is the root of the outline tree and typically has no Title itself.
655 // That is, the children of the returned root are the top-level entries in the outline.
656 func (r *Reader) Outline() Outline {
657 return buildOutline(r.Trailer().Key("Root").Key("Outlines"))
658 }
659
660 func buildOutline(entry Value) Outline {
661 var x Outline
662 x.Title = entry.Key("Title").Text()
663 for child := entry.Key("First"); child.Kind() == Dict; child = child.Key("Next") {
664 x.Child = append(x.Child, buildOutline(child))
665 }
666 return x
667 }