document.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  1. package pdf
  2. /*
  3. document.go - Build a PDF from a Docs Document with REAL text.
  4. The layout deliberately mirrors the editor's CSS
  5. (src/web/Office/docs/docs.css) so the exported PDF paginates exactly like
  6. the on-screen page preview:
  7. - HTML whitespace is collapsed the way a browser collapses it (pasted
  8. markup is full of hard-wrapped newlines that must NOT become line
  9. breaks; <pre> keeps them),
  10. - lines are wrapped by a small inline layout engine at the real text
  11. width, with per-run fonts/sizes and CSS line-box heights,
  12. - block margins (headings, lists, tables, ...) collapse like CSS ones,
  13. - a block that would cross the bottom margin moves to the next page as a
  14. whole - the rule the preview's pagination uses - instead of being cut
  15. mid-paragraph by fpdf's automatic page break.
  16. Supported: paragraphs and headings, inline bold/italic/underline/color/
  17. size/font, links (clickable), lists, tables (colgroup widths, cell
  18. shading, rich cell content), inline images, explicit page breaks, page
  19. geometry and header/footer text with optional page numbers. The
  20. headings are the PDF's outline (bookmarks), as in the editor's own
  21. export (docs/docs_pdf.js).
  22. */
  23. import (
  24. "errors"
  25. "math"
  26. "strconv"
  27. "strings"
  28. "github.com/go-pdf/fpdf"
  29. "golang.org/x/net/html"
  30. "imuslab.com/arozos/mod/office/internal/htmlutil"
  31. "imuslab.com/arozos/mod/office/internal/media"
  32. "imuslab.com/arozos/mod/office/model"
  33. )
  34. // metrics taken from docs.css (#editor and friends), in PDF units (mm)
  35. const (
  36. ptToMM = 25.4 / 72.0
  37. docBaseSizePt = 11.0 // #editor font-size
  38. docLineFactor = 1.5 // #editor line-height
  39. // Arial hhea metrics per em - only used to place the baseline inside a
  40. // line box, never to size it (CSS line-height rules that)
  41. fontAscentEm = 0.905
  42. fontDescentEm = 0.212
  43. )
  44. // pdfRun is one drawable piece of a laid-out line
  45. type pdfRun struct {
  46. text string // already cp1252-translated
  47. w float64 // mm
  48. sizePt float64
  49. family string // fpdf core family: Arial / Times / Courier
  50. style string // fpdf style string (B / I / U combos)
  51. color string
  52. hl string // highlight (background) color
  53. link string
  54. strike bool
  55. space bool // collapsible space run (dropped at a line break)
  56. img *pdfImg
  57. }
  58. // pdfImg is a registered image placed inline
  59. type pdfImg struct {
  60. name string
  61. wmm, hmm float64
  62. }
  63. // pdfLine is one laid-out line box
  64. type pdfLine struct {
  65. runs []pdfRun
  66. h float64 // line box height
  67. ascent float64 // baseline offset from the top of the line box
  68. w float64 // used width (trailing spaces excluded)
  69. spaces int // space runs available for justification
  70. last bool // last line of its paragraph (never justified)
  71. }
  72. // pdfItem is one vertically stacked, page-breakable piece of the document
  73. // (a line, a table row, a rule, a margin, ...). draw renders it with its top
  74. // edge at y; x is baked in when the item is built.
  75. type pdfItem struct {
  76. h float64
  77. draw func(y float64)
  78. brk bool // explicit page break
  79. }
  80. type docPdf struct {
  81. pdf *fpdf.Fpdf
  82. tr func(string) string
  83. imgSeq int
  84. textW float64 // usable text width in mm
  85. topY float64 // first usable y on a page
  86. botY float64 // last usable y on a page
  87. pre bool // inside <pre>: preserve whitespace
  88. // heading levels of the outline entries a new one may nest under,
  89. // outermost first
  90. outline []int
  91. }
  92. // BuildDoc renders a Document into PDF bytes
  93. func BuildDoc(doc *model.Document) ([]byte, error) {
  94. // page geometry
  95. wMM, hMM := 210.0, 297.0
  96. mT, mR, mB, mL := 25.4, 25.4, 25.4, 25.4
  97. if doc.Page != nil {
  98. if dim, ok := model.PageSizesMM[doc.Page.Size]; ok {
  99. wMM, hMM = dim[0], dim[1]
  100. }
  101. if doc.Page.Orientation == "landscape" {
  102. wMM, hMM = hMM, wMM
  103. }
  104. if doc.Page.Margins != nil {
  105. mT, mR, mB, mL = doc.Page.Margins.Top, doc.Page.Margins.Right,
  106. doc.Page.Margins.Bottom, doc.Page.Margins.Left
  107. }
  108. }
  109. // dims already swapped for landscape above, so always pass "P"
  110. // (fpdf would swap Wd/Ht again on "L")
  111. pdf := fpdf.NewCustom(&fpdf.InitType{
  112. OrientationStr: "P", UnitStr: "mm",
  113. Size: fpdf.SizeType{Wd: wMM, Ht: hMM},
  114. })
  115. b := &docPdf{pdf: pdf, tr: pdfTr(pdf), textW: wMM - mL - mR,
  116. topY: mT, botY: hMM - mB}
  117. pdf.SetMargins(mL, mT, mR)
  118. // the browser wraps text at the content edge - fpdf's default 1mm cell
  119. // margin would wrap it one millimetre early on both sides
  120. pdf.SetCellMargin(0)
  121. // pagination is done here (block by block, like the preview), not by
  122. // fpdf's line-level automatic break
  123. pdf.SetAutoPageBreak(false, mB)
  124. // header / footer text repeats on every page, minus whatever hfMode
  125. // suppresses (see model.HFOnPage); the page counter is its own option
  126. header := strings.TrimSpace(doc.Header)
  127. footer := strings.TrimSpace(doc.Footer)
  128. if doc.HFMode == model.HFModeNone {
  129. header, footer = "", ""
  130. }
  131. if header != "" {
  132. pdf.SetHeaderFuncMode(func() {
  133. if !model.HFOnPage(doc.HFMode, pdf.PageNo()) {
  134. return
  135. }
  136. pdf.SetFont("Arial", "", 9)
  137. pdf.SetTextColor(107, 112, 120)
  138. pdf.SetXY(mL, mT-8)
  139. pdf.CellFormat(b.textW, 4, b.tr(header), "", 0, "L", false, 0, "")
  140. pdf.SetXY(mL, mT)
  141. }, true)
  142. }
  143. if footer != "" || doc.PageNumbers {
  144. pdf.SetFooterFunc(func() {
  145. page := pdf.PageNo()
  146. txt := ""
  147. if model.HFOnPage(doc.HFMode, page) {
  148. txt = footer
  149. }
  150. if model.HFPageNumberOn(doc, page) {
  151. if txt != "" {
  152. txt += " - "
  153. }
  154. txt += strconv.Itoa(page)
  155. }
  156. if txt == "" {
  157. return
  158. }
  159. pdf.SetFont("Arial", "", 9)
  160. pdf.SetTextColor(107, 112, 120)
  161. pdf.SetXY(mL, hMM-mB+3)
  162. pdf.CellFormat(b.textW, 4, b.tr(txt), "", 0, "L", false, 0, "")
  163. })
  164. }
  165. pdf.AddPage()
  166. root, err := html.Parse(strings.NewReader("<body>" + doc.HTML + "</body>"))
  167. if err != nil {
  168. return nil, err
  169. }
  170. var bodyNode *html.Node
  171. var find func(n *html.Node)
  172. find = func(n *html.Node) {
  173. if n.Type == html.ElementNode && n.Data == "body" {
  174. bodyNode = n
  175. return
  176. }
  177. for c := n.FirstChild; c != nil && bodyNode == nil; c = c.NextSibling {
  178. find(c)
  179. }
  180. }
  181. find(root)
  182. if bodyNode == nil {
  183. return nil, errors.New("no document content")
  184. }
  185. // top level: every block is placed as one unit, exactly like the
  186. // preview moves a whole block onto the next sheet
  187. pending := 0.0
  188. for _, box := range b.boxes(bodyNode, mL, b.textW, pdfSeg{sizePt: docBaseSizePt}) {
  189. b.place(math.Max(pending, box.mt), box.items)
  190. pending = box.mb
  191. }
  192. if pdf.Err() {
  193. return nil, pdf.Error()
  194. }
  195. return pdfOutput(pdf)
  196. }
  197. /* ---------------------------------------------------------------- pagination */
  198. // place emits one block: the collapsed margin above it, then its items. The
  199. // whole block moves to the next page when it does not fit on the rest of this
  200. // one (and would fit on an empty page) - the preview's rule.
  201. func (d *docPdf) place(gap float64, items []pdfItem) {
  202. total := 0.0
  203. for _, it := range items {
  204. total += it.h
  205. }
  206. y := d.pdf.GetY() + gap
  207. if y+total > d.botY && total <= d.botY-d.topY && d.pdf.GetY() > d.topY {
  208. d.pdf.AddPage()
  209. y = d.topY + gap // the margin applies again below the break
  210. }
  211. for _, it := range items {
  212. if it.brk {
  213. d.pdf.AddPage()
  214. y = d.topY
  215. continue
  216. }
  217. // blocks taller than a page still break line by line
  218. if y+it.h > d.botY && y > d.topY {
  219. d.pdf.AddPage()
  220. y = d.topY
  221. }
  222. if it.draw != nil {
  223. it.draw(y)
  224. }
  225. y += it.h
  226. }
  227. d.pdf.SetY(y)
  228. }
  229. /* -------------------------------------------------------------- block layout */
  230. // pdfBox is one laid-out block with the CSS margins around it
  231. type pdfBox struct {
  232. items []pdfItem
  233. mt, mb float64
  234. }
  235. // boxes lays out the children of n: every block element becomes a box, and
  236. // runs of inline content between them become anonymous paragraphs, exactly
  237. // like a browser builds anonymous block boxes
  238. func (d *docPdf) boxes(n *html.Node, x, w float64, base pdfSeg) []pdfBox {
  239. var out []pdfBox
  240. var inline []*html.Node
  241. flushInline := func() {
  242. if len(inline) == 0 {
  243. return
  244. }
  245. lines := d.linesOf(d.segsOf(inline, base), w, base, docLineFactor)
  246. out = append(out, pdfBox{items: d.lineItems(lines, x, w, "")})
  247. inline = nil
  248. }
  249. for c := n.FirstChild; c != nil; c = c.NextSibling {
  250. switch {
  251. case c.Type == html.TextNode:
  252. if len(inline) == 0 && strings.TrimSpace(c.Data) == "" {
  253. continue // whitespace between blocks is not content
  254. }
  255. inline = append(inline, c)
  256. case c.Type != html.ElementNode:
  257. continue
  258. case htmlutil.BlockTags[c.Data]:
  259. flushInline()
  260. items, mt, mb := d.blockBox(c, x, w)
  261. out = append(out, pdfBox{items: items, mt: mt, mb: mb})
  262. default:
  263. inline = append(inline, c)
  264. }
  265. }
  266. flushInline()
  267. return out
  268. }
  269. // flow stacks the child boxes of n, collapsing the margins between them.
  270. // When n establishes a block formatting context (a table cell, a padded
  271. // quote, a list item) the outermost margins stay inside it; otherwise they
  272. // collapse through its edges and are returned to the caller instead.
  273. func (d *docPdf) flow(n *html.Node, x, w float64, base pdfSeg, bfc bool) ([]pdfItem, float64, float64) {
  274. var out []pdfItem
  275. mt, pending := 0.0, 0.0
  276. for i, bx := range d.boxes(n, x, w, base) {
  277. gap := bx.mt
  278. if i > 0 {
  279. gap = math.Max(pending, bx.mt)
  280. } else if !bfc {
  281. mt = gap
  282. gap = 0
  283. }
  284. if gap > 0 {
  285. out = append(out, pdfItem{h: gap})
  286. }
  287. out = append(out, bx.items...)
  288. pending = bx.mb
  289. }
  290. if !bfc {
  291. return out, mt, pending
  292. }
  293. if pending > 0 {
  294. out = append(out, pdfItem{h: pending})
  295. }
  296. return out, 0, 0
  297. }
  298. // blockBox lays out one block element into items plus its CSS margins
  299. func (d *docPdf) blockBox(n *html.Node, x, w float64) ([]pdfItem, float64, float64) {
  300. class := " " + htmlutil.Attr(n, "class") + " "
  301. if strings.Contains(class, " doc-pagebreak ") {
  302. return []pdfItem{{brk: true}}, 0, 0
  303. }
  304. switch n.Data {
  305. case "h1", "h2", "h3", "h4", "h5", "h6":
  306. sizes := map[string]float64{"h1": 20, "h2": 16, "h3": 13, "h4": 11, "h5": 11, "h6": 10}
  307. base := pdfSeg{b: true, i: n.Data == "h4", sizePt: sizes[n.Data]}
  308. mt, mb := 14*ptToMM, 6*ptToMM
  309. factor := 1.25
  310. title := strings.Contains(class, " doc-title ")
  311. if title {
  312. // .doc-title: 26pt, regular weight, margin 0 0 12pt
  313. base = pdfSeg{sizePt: 26}
  314. mt, mb = 0, 12*ptToMM
  315. }
  316. items := d.paraItems(n, x, w, base, factor)
  317. if !title {
  318. d.bookmark(items, n, int(n.Data[1]-'0'))
  319. }
  320. return items, mt, mb
  321. case "ul", "ol":
  322. return d.listItems(n, x, w, n.Data == "ol")
  323. case "table":
  324. return d.tableItems(n, x, w), 8 * ptToMM, 8 * ptToMM
  325. case "pre":
  326. return d.preItems(n, x, w), 8 * ptToMM, 8 * ptToMM
  327. case "blockquote":
  328. // border-left 3px + padding 2pt 0 2pt 12px
  329. indent := 15 * pxToMM
  330. items := d.container(n, x+indent, w-indent, pdfSeg{i: true, sizePt: docBaseSizePt})
  331. pad := 2 * ptToMM
  332. var out []pdfItem
  333. out = append(out, pdfItem{h: pad})
  334. out = append(out, items...)
  335. out = append(out, pdfItem{h: pad})
  336. total := 0.0
  337. for _, it := range out {
  338. total += it.h
  339. }
  340. bx, bw := x, total
  341. out[0].draw = func(y float64) {
  342. d.pdf.SetDrawColor(195, 199, 204)
  343. d.pdf.SetLineWidth(3 * pxToMM)
  344. d.pdf.Line(bx+1.5*pxToMM, y, bx+1.5*pxToMM, y+bw)
  345. d.pdf.SetLineWidth(0.2)
  346. }
  347. return out, 8 * ptToMM, 8 * ptToMM
  348. case "hr":
  349. h := 14 * ptToMM
  350. line := pdfItem{h: pxToMM, draw: func(y float64) {
  351. d.pdf.SetDrawColor(201, 205, 211)
  352. d.pdf.SetLineWidth(pxToMM)
  353. d.pdf.Line(x, y, x+w, y)
  354. d.pdf.SetLineWidth(0.2)
  355. }}
  356. return []pdfItem{line}, h, h
  357. default:
  358. // a plain wrapper: its children's outer margins collapse through it
  359. return d.containerBox(n, x, w, pdfSeg{sizePt: docBaseSizePt}, false)
  360. }
  361. }
  362. // bookmark makes a heading an entry of the PDF outline, written with its
  363. // first line so it lands on the page the heading does. Entries nest by
  364. // level - a level 3 right after a level 1 goes under the 1 - which also
  365. // keeps fpdf's outline, whose depth may only grow one step at a time, well
  366. // formed. The Title paragraph is no heading, as in the table of contents.
  367. func (d *docPdf) bookmark(items []pdfItem, n *html.Node, level int) {
  368. text := headingText(n)
  369. if text == "" || len(items) == 0 {
  370. return
  371. }
  372. for len(d.outline) > 0 && d.outline[len(d.outline)-1] >= level {
  373. d.outline = d.outline[:len(d.outline)-1]
  374. }
  375. depth := len(d.outline)
  376. d.outline = append(d.outline, level)
  377. title := pdfTextString(text)
  378. draw := items[0].draw
  379. items[0].draw = func(y float64) {
  380. d.pdf.Bookmark(title, depth, y)
  381. if draw != nil {
  382. draw(y)
  383. }
  384. }
  385. }
  386. // headingText is a heading's text on one line, without footnote markers
  387. func headingText(n *html.Node) string {
  388. var sb strings.Builder
  389. var walk func(*html.Node)
  390. walk = func(x *html.Node) {
  391. if x.Type == html.TextNode {
  392. sb.WriteString(x.Data)
  393. return
  394. }
  395. if x.Type == html.ElementNode {
  396. if x.Data == "sup" && strings.Contains(" "+htmlutil.Attr(x, "class")+" ", " doc-fnref ") {
  397. return
  398. }
  399. if x.Data == "br" {
  400. sb.WriteString(" ")
  401. }
  402. }
  403. for c := x.FirstChild; c != nil; c = c.NextSibling {
  404. walk(c)
  405. }
  406. }
  407. walk(n)
  408. text := strings.ReplaceAll(sb.String(), string(rune(0x200B)), "")
  409. return strings.Join(strings.Fields(text), " ")
  410. }
  411. // containerBox renders a wrapper element: its block children when it has
  412. // any, otherwise its inline content as one paragraph
  413. func (d *docPdf) containerBox(n *html.Node, x, w float64, base pdfSeg, bfc bool) ([]pdfItem, float64, float64) {
  414. if htmlutil.HasBlockChild(n) {
  415. return d.flow(n, x, w, base, bfc)
  416. }
  417. return d.paraItems(n, x, w, base, docLineFactor), 0, 0
  418. }
  419. // container is containerBox for the callers that keep every margin inside
  420. func (d *docPdf) container(n *html.Node, x, w float64, base pdfSeg) []pdfItem {
  421. items, _, _ := d.containerBox(n, x, w, base, true)
  422. return items
  423. }
  424. // preItems lays out a <pre> block: Courier 10pt / 1.45 on a light card
  425. func (d *docPdf) preItems(n *html.Node, x, w float64) []pdfItem {
  426. // padding 10px 12px on a 1px bordered card
  427. padV, padH, bw := 10*pxToMM, 12*pxToMM, pxToMM
  428. d.pre = true
  429. base := pdfSeg{sizePt: 10, family: "Courier"}
  430. lines := d.paraLines(n, w-2*(padH+bw), base, 1.45)
  431. d.pre = false
  432. card := func(y, h float64) {
  433. d.pdf.SetFillColor(241, 243, 244)
  434. d.pdf.SetDrawColor(226, 229, 233)
  435. d.pdf.Rect(x, y, w, h, "F")
  436. }
  437. out := []pdfItem{{h: padV + bw, draw: func(y float64) { card(y, padV+bw) }}}
  438. for _, ln := range lines {
  439. l := ln
  440. out = append(out, pdfItem{h: l.h, draw: func(y float64) {
  441. card(y, l.h)
  442. d.drawLine(l, x+padH+bw, y, w-2*(padH+bw), "")
  443. }})
  444. }
  445. out = append(out, pdfItem{h: padV + bw, draw: func(y float64) { card(y, padV+bw) }})
  446. return out
  447. }
  448. // listItems lays out <ul>/<ol>: 28px content indent with a hanging marker,
  449. // 4pt/8pt outer margins and 2pt between items (all collapsed as CSS does)
  450. func (d *docPdf) listItems(n *html.Node, x, w float64, numbered bool) ([]pdfItem, float64, float64) {
  451. indent := 28 * pxToMM
  452. checklist := strings.Contains(" "+htmlutil.Attr(n, "class")+" ", " of-checklist ")
  453. liGap := 2 * ptToMM // li { margin: 2pt 0 } - 3pt on checklists
  454. if checklist {
  455. liGap = 3 * ptToMM
  456. }
  457. var out []pdfItem
  458. idx := 0
  459. for c := n.FirstChild; c != nil; c = c.NextSibling {
  460. if c.Type != html.ElementNode || c.Data != "li" {
  461. continue
  462. }
  463. idx++
  464. base := pdfSeg{sizePt: docBaseSizePt}
  465. done := checklist && strings.Contains(" "+htmlutil.Attr(c, "class")+" ", " checked ")
  466. if done {
  467. // li.checked { text-decoration: line-through; color: #9aa0a6 }
  468. base.strike = true
  469. base.color = "#9aa0a6"
  470. }
  471. items := d.container(c, x+indent, w-indent, base)
  472. if len(items) > 0 {
  473. switch {
  474. case checklist:
  475. d.attachCheckbox(&items[0], x+indent, done)
  476. case numbered:
  477. d.attachMarker(&items[0], d.tr(strconv.Itoa(idx)+"."), x+indent)
  478. default:
  479. d.attachMarker(&items[0], d.tr("•"), x+indent)
  480. }
  481. }
  482. if len(out) > 0 {
  483. out = append(out, pdfItem{h: liGap})
  484. }
  485. out = append(out, items...)
  486. }
  487. return out, math.Max(4*ptToMM, liGap), math.Max(8*ptToMM, liGap)
  488. }
  489. // attachMarker draws a list marker right-aligned just before the first line
  490. // of an item, without disturbing that line's own drawing
  491. func (d *docPdf) attachMarker(it *pdfItem, marker string, contentX float64) {
  492. inner := it.draw
  493. it.draw = func(y float64) {
  494. d.pdf.SetFont("Arial", "", docBaseSizePt)
  495. d.pdf.SetTextColor(31, 35, 40)
  496. w := d.pdf.GetStringWidth(marker)
  497. _, asc := lineMetrics(docBaseSizePt*ptToMM, docLineFactor)
  498. d.pdf.Text(contentX-w-1.5, y+asc, marker)
  499. if inner != nil {
  500. inner(y)
  501. }
  502. }
  503. }
  504. // attachCheckbox draws a checklist item's box (and its tick when done) the
  505. // way the editor's ::before rule paints it - never an emoji glyph
  506. func (d *docPdf) attachCheckbox(it *pdfItem, contentX float64, checked bool) {
  507. inner := it.draw
  508. it.draw = func(y float64) {
  509. pdf := d.pdf
  510. box := 13 * pxToMM
  511. bx := contentX - 22*pxToMM
  512. by := y + 0.22*docBaseSizePt*ptToMM
  513. pdf.SetLineWidth(1.5 * pxToMM)
  514. if checked {
  515. pdf.SetFillColor(26, 115, 232)
  516. pdf.SetDrawColor(26, 115, 232)
  517. } else {
  518. pdf.SetFillColor(255, 255, 255)
  519. pdf.SetDrawColor(138, 143, 152)
  520. }
  521. pdf.RoundedRect(bx, by, box, box, 3*pxToMM, "1234", "FD")
  522. if checked { // tick
  523. pdf.SetDrawColor(255, 255, 255)
  524. pdf.SetLineWidth(1.4 * pxToMM)
  525. pdf.Line(bx+box*0.25, by+box*0.52, bx+box*0.43, by+box*0.72)
  526. pdf.Line(bx+box*0.43, by+box*0.72, bx+box*0.76, by+box*0.28)
  527. }
  528. pdf.SetLineWidth(0.2)
  529. if inner != nil {
  530. inner(y)
  531. }
  532. }
  533. }
  534. // lineItems turns laid-out lines into page items
  535. func (d *docPdf) lineItems(lines []pdfLine, x, w float64, align string) []pdfItem {
  536. out := make([]pdfItem, 0, len(lines))
  537. for _, ln := range lines {
  538. l := ln
  539. out = append(out, pdfItem{h: l.h, draw: func(y float64) {
  540. d.drawLine(l, x, y, w, align)
  541. }})
  542. }
  543. return out
  544. }
  545. // paraItems lays out one paragraph and wraps its lines into page items
  546. func (d *docPdf) paraItems(n *html.Node, x, w float64, base pdfSeg, factor float64) []pdfItem {
  547. if lh := htmlutil.StyleProp(htmlutil.Attr(n, "style"), "line-height"); lh != "" {
  548. if v, err := strconv.ParseFloat(strings.TrimSuffix(lh, "px"), 64); err == nil && v > 0 && v < 5 {
  549. factor = v
  550. }
  551. }
  552. align := ""
  553. switch htmlutil.StyleProp(htmlutil.Attr(n, "style"), "text-align") {
  554. case "center":
  555. align = "C"
  556. case "right":
  557. align = "R"
  558. case "justify":
  559. align = "J"
  560. }
  561. return d.lineItems(d.paraLines(n, w, base, factor), x, w, align)
  562. }
  563. /* ------------------------------------------------------------ inline layout */
  564. // pdfSeg is one styled run of inline content before line breaking
  565. type pdfSeg struct {
  566. text string
  567. b, i, u bool
  568. strike bool
  569. family string
  570. color string
  571. hl string // text highlight (background) color
  572. sizePt float64
  573. link string
  574. img *html.Node // inline image instead of text
  575. brk bool // <br>
  576. }
  577. func (s pdfSeg) fontStyle() string { return pdfStyleStr(s.b, s.i, s.u) }
  578. func (s pdfSeg) fontFamily() string {
  579. if s.family != "" {
  580. return s.family
  581. }
  582. return "Arial"
  583. }
  584. // collapseWS folds every run of HTML whitespace into a single space, the way
  585. // a browser does. Without it the hard newlines that pasted markup is full of
  586. // would each become a real line break in the PDF.
  587. func collapseWS(s string) string {
  588. var sb strings.Builder
  589. sb.Grow(len(s))
  590. sp := false
  591. for i := 0; i < len(s); i++ {
  592. switch s[i] {
  593. case ' ', '\t', '\n', '\r', '\f', '\v':
  594. sp = true
  595. default:
  596. if sp {
  597. // a leading space is kept here and collapsed away later,
  598. // when it lands at the start of a line
  599. sb.WriteByte(' ')
  600. }
  601. sp = false
  602. sb.WriteByte(s[i])
  603. }
  604. }
  605. if sp {
  606. sb.WriteByte(' ')
  607. }
  608. return sb.String()
  609. }
  610. // cssFontFamily maps a CSS font stack onto the PDF core font that is closest
  611. func cssFontFamily(f string) string {
  612. f = strings.ToLower(f)
  613. switch {
  614. case f == "":
  615. return ""
  616. case strings.Contains(f, "courier"), strings.Contains(f, "consolas"),
  617. strings.Contains(f, "mono"):
  618. return "Courier"
  619. case strings.Contains(f, "times"), strings.Contains(f, "georgia"),
  620. strings.Contains(f, "serif") && !strings.Contains(f, "sans-serif"):
  621. return "Times"
  622. }
  623. return "Arial"
  624. }
  625. // collectSegs flattens the inline content of n into styled runs
  626. func (d *docPdf) collectSegs(n *html.Node, cur pdfSeg, out *[]pdfSeg) {
  627. for c := n.FirstChild; c != nil; c = c.NextSibling {
  628. d.collectNode(c, cur, out)
  629. }
  630. }
  631. // segsOf flattens a list of sibling inline nodes (an anonymous block)
  632. func (d *docPdf) segsOf(nodes []*html.Node, base pdfSeg) []pdfSeg {
  633. var out []pdfSeg
  634. for _, n := range nodes {
  635. d.collectNode(n, base, &out)
  636. }
  637. return out
  638. }
  639. func (d *docPdf) collectNode(c *html.Node, cur pdfSeg, out *[]pdfSeg) {
  640. if c.Type == html.TextNode {
  641. txt := c.Data
  642. if !d.pre {
  643. txt = collapseWS(txt)
  644. }
  645. if txt != "" {
  646. seg := cur
  647. seg.text = txt
  648. *out = append(*out, seg)
  649. }
  650. return
  651. }
  652. if c.Type != html.ElementNode {
  653. return
  654. }
  655. if c.Data == "br" {
  656. seg := cur
  657. seg.brk = true
  658. *out = append(*out, seg)
  659. return
  660. }
  661. if c.Data == "img" {
  662. *out = append(*out, pdfSeg{img: c, sizePt: cur.sizePt})
  663. return
  664. }
  665. cf := cur
  666. st := htmlutil.Attr(c, "style")
  667. switch c.Data {
  668. case "b", "strong":
  669. cf.b = true
  670. case "i", "em":
  671. cf.i = true
  672. case "u", "ins":
  673. cf.u = true
  674. case "s", "strike", "del":
  675. cf.strike = true
  676. case "a":
  677. cf.link = htmlutil.Attr(c, "href")
  678. cf.color = "#1a58c2"
  679. cf.u = true
  680. case "font":
  681. if col := htmlutil.Attr(c, "color"); col != "" {
  682. cf.color = col
  683. }
  684. if fam := cssFontFamily(htmlutil.Attr(c, "face")); fam != "" {
  685. cf.family = fam
  686. }
  687. case "mark":
  688. cf.hl = "#ffff00"
  689. }
  690. if col := htmlutil.StyleProp(st, "color"); col != "" {
  691. cf.color = col
  692. }
  693. if bgc := htmlutil.StyleProp(st, "background-color"); bgc != "" {
  694. cf.hl = bgc
  695. }
  696. if fam := cssFontFamily(htmlutil.StyleProp(st, "font-family")); fam != "" {
  697. cf.family = fam
  698. }
  699. if fw := htmlutil.StyleProp(st, "font-weight"); fw == "700" || fw == "bold" || fw == "600" {
  700. cf.b = true
  701. }
  702. if htmlutil.StyleProp(st, "font-style") == "italic" {
  703. cf.i = true
  704. }
  705. if fs := htmlutil.StyleProp(st, "font-size"); strings.HasSuffix(fs, "px") {
  706. if v, err := strconv.ParseFloat(strings.TrimSuffix(fs, "px"), 64); err == nil && v > 0 {
  707. cf.sizePt = v * 72.0 / 96.0
  708. }
  709. } else if strings.HasSuffix(fs, "pt") {
  710. if v, err := strconv.ParseFloat(strings.TrimSuffix(fs, "pt"), 64); err == nil && v > 0 {
  711. cf.sizePt = v
  712. }
  713. }
  714. if td := htmlutil.StyleProp(st, "text-decoration"); td != "" {
  715. if strings.Contains(td, "underline") {
  716. cf.u = true
  717. }
  718. if strings.Contains(td, "line-through") {
  719. cf.strike = true
  720. }
  721. }
  722. d.collectSegs(c, cf, out)
  723. }
  724. // lineMetrics returns the line-box height and baseline offset of one run
  725. func lineMetrics(sizeMM, factor float64) (h, ascent float64) {
  726. h = sizeMM * factor
  727. ascent = (h-(fontAscentEm+fontDescentEm)*sizeMM)/2 + fontAscentEm*sizeMM
  728. return
  729. }
  730. // paraLines collects the inline content of n and breaks it into lines that
  731. // fit availW, the way the browser's line breaker does
  732. func (d *docPdf) paraLines(n *html.Node, availW float64, base pdfSeg, factor float64) []pdfLine {
  733. if base.sizePt <= 0 {
  734. base.sizePt = docBaseSizePt
  735. }
  736. var segs []pdfSeg
  737. d.collectSegs(n, base, &segs)
  738. return d.linesOf(segs, availW, base, factor)
  739. }
  740. // linesOf breaks collected segments into lines, applying the two browser
  741. // rules for near-empty blocks: a block with no content at all has no line
  742. // box (height 0), while a lone or trailing <br> still leaves one empty line
  743. func (d *docPdf) linesOf(segs []pdfSeg, availW float64, base pdfSeg, factor float64) []pdfLine {
  744. content := false
  745. for _, s := range segs {
  746. if s.img != nil || s.brk || strings.TrimSpace(s.text) != "" {
  747. content = true
  748. break
  749. }
  750. }
  751. if !content {
  752. return nil
  753. }
  754. // a <br> at the very end of a block adds no line in a browser
  755. for len(segs) > 0 && segs[len(segs)-1].brk {
  756. segs = segs[:len(segs)-1]
  757. }
  758. return d.layoutSegs(segs, availW, base, factor)
  759. }
  760. func (d *docPdf) layoutSegs(segs []pdfSeg, availW float64, base pdfSeg, factor float64) []pdfLine {
  761. baseH, baseAsc := lineMetrics(base.sizePt*ptToMM, factor)
  762. if availW < 1 {
  763. availW = 1
  764. }
  765. var lines []pdfLine
  766. cur := pdfLine{h: baseH, ascent: baseAsc}
  767. used := 0.0 // width including any trailing spaces
  768. grow := func(r pdfRun) {
  769. var h, asc float64
  770. if r.img != nil {
  771. h, asc = r.img.hmm, r.img.hmm
  772. } else {
  773. h, asc = lineMetrics(r.sizePt*ptToMM, factor)
  774. }
  775. desc := math.Max(cur.h-cur.ascent, h-asc)
  776. cur.ascent = math.Max(cur.ascent, asc)
  777. cur.h = cur.ascent + desc
  778. }
  779. flush := func(last bool) {
  780. // trailing spaces do not occupy the end of a line
  781. for len(cur.runs) > 0 && cur.runs[len(cur.runs)-1].space {
  782. cur.runs = cur.runs[:len(cur.runs)-1]
  783. }
  784. cur.w = 0
  785. cur.spaces = 0
  786. for i, r := range cur.runs {
  787. cur.w += r.w
  788. if r.space && i < len(cur.runs)-1 {
  789. cur.spaces++
  790. }
  791. }
  792. cur.last = last
  793. lines = append(lines, cur)
  794. cur = pdfLine{h: baseH, ascent: baseAsc}
  795. used = 0
  796. }
  797. add := func(r pdfRun) {
  798. cur.runs = append(cur.runs, r)
  799. used += r.w
  800. grow(r)
  801. }
  802. for _, s := range segs {
  803. if s.brk {
  804. flush(true)
  805. continue
  806. }
  807. if s.img != nil {
  808. img := d.inlineImage(s.img, availW)
  809. if img == nil {
  810. continue
  811. }
  812. if used+img.wmm > availW+0.01 && len(cur.runs) > 0 {
  813. flush(false)
  814. }
  815. add(pdfRun{img: img, w: img.wmm, sizePt: base.sizePt,
  816. family: base.fontFamily()})
  817. continue
  818. }
  819. sizePt := s.sizePt
  820. if sizePt <= 0 {
  821. sizePt = base.sizePt
  822. }
  823. family, style := s.fontFamily(), s.fontStyle()
  824. d.pdf.SetFont(family, style, sizePt)
  825. parts := strings.Split(d.tr(s.text), "\n") // \n only survives in <pre>
  826. for li, part := range parts {
  827. if li > 0 {
  828. flush(true)
  829. }
  830. for _, tok := range splitTokens(part, d.pre) {
  831. isSpace := strings.TrimLeft(tok, " ") == ""
  832. if isSpace && len(cur.runs) == 0 {
  833. continue // whitespace at the start of a line collapses away
  834. }
  835. w := d.pdf.GetStringWidth(tok)
  836. if !isSpace && used+w > availW+0.01 && len(cur.runs) > 0 {
  837. flush(false)
  838. }
  839. if !isSpace && w > availW {
  840. // a single word wider than the line (word-wrap: break-word)
  841. for _, piece := range d.breakWord(tok, availW, &used) {
  842. if piece.brk {
  843. flush(false)
  844. continue
  845. }
  846. add(pdfRun{text: piece.text, w: piece.w, sizePt: sizePt,
  847. family: family, style: style, color: s.color,
  848. hl: s.hl, link: s.link, strike: s.strike})
  849. }
  850. continue
  851. }
  852. add(pdfRun{text: tok, w: w, sizePt: sizePt, family: family,
  853. style: style, color: s.color, hl: s.hl, link: s.link,
  854. strike: s.strike, space: isSpace})
  855. }
  856. }
  857. }
  858. flush(true)
  859. return lines
  860. }
  861. // splitTokens cuts text into wrap tokens: words and the single spaces that
  862. // separate them (inside <pre>, runs of spaces are kept as one token)
  863. func splitTokens(s string, pre bool) []string {
  864. var out []string
  865. i := 0
  866. for i < len(s) {
  867. j := i
  868. if s[i] == ' ' {
  869. for j < len(s) && s[j] == ' ' {
  870. j++
  871. }
  872. if !pre {
  873. for ; i < j; i++ {
  874. out = append(out, " ")
  875. }
  876. continue
  877. }
  878. } else {
  879. for j < len(s) && s[j] != ' ' {
  880. j++
  881. }
  882. }
  883. out = append(out, s[i:j])
  884. i = j
  885. }
  886. return out
  887. }
  888. type wordPiece struct {
  889. text string
  890. w float64
  891. brk bool
  892. }
  893. // breakWord splits a word that cannot fit on one line into line-sized pieces
  894. func (d *docPdf) breakWord(tok string, availW float64, used *float64) []wordPiece {
  895. var out []wordPiece
  896. start, w := 0, 0.0
  897. for i := 0; i < len(tok); i++ {
  898. cw := d.pdf.GetStringWidth(tok[i : i+1])
  899. if w+cw > availW-*used && i > start {
  900. out = append(out, wordPiece{text: tok[start:i], w: w})
  901. out = append(out, wordPiece{brk: true})
  902. start, w = i, 0
  903. *used = 0
  904. }
  905. w += cw
  906. }
  907. if start < len(tok) {
  908. out = append(out, wordPiece{text: tok[start:], w: w})
  909. }
  910. return out
  911. }
  912. // inlineImage registers an image and returns its placed size
  913. func (d *docPdf) inlineImage(n *html.Node, availW float64) *pdfImg {
  914. src := htmlutil.Attr(n, "src")
  915. name, _, ok := pdfImageFromDataURL(d.pdf, src, &d.imgSeq)
  916. if !ok {
  917. return nil
  918. }
  919. data, _, _ := media.DecodeDataURL(src)
  920. wPx, hPx := htmlutil.ImageSizePx(n, data)
  921. // #editor img { height: auto } - the stylesheet beats a height attribute,
  922. // so unless the height is pinned inline the aspect ratio rules
  923. if !strings.HasSuffix(htmlutil.StyleProp(htmlutil.Attr(n, "style"), "height"), "px") {
  924. if cfg, _, err := media.ImageConfig(data); err == nil && cfg.Width > 0 {
  925. hPx = wPx * float64(cfg.Height) / float64(cfg.Width)
  926. }
  927. }
  928. wmm, hmm := wPx*pxToMM, hPx*pxToMM
  929. if wmm > availW && wmm > 0 { // #editor img { max-width: 100% }
  930. hmm = hmm * availW / wmm
  931. wmm = availW
  932. }
  933. return &pdfImg{name: name, wmm: wmm, hmm: hmm}
  934. }
  935. /* ---------------------------------------------------------------- rendering */
  936. // drawLine paints one laid-out line with its top edge at y
  937. func (d *docPdf) drawLine(ln pdfLine, x, y, availW float64, align string) {
  938. pdf := d.pdf
  939. extra := 0.0 // per-space padding for justified text
  940. switch align {
  941. case "C":
  942. x += (availW - ln.w) / 2
  943. case "R":
  944. x += availW - ln.w
  945. case "J":
  946. if !ln.last && ln.spaces > 0 && ln.w < availW {
  947. extra = (availW - ln.w) / float64(ln.spaces)
  948. }
  949. }
  950. baseline := y + ln.ascent
  951. // neighbouring runs that share their styling are drawn as one text
  952. // object, so the PDF keeps whole words and sentences intact
  953. for i := 0; i < len(ln.runs); i++ {
  954. r := ln.runs[i]
  955. if r.img != nil {
  956. pdf.ImageOptions(r.img.name, x, baseline-r.img.hmm, r.img.wmm,
  957. r.img.hmm, false, fpdf.ImageOptions{}, 0, "")
  958. x += r.img.wmm
  959. continue
  960. }
  961. txt, w := r.text, r.w
  962. if r.space && extra > 0 && i < len(ln.runs)-1 {
  963. w += extra
  964. } else {
  965. for j := i + 1; j < len(ln.runs); j++ {
  966. nx := ln.runs[j]
  967. if nx.img != nil || !sameStyle(r, nx) ||
  968. (extra > 0 && nx.space && j < len(ln.runs)-1) {
  969. break
  970. }
  971. txt += nx.text
  972. w += nx.w
  973. i = j
  974. }
  975. }
  976. sz := r.sizePt * ptToMM
  977. if r.hl != "" && pdfSetFillHex(pdf, r.hl) {
  978. pdf.Rect(x, baseline-fontAscentEm*sz, w, (fontAscentEm+fontDescentEm)*sz, "F")
  979. }
  980. if strings.TrimSpace(txt) != "" {
  981. pdf.SetFont(r.family, r.style, r.sizePt)
  982. pdfSetTextHex(pdf, r.color, 31, 35, 40)
  983. pdf.Text(x, baseline, txt)
  984. }
  985. if r.strike && strings.TrimSpace(txt) != "" {
  986. pdf.SetLineWidth(math.Max(0.15, sz*0.06))
  987. pdf.Line(x, baseline-sz*0.27, x+w, baseline-sz*0.27)
  988. pdf.SetLineWidth(0.2)
  989. }
  990. if r.link != "" && strings.HasPrefix(r.link, "http") {
  991. pdf.LinkString(x, baseline-fontAscentEm*sz, w,
  992. (fontAscentEm+fontDescentEm)*sz, r.link)
  993. }
  994. x += w
  995. }
  996. }
  997. // sameStyle reports whether two runs can share one text object
  998. func sameStyle(a, b pdfRun) bool {
  999. return a.sizePt == b.sizePt && a.family == b.family && a.style == b.style &&
  1000. a.color == b.color && a.hl == b.hl && a.link == b.link &&
  1001. a.strike == b.strike
  1002. }
  1003. /* -------------------------------------------------------------------- tables */
  1004. // tableItems lays out a table as one item per row (CSS: border-collapse,
  1005. // 1px #b9bec7 borders, 4px/8px cell padding, top aligned cells)
  1006. func (d *docPdf) tableItems(n *html.Node, x, w float64) []pdfItem {
  1007. cols := 0
  1008. var count func(node *html.Node)
  1009. count = func(node *html.Node) {
  1010. for c := node.FirstChild; c != nil && cols == 0; c = c.NextSibling {
  1011. if c.Type != html.ElementNode {
  1012. continue
  1013. }
  1014. switch c.Data {
  1015. case "thead", "tbody", "tfoot":
  1016. count(c)
  1017. case "tr":
  1018. for td := c.FirstChild; td != nil; td = td.NextSibling {
  1019. if td.Type == html.ElementNode && (td.Data == "td" || td.Data == "th") {
  1020. cols++
  1021. }
  1022. }
  1023. }
  1024. }
  1025. }
  1026. count(n)
  1027. if cols == 0 {
  1028. return nil
  1029. }
  1030. pcts := htmlutil.TableColPercents(n, cols)
  1031. tblW := w * htmlutil.TableWidthPct(n) / 100
  1032. widths := make([]float64, cols)
  1033. for i := range widths {
  1034. widths[i] = tblW * pcts[i] / 100
  1035. }
  1036. padV, padH := 4*pxToMM, 8*pxToMM
  1037. bw := pxToMM // collapsed 1px border, shared between neighbouring rows
  1038. var out []pdfItem
  1039. var rows func(node *html.Node)
  1040. rows = func(node *html.Node) {
  1041. for c := node.FirstChild; c != nil; c = c.NextSibling {
  1042. if c.Type != html.ElementNode {
  1043. continue
  1044. }
  1045. switch c.Data {
  1046. case "thead", "tbody", "tfoot":
  1047. rows(c)
  1048. case "tr":
  1049. type cellBox struct {
  1050. items []pdfItem
  1051. x, w float64
  1052. bg string
  1053. h float64
  1054. }
  1055. var cells []cellBox
  1056. cx, ci := x, 0
  1057. rowH := 0.0
  1058. for td := c.FirstChild; td != nil && ci < cols; td = td.NextSibling {
  1059. if td.Type != html.ElementNode || (td.Data != "td" && td.Data != "th") {
  1060. continue
  1061. }
  1062. st := htmlutil.Attr(td, "style")
  1063. base := pdfSeg{sizePt: docBaseSizePt,
  1064. b: td.Data == "th" || htmlutil.StyleProp(st, "font-weight") == "700" ||
  1065. htmlutil.StyleProp(st, "font-weight") == "600" ||
  1066. htmlutil.StyleProp(st, "font-weight") == "bold",
  1067. color: htmlutil.StyleProp(st, "color")}
  1068. bg := htmlutil.StyleProp(st, "background-color")
  1069. if bg == "" && td.Data == "th" {
  1070. bg = "#f1f3f4"
  1071. }
  1072. cw := widths[ci]
  1073. items := d.container(td, cx+padH, cw-2*padH, base)
  1074. h := 2 * padV
  1075. for _, it := range items {
  1076. h += it.h
  1077. }
  1078. cells = append(cells, cellBox{items: items, x: cx, w: cw, bg: bg, h: h})
  1079. rowH = math.Max(rowH, h)
  1080. cx += cw
  1081. ci++
  1082. }
  1083. if len(cells) == 0 {
  1084. continue
  1085. }
  1086. boxes := cells
  1087. h := rowH + bw
  1088. out = append(out, pdfItem{h: h, draw: func(y float64) {
  1089. d.pdf.SetDrawColor(185, 190, 199)
  1090. d.pdf.SetLineWidth(bw)
  1091. for _, cb := range boxes {
  1092. mode := "D"
  1093. if pdfSetFillHex(d.pdf, cb.bg) {
  1094. mode = "FD"
  1095. }
  1096. d.pdf.Rect(cb.x, y, cb.w, h, mode)
  1097. cy := y + bw + padV
  1098. for _, it := range cb.items {
  1099. if it.draw != nil {
  1100. it.draw(cy)
  1101. }
  1102. cy += it.h
  1103. }
  1104. }
  1105. d.pdf.SetLineWidth(0.2)
  1106. }})
  1107. }
  1108. }
  1109. }
  1110. rows(n)
  1111. if len(out) > 0 {
  1112. out = append(out, pdfItem{h: bw}) // the table's own bottom border
  1113. }
  1114. return out
  1115. }