render.go 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  1. package pdfrender
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "image"
  7. "math"
  8. "time"
  9. )
  10. /*
  11. render.go
  12. The content stream interpreter: graphics state, path construction and
  13. painting, clipping, text, colour operators, marked / optional content
  14. and the public Render entry point. Images, forms and annotations are in
  15. xobject.go, shadings and patterns in shading.go.
  16. */
  17. // Options control a render
  18. type Options struct {
  19. //Scale is device pixels per PDF point (1 = 72 dpi)
  20. Scale float64
  21. //Region is the part of the scaled page to draw, in device pixels from
  22. //the top left corner of the page. Empty draws the whole page.
  23. Region image.Rectangle
  24. //Timeout stops a slow render early; what was drawn so far is returned.
  25. //Zero means 20 seconds.
  26. Timeout time.Duration
  27. //NoAnnotations skips annotation appearances (form fields, stamps ...)
  28. NoAnnotations bool
  29. }
  30. // ErrTimeout is returned with a partial image when the render hit its time
  31. // or operation budget
  32. var ErrTimeout = errors.New("pdfrender: render stopped early")
  33. const (
  34. maxOps = 4000000
  35. maxFormDepth = 16
  36. minLineDevice = 0.45 //Thinnest stroke drawn, in device pixels
  37. )
  38. type gstate struct {
  39. ctm matrix
  40. clip *mask
  41. soft *mask
  42. blend int
  43. fillCS, strokeCS colorSpace
  44. fill, stroke []float64
  45. fillPat, strokePat Object
  46. fillRGB, strokeRGB solidPaint
  47. fillNone, strokeNone bool //Separation /None paints nothing
  48. lw, ml float64
  49. lineCap int
  50. lineJoin int
  51. dash []float64
  52. dashPhase float64
  53. fa, sa float64
  54. font *pdfFont
  55. fs float64
  56. tc, tw float64
  57. th float64
  58. tl float64
  59. rise float64
  60. tr int
  61. }
  62. func (g *gstate) clone() *gstate {
  63. c := *g
  64. c.fill = append([]float64{}, g.fill...)
  65. c.stroke = append([]float64{}, g.stroke...)
  66. return &c
  67. }
  68. type renderer struct {
  69. d *Document
  70. cv *canvas
  71. gs *gstate
  72. stack []*gstate
  73. path path
  74. clipOp int //Pending W (1) or W* (2)
  75. tm, tlm matrix
  76. textClip []polyline
  77. inText bool
  78. res Dict
  79. base matrix //Matrix that pattern spaces are relative to
  80. depth int
  81. ops int
  82. deadline time.Time
  83. stopped bool
  84. mcHidden []bool
  85. hidden int
  86. forceColor *solidPaint //Uncoloured patterns and d1 glyphs
  87. formsBusy map[*Stream]bool
  88. shared *renderShared
  89. }
  90. // renderShared is what the renderers of one page (patterns, soft masks)
  91. // share
  92. type renderShared struct {
  93. fonts map[string]*pdfFont
  94. images map[string]*pdfImage
  95. ocOff map[Ref]bool
  96. }
  97. // Render draws page n (0 based)
  98. func (d *Document) Render(n int, opt Options) (img *image.RGBA, err error) {
  99. pg, err := d.Page(n)
  100. if err != nil {
  101. return nil, err
  102. }
  103. scale := opt.Scale
  104. if scale <= 0 || math.IsNaN(scale) {
  105. scale = 1
  106. }
  107. pw, ph := pg.Size()
  108. fullW := int(math.Ceil(pw * scale))
  109. fullH := int(math.Ceil(ph * scale))
  110. region := opt.Region
  111. if region.Empty() {
  112. region = image.Rect(0, 0, fullW, fullH)
  113. }
  114. region = region.Intersect(image.Rect(0, 0, fullW, fullH))
  115. if region.Empty() || int64(region.Dx())*int64(region.Dy()) > 64<<20 {
  116. return nil, errors.New("pdfrender: bad render size")
  117. }
  118. timeout := opt.Timeout
  119. if timeout <= 0 {
  120. timeout = 20 * time.Second
  121. }
  122. //Page space to device space
  123. x0, y0, x1, y1 := pg.CropBox[0], pg.CropBox[1], pg.CropBox[2], pg.CropBox[3]
  124. s := scale
  125. var m matrix
  126. switch pg.Rotate {
  127. case 90:
  128. m = matrix{0, s, s, 0, -y0 * s, -x0 * s}
  129. case 180:
  130. m = matrix{-s, 0, 0, s, x1 * s, -y0 * s}
  131. case 270:
  132. m = matrix{0, -s, -s, 0, y1 * s, x1 * s}
  133. default:
  134. m = matrix{s, 0, 0, -s, -x0 * s, y1 * s}
  135. }
  136. m = m.mul(matrix{1, 0, 0, 1, -float64(region.Min.X), -float64(region.Min.Y)})
  137. cv := newCanvas(region.Dx(), region.Dy(), true)
  138. shared := &renderShared{fonts: map[string]*pdfFont{}, images: map[string]*pdfImage{}, ocOff: d.optionalContentOff()}
  139. r := newRenderer(d, cv, m, shared, time.Now().Add(timeout))
  140. defer func() {
  141. if p := recover(); p != nil {
  142. img = cv.toRGBA()
  143. err = fmt.Errorf("pdfrender: render failed: %v", p)
  144. }
  145. }()
  146. //Clip to the crop box
  147. r.gs.clip = &mask{r: cv.bounds()}
  148. content := d.pageContent(pg)
  149. r.run(content, pg.Resources)
  150. if !opt.NoAnnotations && !r.stopped {
  151. //Annotations start from a clean state, whatever the page left
  152. ops := r.ops
  153. r = newRenderer(d, cv, m, shared, r.deadline)
  154. r.ops = ops
  155. r.gs.clip = &mask{r: cv.bounds()}
  156. r.drawAnnotations(pg)
  157. }
  158. img = cv.toRGBA()
  159. if r.stopped {
  160. return img, ErrTimeout
  161. }
  162. return img, nil
  163. }
  164. func newRenderer(d *Document, cv *canvas, base matrix, shared *renderShared, deadline time.Time) *renderer {
  165. r := &renderer{
  166. d: d,
  167. cv: cv,
  168. base: base,
  169. deadline: deadline,
  170. shared: shared,
  171. formsBusy: map[*Stream]bool{},
  172. }
  173. r.gs = &gstate{
  174. ctm: base,
  175. fillCS: csGray{},
  176. strokeCS: csGray{},
  177. fill: []float64{0},
  178. stroke: []float64{0},
  179. lw: 1,
  180. ml: 10,
  181. fa: 1,
  182. sa: 1,
  183. th: 1,
  184. }
  185. return r
  186. }
  187. // pageContent concatenates the content streams of a page
  188. func (d *Document) pageContent(pg *Page) []byte {
  189. var out []byte
  190. add := func(o Object) {
  191. if s := d.stream(o); s != nil {
  192. if data, err := d.decodeStream(s, 256<<20); err == nil || len(data) > 0 {
  193. out = append(out, data...)
  194. out = append(out, '\n')
  195. }
  196. }
  197. }
  198. switch c := d.resolve(pg.Dict["Contents"]).(type) {
  199. case *Stream:
  200. add(c)
  201. case Array:
  202. for _, e := range c {
  203. add(e)
  204. }
  205. }
  206. return out
  207. }
  208. /*
  209. Optional content
  210. */
  211. func (d *Document) optionalContentOff() map[Ref]bool {
  212. off := map[Ref]bool{}
  213. cat := d.catalog()
  214. ocp := d.dict(cat["OCProperties"])
  215. if ocp == nil {
  216. return off
  217. }
  218. cfg := d.dict(ocp["D"])
  219. if cfg == nil {
  220. return off
  221. }
  222. if d.name(cfg["BaseState"]) == "OFF" {
  223. for _, o := range d.array(ocp["OCGs"]) {
  224. if ref, ok := o.(Ref); ok {
  225. off[ref] = true
  226. }
  227. }
  228. for _, o := range d.array(cfg["ON"]) {
  229. if ref, ok := o.(Ref); ok {
  230. delete(off, ref)
  231. }
  232. }
  233. }
  234. for _, o := range d.array(cfg["OFF"]) {
  235. if ref, ok := o.(Ref); ok {
  236. off[ref] = true
  237. }
  238. }
  239. return off
  240. }
  241. // ocHidden reports whether an optional content group or membership dict
  242. // is switched off
  243. func (r *renderer) ocHidden(o Object) bool {
  244. if len(r.shared.ocOff) == 0 {
  245. return false
  246. }
  247. ref, isRef := o.(Ref)
  248. dict := r.d.dict(o)
  249. if dict == nil {
  250. return false
  251. }
  252. if r.d.name(dict["Type"]) == "OCMD" {
  253. var groups []Object
  254. switch g := r.d.resolve(dict["OCGs"]).(type) {
  255. case Array:
  256. groups = g
  257. case Dict:
  258. groups = []Object{dict["OCGs"]}
  259. }
  260. if len(groups) == 0 {
  261. return false
  262. }
  263. on, offN := 0, 0
  264. for _, g := range groups {
  265. if gr, ok := g.(Ref); ok && r.shared.ocOff[gr] {
  266. offN++
  267. } else {
  268. on++
  269. }
  270. }
  271. switch r.d.name(dict["P"]) {
  272. case "AllOn":
  273. return offN > 0
  274. case "AnyOff":
  275. return offN == 0
  276. case "AllOff":
  277. return on > 0
  278. }
  279. return on == 0
  280. }
  281. return isRef && r.shared.ocOff[ref]
  282. }
  283. /*
  284. Interpreter
  285. */
  286. func (r *renderer) checkBudget() bool {
  287. if r.stopped {
  288. return false
  289. }
  290. r.ops++
  291. if r.ops > maxOps {
  292. r.stopped = true
  293. return false
  294. }
  295. if r.ops%2048 == 0 && time.Now().After(r.deadline) {
  296. r.stopped = true
  297. return false
  298. }
  299. return true
  300. }
  301. // run interprets a content stream with the given resources
  302. func (r *renderer) run(data []byte, res Dict) {
  303. prevRes := r.res
  304. r.res = res
  305. defer func() { r.res = prevRes }()
  306. p := newParser(data)
  307. var operands []Object
  308. for r.checkBudget() {
  309. obj, err := p.parseObject(0)
  310. if err != nil {
  311. if p.lex.pos >= len(p.lex.buf) && len(p.peek) == 0 {
  312. return
  313. }
  314. //Skip the bad token and carry on
  315. operands = operands[:0]
  316. continue
  317. }
  318. kw, ok := obj.(keyword)
  319. if !ok {
  320. if len(operands) < 64 {
  321. operands = append(operands, obj)
  322. }
  323. continue
  324. }
  325. if kw == "BI" {
  326. r.inlineImage(p)
  327. operands = operands[:0]
  328. continue
  329. }
  330. r.exec(string(kw), operands)
  331. operands = operands[:0]
  332. }
  333. }
  334. func numArg(ops []Object, i int) float64 {
  335. if i < 0 || i >= len(ops) {
  336. return 0
  337. }
  338. v, _ := toFloat(ops[i])
  339. if math.IsNaN(v) || math.IsInf(v, 0) {
  340. return 0
  341. }
  342. return v
  343. }
  344. func (r *renderer) numArgs(ops []Object) []float64 {
  345. out := make([]float64, 0, len(ops))
  346. for _, o := range ops {
  347. if v, ok := toFloat(o); ok {
  348. out = append(out, v)
  349. }
  350. }
  351. return out
  352. }
  353. func (r *renderer) exec(op string, ops []Object) {
  354. gs := r.gs
  355. switch op {
  356. //Graphics state
  357. case "q":
  358. if len(r.stack) < 256 {
  359. r.stack = append(r.stack, gs.clone())
  360. }
  361. case "Q":
  362. if len(r.stack) > 0 {
  363. r.gs = r.stack[len(r.stack)-1]
  364. r.stack = r.stack[:len(r.stack)-1]
  365. }
  366. case "cm":
  367. if len(ops) >= 6 {
  368. m := matrix{numArg(ops, 0), numArg(ops, 1), numArg(ops, 2), numArg(ops, 3), numArg(ops, 4), numArg(ops, 5)}
  369. gs.ctm = m.mul(gs.ctm)
  370. }
  371. case "w":
  372. gs.lw = math.Abs(numArg(ops, 0))
  373. case "J":
  374. gs.lineCap = int(numArg(ops, 0))
  375. case "j":
  376. gs.lineJoin = int(numArg(ops, 0))
  377. case "M":
  378. gs.ml = numArg(ops, 0)
  379. case "d":
  380. if len(ops) >= 2 {
  381. if arr, ok := ops[0].(Array); ok {
  382. gs.dash = gs.dash[:0:0]
  383. for _, v := range arr {
  384. if f, ok := toFloat(r.d.resolve(v)); ok {
  385. gs.dash = append(gs.dash, math.Abs(f))
  386. }
  387. }
  388. gs.dashPhase = numArg(ops, 1)
  389. }
  390. }
  391. case "gs":
  392. if len(ops) >= 1 {
  393. if n, ok := ops[0].(Name); ok {
  394. r.setExtGState(r.d.dict(r.d.dict(r.res["ExtGState"])[n]))
  395. }
  396. }
  397. case "ri", "i":
  398. //Path construction
  399. case "m":
  400. r.path.moveTo(numArg(ops, 0), numArg(ops, 1))
  401. case "l":
  402. r.path.lineTo(numArg(ops, 0), numArg(ops, 1))
  403. case "c":
  404. r.path.cubicTo(numArg(ops, 0), numArg(ops, 1), numArg(ops, 2), numArg(ops, 3), numArg(ops, 4), numArg(ops, 5))
  405. case "v":
  406. if cp, ok := r.path.currentPoint(); ok {
  407. r.path.cubicTo(cp.x, cp.y, numArg(ops, 0), numArg(ops, 1), numArg(ops, 2), numArg(ops, 3))
  408. }
  409. case "y":
  410. r.path.cubicTo(numArg(ops, 0), numArg(ops, 1), numArg(ops, 2), numArg(ops, 3), numArg(ops, 2), numArg(ops, 3))
  411. case "h":
  412. r.path.close()
  413. case "re":
  414. x, y, w, h := numArg(ops, 0), numArg(ops, 1), numArg(ops, 2), numArg(ops, 3)
  415. r.path.moveTo(x, y)
  416. r.path.lineTo(x+w, y)
  417. r.path.lineTo(x+w, y+h)
  418. r.path.lineTo(x, y+h)
  419. r.path.close()
  420. //Path painting
  421. case "S":
  422. r.strokePath()
  423. r.endPath()
  424. case "s":
  425. r.path.close()
  426. r.strokePath()
  427. r.endPath()
  428. case "f", "F":
  429. r.fillPath(false)
  430. r.endPath()
  431. case "f*":
  432. r.fillPath(true)
  433. r.endPath()
  434. case "B":
  435. r.fillPath(false)
  436. r.strokePath()
  437. r.endPath()
  438. case "B*":
  439. r.fillPath(true)
  440. r.strokePath()
  441. r.endPath()
  442. case "b":
  443. r.path.close()
  444. r.fillPath(false)
  445. r.strokePath()
  446. r.endPath()
  447. case "b*":
  448. r.path.close()
  449. r.fillPath(true)
  450. r.strokePath()
  451. r.endPath()
  452. case "n":
  453. r.endPath()
  454. case "W":
  455. r.clipOp = 1
  456. case "W*":
  457. r.clipOp = 2
  458. //Colour
  459. case "CS":
  460. if len(ops) >= 1 {
  461. cs := r.d.loadColorSpace(ops[0], r.res, 0)
  462. if cs == nil {
  463. cs = csGray{}
  464. }
  465. gs.strokeCS = cs
  466. gs.stroke = cs.initial()
  467. gs.strokePat = nil
  468. r.updateColor(false)
  469. }
  470. case "cs":
  471. if len(ops) >= 1 {
  472. cs := r.d.loadColorSpace(ops[0], r.res, 0)
  473. if cs == nil {
  474. cs = csGray{}
  475. }
  476. gs.fillCS = cs
  477. gs.fill = cs.initial()
  478. gs.fillPat = nil
  479. r.updateColor(true)
  480. }
  481. case "SC", "SCN":
  482. gs.stroke, gs.strokePat = r.colorOperands(ops, gs.strokeCS)
  483. r.updateColor(false)
  484. case "sc", "scn":
  485. gs.fill, gs.fillPat = r.colorOperands(ops, gs.fillCS)
  486. r.updateColor(true)
  487. case "G":
  488. gs.strokeCS, gs.stroke, gs.strokePat = csGray{}, r.numArgs(ops), nil
  489. r.updateColor(false)
  490. case "g":
  491. gs.fillCS, gs.fill, gs.fillPat = csGray{}, r.numArgs(ops), nil
  492. r.updateColor(true)
  493. case "RG":
  494. gs.strokeCS, gs.stroke, gs.strokePat = csRGB{}, r.numArgs(ops), nil
  495. r.updateColor(false)
  496. case "rg":
  497. gs.fillCS, gs.fill, gs.fillPat = csRGB{}, r.numArgs(ops), nil
  498. r.updateColor(true)
  499. case "K":
  500. gs.strokeCS, gs.stroke, gs.strokePat = csCMYK{}, r.numArgs(ops), nil
  501. r.updateColor(false)
  502. case "k":
  503. gs.fillCS, gs.fill, gs.fillPat = csCMYK{}, r.numArgs(ops), nil
  504. r.updateColor(true)
  505. //Text
  506. case "BT":
  507. r.tm, r.tlm = identity, identity
  508. r.inText = true
  509. r.textClip = nil
  510. case "ET":
  511. r.inText = false
  512. if gs.tr >= 4 && !r.isHidden() {
  513. cov := r.raster(r.textClip, false, r.cv.bounds())
  514. if cov == nil {
  515. cov = &mask{}
  516. }
  517. gs.clip = intersectMasks(gs.clip, cov)
  518. }
  519. r.textClip = nil
  520. case "Tc":
  521. gs.tc = numArg(ops, 0)
  522. case "Tw":
  523. gs.tw = numArg(ops, 0)
  524. case "Tz":
  525. gs.th = numArg(ops, 0) / 100
  526. case "TL":
  527. gs.tl = numArg(ops, 0)
  528. case "Ts":
  529. gs.rise = numArg(ops, 0)
  530. case "Tr":
  531. gs.tr = int(numArg(ops, 0))
  532. case "Tf":
  533. if len(ops) >= 2 {
  534. if n, ok := ops[0].(Name); ok {
  535. gs.font = r.font(n)
  536. }
  537. gs.fs = numArg(ops, 1)
  538. }
  539. case "Td":
  540. r.tlm = matrix{1, 0, 0, 1, numArg(ops, 0), numArg(ops, 1)}.mul(r.tlm)
  541. r.tm = r.tlm
  542. case "TD":
  543. gs.tl = -numArg(ops, 1)
  544. r.tlm = matrix{1, 0, 0, 1, numArg(ops, 0), numArg(ops, 1)}.mul(r.tlm)
  545. r.tm = r.tlm
  546. case "Tm":
  547. if len(ops) >= 6 {
  548. r.tlm = matrix{numArg(ops, 0), numArg(ops, 1), numArg(ops, 2), numArg(ops, 3), numArg(ops, 4), numArg(ops, 5)}
  549. r.tm = r.tlm
  550. }
  551. case "T*":
  552. r.nextLine()
  553. case "Tj":
  554. if len(ops) >= 1 {
  555. if s, ok := ops[len(ops)-1].(String); ok {
  556. r.showText([]byte(s))
  557. }
  558. }
  559. case "'":
  560. r.nextLine()
  561. if len(ops) >= 1 {
  562. if s, ok := ops[len(ops)-1].(String); ok {
  563. r.showText([]byte(s))
  564. }
  565. }
  566. case "\"":
  567. if len(ops) >= 3 {
  568. gs.tw = numArg(ops, 0)
  569. gs.tc = numArg(ops, 1)
  570. r.nextLine()
  571. if s, ok := ops[2].(String); ok {
  572. r.showText([]byte(s))
  573. }
  574. }
  575. case "TJ":
  576. if len(ops) >= 1 {
  577. if arr, ok := ops[len(ops)-1].(Array); ok {
  578. for _, e := range arr {
  579. switch v := e.(type) {
  580. case String:
  581. r.showText([]byte(v))
  582. case int, float64:
  583. f, _ := toFloat(v)
  584. r.textAdjust(f)
  585. }
  586. }
  587. }
  588. }
  589. case "d0", "d1":
  590. //XObjects, shadings, marked content
  591. case "Do":
  592. if len(ops) >= 1 {
  593. if n, ok := ops[0].(Name); ok {
  594. r.doXObject(n)
  595. }
  596. }
  597. case "sh":
  598. if len(ops) >= 1 {
  599. if n, ok := ops[0].(Name); ok && !r.isHidden() {
  600. sh := r.d.resolve(r.d.dict(r.res["Shading"])[n])
  601. r.paintShadingOp(sh)
  602. }
  603. }
  604. case "BMC":
  605. r.pushMC(false)
  606. case "BDC":
  607. hide := false
  608. if len(ops) >= 2 {
  609. if tag, ok := ops[0].(Name); ok && tag == "OC" {
  610. var prop Object
  611. switch v := ops[1].(type) {
  612. case Name:
  613. prop = r.d.dict(r.res["Properties"])[v]
  614. default:
  615. prop = v
  616. }
  617. hide = r.ocHidden(prop)
  618. }
  619. }
  620. r.pushMC(hide)
  621. case "EMC":
  622. if n := len(r.mcHidden); n > 0 {
  623. if r.mcHidden[n-1] {
  624. r.hidden--
  625. }
  626. r.mcHidden = r.mcHidden[:n-1]
  627. }
  628. }
  629. }
  630. func (r *renderer) pushMC(hide bool) {
  631. if len(r.mcHidden) > 1024 {
  632. return
  633. }
  634. r.mcHidden = append(r.mcHidden, hide)
  635. if hide {
  636. r.hidden++
  637. }
  638. }
  639. func (r *renderer) isHidden() bool {
  640. return r.hidden > 0
  641. }
  642. // colorOperands reads sc / scn operands; a trailing name selects a pattern
  643. func (r *renderer) colorOperands(ops []Object, cs colorSpace) ([]float64, Object) {
  644. var pat Object
  645. if len(ops) > 0 {
  646. if n, ok := ops[len(ops)-1].(Name); ok {
  647. pat = r.d.resolve(r.d.dict(r.res["Pattern"])[n])
  648. ops = ops[:len(ops)-1]
  649. }
  650. }
  651. return r.numArgs(ops), pat
  652. }
  653. func (r *renderer) updateColor(fill bool) {
  654. gs := r.gs
  655. cs, comps := gs.strokeCS, gs.stroke
  656. if fill {
  657. cs, comps = gs.fillCS, gs.fill
  658. }
  659. none := false
  660. if t, ok := cs.(*csTint); ok && t.none {
  661. none = true
  662. }
  663. rr, gg, bb := cs.toRGB(comps)
  664. c := solidPaint{float32(rr), float32(gg), float32(bb)}
  665. if fill {
  666. gs.fillRGB, gs.fillNone = c, none
  667. } else {
  668. gs.strokeRGB, gs.strokeNone = c, none
  669. }
  670. }
  671. func (r *renderer) setExtGState(eg Dict) {
  672. if eg == nil {
  673. return
  674. }
  675. d := r.d
  676. gs := r.gs
  677. for k, v := range eg {
  678. switch k {
  679. case "LW":
  680. gs.lw = math.Abs(d.num(v, gs.lw))
  681. case "LC":
  682. gs.lineCap = d.integer(v, gs.lineCap)
  683. case "LJ":
  684. gs.lineJoin = d.integer(v, gs.lineJoin)
  685. case "ML":
  686. gs.ml = d.num(v, gs.ml)
  687. case "D":
  688. arr := d.array(v)
  689. if len(arr) == 2 {
  690. gs.dash = nil
  691. for _, e := range d.array(arr[0]) {
  692. gs.dash = append(gs.dash, math.Abs(d.num(e, 0)))
  693. }
  694. gs.dashPhase = d.num(arr[1], 0)
  695. }
  696. case "CA":
  697. gs.sa = clamp(d.num(v, 1), 0, 1)
  698. case "ca":
  699. gs.fa = clamp(d.num(v, 1), 0, 1)
  700. case "Font":
  701. arr := d.array(v)
  702. if len(arr) == 2 {
  703. gs.font = r.fontFromObject(arr[0])
  704. gs.fs = d.num(arr[1], gs.fs)
  705. }
  706. case "BM":
  707. bm := d.resolve(v)
  708. if a, ok := bm.(Array); ok && len(a) > 0 {
  709. bm = d.resolve(a[0])
  710. }
  711. switch d.name(bm) {
  712. case "Multiply":
  713. gs.blend = blendMultiply
  714. case "Screen":
  715. gs.blend = blendScreen
  716. case "Darken":
  717. gs.blend = blendDarken
  718. case "Lighten":
  719. gs.blend = blendLighten
  720. case "Overlay", "HardLight":
  721. gs.blend = blendOverlay
  722. case "Difference", "Exclusion":
  723. gs.blend = blendDifference
  724. default:
  725. gs.blend = blendNormal
  726. }
  727. case "SMask":
  728. if d.name(v) == "None" {
  729. gs.soft = nil
  730. } else if sm := d.dict(v); sm != nil {
  731. gs.soft = r.softMask(sm)
  732. }
  733. }
  734. }
  735. }
  736. func (r *renderer) font(n Name) *pdfFont {
  737. fonts := r.d.dict(r.res["Font"])
  738. if fonts == nil {
  739. return nil
  740. }
  741. return r.fontFromObject(fonts[n])
  742. }
  743. func (r *renderer) fontFromObject(o Object) *pdfFont {
  744. key := ""
  745. switch v := o.(type) {
  746. case Ref:
  747. key = fmt.Sprintf("r%d.%d", v.Num, v.Gen)
  748. case Dict:
  749. key = fmt.Sprintf("d%p", v)
  750. default:
  751. return nil
  752. }
  753. if f, ok := r.shared.fonts[key]; ok {
  754. return f
  755. }
  756. f := r.d.loadFont(o)
  757. r.shared.fonts[key] = f
  758. return f
  759. }
  760. /*
  761. Painting
  762. */
  763. // raster rasterizes within the render's time budget; running out stops
  764. // the render
  765. func (r *renderer) raster(polys []polyline, evenOdd bool, bounds image.Rectangle) *mask {
  766. if r.stopped {
  767. return nil
  768. }
  769. m, aborted := rasterizeUntil(polys, evenOdd, bounds, r.deadline)
  770. if aborted {
  771. r.stopped = true
  772. }
  773. return m
  774. }
  775. func (r *renderer) endPath() {
  776. if r.clipOp != 0 {
  777. polys := r.path.flatten(r.gs.ctm, 0.3)
  778. cov := r.raster(polys, r.clipOp == 2, r.cv.bounds())
  779. if cov == nil {
  780. cov = &mask{}
  781. }
  782. r.gs.clip = intersectMasks(r.gs.clip, cov)
  783. r.clipOp = 0
  784. }
  785. r.path = path{}
  786. }
  787. func (r *renderer) paintBounds() image.Rectangle {
  788. return r.cv.bounds().Intersect(r.gs.clip.bounds())
  789. }
  790. func (r *renderer) fillPath(evenOdd bool) {
  791. if r.isHidden() || r.path.empty() || r.gs.fillNone {
  792. return
  793. }
  794. polys := r.path.flatten(r.gs.ctm, 0.3)
  795. cov := r.raster(polys, evenOdd, r.paintBounds())
  796. r.paintCoverage(cov, true)
  797. }
  798. // strokeWidth returns the stroke width in user space, widened so the line
  799. // is at least minLineDevice wide on the device
  800. func (r *renderer) strokeWidth(m matrix) float64 {
  801. sc := m.scale()
  802. if sc <= 0 {
  803. return 0
  804. }
  805. lw := r.gs.lw
  806. if lw*sc < minLineDevice {
  807. lw = minLineDevice / sc
  808. }
  809. return lw
  810. }
  811. func (r *renderer) strokePath() {
  812. if r.isHidden() || r.path.empty() || r.gs.strokeNone {
  813. return
  814. }
  815. r.strokeShape(&r.path, identity)
  816. }
  817. // strokeShape strokes a path given in the space pm maps into user space
  818. func (r *renderer) strokeShape(p *path, pm matrix) {
  819. gs := r.gs
  820. ctm := gs.ctm
  821. sc := ctm.scale()
  822. if sc <= 0 || math.IsNaN(sc) {
  823. return
  824. }
  825. lw := r.strokeWidth(ctm)
  826. lines := p.flatten(pm, 0.3/sc)
  827. devRadius := lw * sc / 2
  828. //Drop subpaths that cannot reach the canvas, stroke width included
  829. {
  830. b := r.paintBounds()
  831. kept := lines[:0]
  832. for _, pl := range lines {
  833. lx, ly := math.Inf(1), math.Inf(1)
  834. hx, hy := math.Inf(-1), math.Inf(-1)
  835. for _, pt := range pl.pts {
  836. x, y := ctm.apply(pt.x, pt.y)
  837. lx, ly, hx, hy = math.Min(lx, x), math.Min(ly, y), math.Max(hx, x), math.Max(hy, y)
  838. }
  839. if hx+devRadius >= float64(b.Min.X) && lx-devRadius <= float64(b.Max.X) &&
  840. hy+devRadius >= float64(b.Min.Y) && ly-devRadius <= float64(b.Max.Y) {
  841. kept = append(kept, pl)
  842. }
  843. }
  844. lines = kept
  845. }
  846. segs := int(math.Ceil(devRadius * 2 * math.Pi / 1.5))
  847. if segs > 64 {
  848. segs = 64
  849. }
  850. var dash []float64
  851. if len(gs.dash) > 0 {
  852. total := 0.0
  853. for _, v := range gs.dash {
  854. total += v
  855. }
  856. //Dashes far below a pixel read as a lighter solid line
  857. if total*sc >= 1 {
  858. dash = gs.dash
  859. }
  860. }
  861. outline := strokePolys(lines, strokeStyle{
  862. width: lw,
  863. cap: gs.lineCap,
  864. join: gs.lineJoin,
  865. miterLimit: gs.ml,
  866. dash: dash,
  867. dashPhase: gs.dashPhase,
  868. circleSegs: segs,
  869. devScale: sc,
  870. maxPolys: 300000,
  871. })
  872. if time.Now().After(r.deadline) {
  873. r.stopped = true
  874. return
  875. }
  876. //To device space, dropping the pieces that lie wholly off the canvas
  877. b := r.paintBounds()
  878. minX, minY, maxX, maxY := float64(b.Min.X), float64(b.Min.Y), float64(b.Max.X), float64(b.Max.Y)
  879. kept := outline[:0]
  880. for i := range outline {
  881. lx, ly := math.Inf(1), math.Inf(1)
  882. hx, hy := math.Inf(-1), math.Inf(-1)
  883. for k, pt := range outline[i].pts {
  884. x, y := ctm.apply(pt.x, pt.y)
  885. outline[i].pts[k] = point{x, y}
  886. lx, ly, hx, hy = math.Min(lx, x), math.Min(ly, y), math.Max(hx, x), math.Max(hy, y)
  887. }
  888. if hx >= minX && lx <= maxX && hy >= minY && ly <= maxY {
  889. kept = append(kept, outline[i])
  890. }
  891. }
  892. cov := r.raster(kept, false, b)
  893. r.paintCoverage(cov, false)
  894. }
  895. // paintCoverage composites the current fill or stroke colour (or pattern)
  896. func (r *renderer) paintCoverage(cov *mask, fill bool) {
  897. if cov == nil {
  898. return
  899. }
  900. gs := r.gs
  901. alpha := gs.sa
  902. color := gs.strokeRGB
  903. pat := gs.strokePat
  904. cs := gs.strokeCS
  905. comps := gs.stroke
  906. if fill {
  907. alpha, color, pat, cs, comps = gs.fa, gs.fillRGB, gs.fillPat, gs.fillCS, gs.fill
  908. }
  909. if r.forceColor != nil {
  910. r.cv.composite(cov, gs.clip, gs.soft, *r.forceColor, float32(alpha), gs.blend)
  911. return
  912. }
  913. if pcs, ok := cs.(*csPattern); ok {
  914. if pat == nil {
  915. return
  916. }
  917. var tint *solidPaint
  918. if pcs.base != nil {
  919. rr, gg, bb := pcs.base.toRGB(comps)
  920. tint = &solidPaint{float32(rr), float32(gg), float32(bb)}
  921. }
  922. r.paintPattern(cov, pat, tint, alpha)
  923. return
  924. }
  925. r.cv.composite(cov, gs.clip, gs.soft, color, float32(alpha), gs.blend)
  926. }
  927. /*
  928. Text
  929. */
  930. func (r *renderer) nextLine() {
  931. r.tlm = matrix{1, 0, 0, 1, 0, -r.gs.tl}.mul(r.tlm)
  932. r.tm = r.tlm
  933. }
  934. func (r *renderer) textAdjust(n float64) {
  935. gs := r.gs
  936. if gs.font != nil && gs.font.vertical {
  937. r.tm = matrix{1, 0, 0, 1, 0, -n / 1000 * gs.fs}.mul(r.tm)
  938. return
  939. }
  940. r.tm = matrix{1, 0, 0, 1, -n / 1000 * gs.fs * gs.th, 0}.mul(r.tm)
  941. }
  942. func (r *renderer) showText(s []byte) {
  943. gs := r.gs
  944. f := gs.font
  945. if f == nil {
  946. return
  947. }
  948. visible := gs.tr != 3 && gs.tr != 7 && !r.isHidden()
  949. for _, c := range f.decode(s) {
  950. if !r.checkBudget() {
  951. return
  952. }
  953. w0 := f.advance(c)
  954. space := 0.0
  955. if c.n == 1 && c.code == 32 {
  956. space = gs.tw
  957. }
  958. trm := matrix{gs.fs * gs.th, 0, 0, gs.fs, 0, gs.rise}.mul(r.tm)
  959. var vx, vy, w1 float64
  960. if f.vertical {
  961. w1, vx, vy = f.verticalMetrics(c)
  962. trm = matrix{1, 0, 0, 1, -vx * gs.fs * gs.th, -vy * gs.fs}.mul(trm)
  963. }
  964. if visible && gs.fs != 0 {
  965. if f.kind == fontType3 {
  966. r.drawType3Glyph(f, c, trm)
  967. } else if g := f.outline(c); g != nil && g.p != nil && !g.p.empty() {
  968. r.drawGlyph(g, trm)
  969. }
  970. }
  971. if f.vertical {
  972. ty := w1*gs.fs + gs.tc + space
  973. r.tm = matrix{1, 0, 0, 1, 0, ty}.mul(r.tm)
  974. } else {
  975. tx := (w0*gs.fs + gs.tc + space) * gs.th
  976. r.tm = matrix{1, 0, 0, 1, tx, 0}.mul(r.tm)
  977. }
  978. }
  979. }
  980. func (r *renderer) drawGlyph(g *glyphOutline, trm matrix) {
  981. gs := r.gs
  982. userM := g.m.mul(trm) //Glyph units to user space
  983. devM := userM.mul(gs.ctm) //Glyph units to device
  984. //Skip glyphs far outside the canvas
  985. ox, oy := devM.apply(0, 0)
  986. size := trm.mul(gs.ctm).scale() * 2
  987. b := r.paintBounds()
  988. if ox < float64(b.Min.X)-size || ox > float64(b.Max.X)+size || oy < float64(b.Min.Y)-size || oy > float64(b.Max.Y)+size {
  989. return
  990. }
  991. mode := gs.tr
  992. fill := mode == 0 || mode == 2 || mode == 4 || mode == 6
  993. stroke := mode == 1 || mode == 2 || mode == 5 || mode == 6
  994. if fill && !gs.fillNone {
  995. polys := g.p.flatten(devM, 0.2)
  996. cov := r.raster(polys, false, b)
  997. r.paintCoverage(cov, true)
  998. }
  999. if stroke && !gs.strokeNone {
  1000. r.strokeShape(g.p, userM)
  1001. }
  1002. if mode >= 4 {
  1003. r.textClip = append(r.textClip, g.p.flatten(devM, 0.2)...)
  1004. }
  1005. }
  1006. func (r *renderer) drawType3Glyph(f *pdfFont, c charCode, trm matrix) {
  1007. name := f.names[c.code&0xff]
  1008. if name == "" || f.t3procs == nil || r.depth >= maxFormDepth {
  1009. return
  1010. }
  1011. s := r.d.stream(f.t3procs[Name(name)])
  1012. if s == nil || r.formsBusy[s] {
  1013. return
  1014. }
  1015. data, err := r.d.decodeStream(s, 16<<20)
  1016. if err != nil {
  1017. return
  1018. }
  1019. res := f.t3res
  1020. if res == nil {
  1021. res = r.res
  1022. }
  1023. r.formsBusy[s] = true
  1024. defer delete(r.formsBusy, s)
  1025. saved := r.gs
  1026. savedStack := r.stack
  1027. savedPath := r.path
  1028. savedTm, savedTlm := r.tm, r.tlm
  1029. savedForce := r.forceColor
  1030. //A d1 glyph is a shape only: it is painted in the current fill colour
  1031. head := data
  1032. if len(head) > 256 {
  1033. head = head[:256]
  1034. }
  1035. if bytes.Contains(head, []byte("d1")) && r.forceColor == nil {
  1036. c := saved.fillRGB
  1037. r.forceColor = &c
  1038. }
  1039. defer func() { r.forceColor = savedForce }()
  1040. r.gs = saved.clone()
  1041. r.gs.ctm = f.t3matrix.mul(trm).mul(saved.ctm)
  1042. r.stack = nil
  1043. r.path = path{}
  1044. r.depth++
  1045. r.run(data, res)
  1046. r.depth--
  1047. r.gs = saved
  1048. r.stack = savedStack
  1049. r.path = savedPath
  1050. r.tm, r.tlm = savedTm, savedTlm
  1051. }