docs_pdf.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. /*
  2. ArozOS Office - Docs PDF export
  3. ===============================
  4. The PDF is drawn from the editor's own pages. docs_layout.js has already
  5. decided where every line, row and page break goes, and the sheet the
  6. editor shows is the sheet that gets written: each element in the page
  7. becomes the PDF object it is, at the position the browser gave it.
  8. text real PDF text, one show-text per line fragment at the
  9. browser's baseline (OfficePdfCore.drawRuns - the font rules
  10. are the ones Slides uses: standard PDF fonts for families
  11. metric-identical to them, the shipped Noto faces embedded
  12. and subset for everything else, and a picture only of the
  13. characters nothing can show, in their place in the line)
  14. background a filled rectangle - per line fragment for highlighted text
  15. borders filled strips; a collapsed table rule is centred on the
  16. cell edge the way the browser draws it, at the width the
  17. document states rather than the pixel it was rounded to
  18. pictures the original bytes embedded once, cropped with a clip path
  19. markers list numbers and bullets (li[data-marker]), tab leaders and
  20. the footnote rule, which the editor draws with CSS
  21. generated content and therefore have no text node
  22. Nothing is re-laid out, so the export cannot paginate differently from
  23. the editor. The page is only held while it is measured: what to draw is
  24. written down as a display list, and common/pdfworker.js (pdfdraw.js)
  25. assembles the file in a Web Worker while the document stays editable.
  26. The headings become the PDF's outline (bookmarks), each pointing at the
  27. top of the heading on its sheet.
  28. Usage:
  29. DocsPdf.build({ pageEl, pages, sheetW, sheetH, title, outline,
  30. enter, leave, onProgress }) -> Promise<Uint8Array>
  31. */
  32. var DocsPdf = (function () {
  33. "use strict";
  34. var C = OfficePdfCore;
  35. var parseFill = C.parseFill, parseColor = C.parseColor;
  36. var PT = 96 / 72;
  37. // subtrees that are editor chrome, not page content
  38. var SKIP_SELECTOR = "#pageSheets, .doc-fn-measure, .of-img-handle, .doc-autobreak, .doc-toc-frame";
  39. function skipped(el) {
  40. return !!(el && el.closest && el.closest(SKIP_SELECTOR));
  41. }
  42. /* ---------------- geometry ---------------- */
  43. function Frame(pageEl) {
  44. this.pageEl = pageEl;
  45. var r = pageEl.getBoundingClientRect();
  46. this.left = r.left + pageEl.clientLeft;
  47. this.top = r.top + pageEl.clientTop;
  48. }
  49. // a client rect in #page layout coordinates (px)
  50. Frame.prototype.box = function (rect) {
  51. return {
  52. x: rect.left - this.left, y: rect.top - this.top,
  53. w: rect.right - rect.left, h: rect.bottom - rect.top
  54. };
  55. };
  56. function pageIndexOf(pages, sheetH, y) {
  57. // pages are in order; the last sheet whose top is at or above y
  58. var lo = 0, hi = pages.length - 1, ans = 0;
  59. while (lo <= hi) {
  60. var mid = (lo + hi) >> 1;
  61. if (pages[mid].sheetTop <= y + 0.5) { ans = mid; lo = mid + 1; }
  62. else hi = mid - 1;
  63. }
  64. return ans;
  65. }
  66. // every page a vertical band [y, y+h] touches
  67. function pagesTouched(pages, sheetH, y, h) {
  68. var out = [];
  69. var i = pageIndexOf(pages, sheetH, y);
  70. for (; i < pages.length; i++) {
  71. var top = pages[i].sheetTop;
  72. if (top > y + h) break;
  73. if (top + sheetH > y) out.push(i);
  74. }
  75. return out;
  76. }
  77. /* ---------------- collecting what is on the pages ---------------- */
  78. function collect(o, frame) {
  79. var pages = o.pages, sheetH = o.sheetH;
  80. var perPage = pages.map(function () {
  81. return { fills: [], images: [], borders: [], texts: [], extras: [] };
  82. });
  83. var add = function (kind, y, h, item) {
  84. pagesTouched(pages, sheetH, y, h).forEach(function (i) { perPage[i][kind].push(item); });
  85. };
  86. var all = o.pageEl.getElementsByTagName("*");
  87. for (var i = 0; i < all.length; i++) {
  88. var el = all[i];
  89. if (skipped(el)) continue;
  90. var cs = window.getComputedStyle(el);
  91. if (cs.display === "none" || cs.visibility === "hidden") continue;
  92. if (el.closest("[hidden]")) continue;
  93. var rects;
  94. // backgrounds
  95. var bg = parseFill(cs.backgroundColor);
  96. if (bg && el !== o.pageEl) {
  97. rects = cs.display === "inline" ? el.getClientRects() : [el.getBoundingClientRect()];
  98. for (var r = 0; r < rects.length; r++) {
  99. var b = frame.box(rects[r]);
  100. if (b.w <= 0 || b.h <= 0) continue;
  101. add("fills", b.y, b.h, { box: b, fill: bg });
  102. }
  103. }
  104. // borders (an inline picture is one box, so its outline is drawn
  105. // too; inline text with a border would need a box per line)
  106. if (cs.display !== "inline" || el.tagName === "IMG") {
  107. var bb = frame.box(el.getBoundingClientRect());
  108. var cell = (el.tagName === "TD" || el.tagName === "TH") && cs.borderCollapse === "collapse";
  109. ["Top", "Right", "Bottom", "Left"].forEach(function (side) {
  110. var st = cs["border" + side + "Style"];
  111. var w = parseFloat(cs["border" + side + "Width"]) || 0;
  112. if (!w || st === "none" || st === "hidden") return;
  113. var col = parseFill(cs["border" + side + "Color"]);
  114. if (!col) return;
  115. // the width the document states, before pixel rounding
  116. var declared = el.style["border" + side + "Width"];
  117. if (declared && /pt$/.test(declared)) w = parseFloat(declared) * PT;
  118. add("borders", bb.y - w, bb.h + 2 * w, { box: bb, side: side, w: w, fill: col, centred: cell, dash: st });
  119. });
  120. }
  121. // pictures
  122. if (el.tagName === "IMG") {
  123. var ib = frame.box(el.getBoundingClientRect());
  124. var bl = parseFloat(cs.borderLeftWidth) || 0, bt = parseFloat(cs.borderTopWidth) || 0;
  125. var pl = parseFloat(cs.paddingLeft) || 0, ptp = parseFloat(cs.paddingTop) || 0;
  126. var content = {
  127. x: ib.x + bl + pl, y: ib.y + bt + ptp,
  128. w: el.clientWidth - pl - (parseFloat(cs.paddingRight) || 0),
  129. h: el.clientHeight - ptp - (parseFloat(cs.paddingBottom) || 0)
  130. };
  131. if (content.w > 0 && content.h > 0) {
  132. add("images", content.y, content.h, { box: content, img: el, viewBox: cs.objectViewBox || el.style.objectViewBox ||
  133. el.getAttribute("data-crop") || "" });
  134. }
  135. }
  136. // list markers
  137. if (el.tagName === "LI" && el.hasAttribute("data-marker")) {
  138. var marker = el.getAttribute("data-marker");
  139. if (marker) {
  140. var m = markerItem(el, marker, frame);
  141. if (m) add("extras", m.baseline - m.size, m.size * 1.4, m);
  142. }
  143. }
  144. // tab leaders
  145. if (el.classList.contains("doc-tab") && el.getAttribute("data-leader")) {
  146. var lb = frame.box(el.getBoundingClientRect());
  147. var leader = el.getAttribute("data-leader");
  148. var met = C.fontMetricsOf(cs);
  149. // the tab's own line: its baseline is its box's, set by the text
  150. add("extras", lb.y, lb.h, {
  151. kind: "leader", box: lb,
  152. ch: leader === "hyphen" ? "-" : (leader === "underscore" ? "_" : "."),
  153. names: C.familyList(cs.fontFamily),
  154. size: parseFloat(cs.fontSize) || 14.67,
  155. weight: parseInt(cs.fontWeight, 10) || 400,
  156. bold: (parseInt(cs.fontWeight, 10) || 400) >= 600,
  157. color: parseColor(cs.color) || PDFLib.rgb(0, 0, 0),
  158. baseline: lb.y + (lb.h - (met.ascent + met.descent)) / 2 + met.ascent
  159. });
  160. }
  161. // the footnote separator rule
  162. if (el.classList.contains("doc-fn-sep")) {
  163. var after = window.getComputedStyle(el, "::after");
  164. var sb = frame.box(el.getBoundingClientRect());
  165. var lw = parseFloat(after.borderTopWidth) || 1;
  166. add("extras", sb.y, sb.h, {
  167. kind: "rule",
  168. box: { x: sb.x, y: sb.y + (parseFloat(after.top) || 0), w: parseFloat(after.width) || 192, h: lw },
  169. fill: parseFill(after.borderTopColor) || { c: PDFLib.rgb(0, 0, 0), a: 1 }
  170. });
  171. }
  172. }
  173. // text, as line fragments at their baselines
  174. var origin = { left: frame.left, top: frame.top, x: 0, y: 0 };
  175. var runs = C.collectRuns(o.pageEl, origin).filter(function (run) {
  176. return C.visibleText(run.text).trim() !== "";
  177. });
  178. runs.forEach(function (run) {
  179. var top = run.rect.top - frame.top;
  180. var h = run.rect.bottom - run.rect.top;
  181. var idx = pageIndexOf(pages, sheetH, top + h / 2);
  182. perPage[idx].texts.push(run);
  183. });
  184. return { perPage: perPage, runs: runs };
  185. }
  186. /* A marker is the li's ::before: drawn in its font, hanging to the left
  187. of the item's text and sitting on the item's first baseline. */
  188. function markerItem(li, text, frame) {
  189. var before = window.getComputedStyle(li, "::before");
  190. var size = parseFloat(before.fontSize) || parseFloat(window.getComputedStyle(li).fontSize) || 14.67;
  191. var lr = li.getBoundingClientRect();
  192. var lcs = window.getComputedStyle(li);
  193. var left = lr.left - frame.left + (parseFloat(before.left) || 0);
  194. // the first line's baseline: from the first text in the item, else
  195. // from the item's own line box
  196. var baseline = null;
  197. var walker = document.createTreeWalker(li, NodeFilter.SHOW_TEXT, null);
  198. var n;
  199. while ((n = walker.nextNode())) {
  200. if (!n.nodeValue.trim()) continue;
  201. if (n.parentElement.closest("ol,ul") !== li.parentElement && n.parentElement.closest("li") !== li) continue;
  202. var range = document.createRange();
  203. range.selectNodeContents(n);
  204. var rects = range.getClientRects();
  205. if (!rects.length) continue;
  206. var pcs = window.getComputedStyle(n.parentElement);
  207. var met = C.fontMetricsOf(pcs);
  208. var rh = rects[0].bottom - rects[0].top;
  209. baseline = rects[0].top - frame.top + (rh - (met.ascent + met.descent)) / 2 + met.ascent;
  210. break;
  211. }
  212. if (baseline === null) {
  213. var lm = C.fontMetricsOf(lcs);
  214. var lh = parseFloat(lcs.lineHeight) || size * 1.2;
  215. baseline = lr.top - frame.top + (parseFloat(lcs.paddingTop) || 0) + (lh - (lm.ascent + lm.descent)) / 2 + lm.ascent;
  216. }
  217. return {
  218. kind: "marker", text: text, x: left, baseline: baseline, size: size,
  219. shape: bulletShape(text, before, size, left, baseline),
  220. names: C.familyList(before.fontFamily),
  221. weight: parseInt(before.fontWeight, 10) || 400,
  222. bold: (parseInt(before.fontWeight, 10) || 400) >= 600,
  223. italic: before.fontStyle === "italic",
  224. color: parseColor(before.color) || PDFLib.rgb(0, 0, 0)
  225. };
  226. }
  227. /* A geometric bullet (a disc, a ring, a square) is drawn as the shape
  228. it is, at the ink box the browser gives the glyph. Written as text it
  229. would land in whichever shipped face has the character - for a disc
  230. that is a CJK face, whose full-width disc is twice the size of the
  231. one Arial draws on screen. */
  232. var SHAPES = {
  233. 0x25CF: "disc", 0x2022: "disc", 0x25CB: "ring", 0x25E6: "ring",
  234. 0x25A0: "square", 0x25AA: "square", 0x25A1: "box", 0x25AB: "box",
  235. 0x25C6: "diamond", 0x25C7: "hollowDiamond"
  236. };
  237. var MEASURE_PX = 200;
  238. var shapeCtx = null;
  239. function bulletShape(text, cs, size, left, baseline) {
  240. var t = String(text || "");
  241. if (t.length !== 1 || !SHAPES[t.charCodeAt(0)]) return null;
  242. try {
  243. if (!shapeCtx) shapeCtx = document.createElement("canvas").getContext("2d");
  244. shapeCtx.font = (cs.fontStyle || "normal") + " " + (cs.fontWeight || "400") + " " +
  245. MEASURE_PX + "px " + cs.fontFamily;
  246. var m = shapeCtx.measureText(t);
  247. var k = size / MEASURE_PX;
  248. var l = left - m.actualBoundingBoxLeft * k;
  249. var r = left + m.actualBoundingBoxRight * k;
  250. var top = baseline - m.actualBoundingBoxAscent * k;
  251. var bottom = baseline + m.actualBoundingBoxDescent * k;
  252. if (!(r > l) || !(bottom > top)) return null;
  253. return { kind: SHAPES[t.charCodeAt(0)], x: l, y: top, w: r - l, h: bottom - top };
  254. } catch (e) {
  255. return null;
  256. }
  257. }
  258. /* ---------------- fonts ---------------- */
  259. /* Which shipped faces the characters need is found out here, in the
  260. page, before the display list is written: the list names the font of
  261. every piece of text, and a character no face can show is sent as a
  262. picture instead. Fetching and parsing a face is what answers "does it
  263. have this glyph" (a pass per round of discoveries, as Slides does);
  264. embedding it is left to the worker. */
  265. function loadCoverage(runs, markers, leaders, fonts) {
  266. var MAX_PASSES = OfficeFonts.FALLBACK.length + 2;
  267. function each(text, names, bold, italic, fn) {
  268. for (var i = 0; i < text.length; i++) {
  269. var cp = text.codePointAt(i);
  270. if (cp > 0xFFFF) i++;
  271. var res = C.resolveChar(cp, names, fonts, bold, italic);
  272. fn(res, bold || !!(res && res.bold), italic);
  273. }
  274. }
  275. function eachChar(fn) {
  276. runs.forEach(function (r) {
  277. each(C.visibleText(C.transformText(r.text, r.transform)), r.names, r.weight >= 600, r.italic, fn);
  278. });
  279. markers.forEach(function (m) { if (!m.shape) each(m.text, m.names, m.bold, m.italic, fn); });
  280. leaders.forEach(function (l) { each(l.ch, l.names, l.bold, false, fn); });
  281. }
  282. function pass(n) {
  283. var asked = false;
  284. eachChar(function (res, bold, italic) {
  285. if (res && res.need) { fonts.want(res.need, bold, italic); asked = true; }
  286. });
  287. if (!asked || n >= MAX_PASSES) return fonts.ready();
  288. return fonts.ready().then(function () { return pass(n + 1); });
  289. }
  290. return pass(0);
  291. }
  292. function absUrl(u) {
  293. try { return new URL(u, document.baseURI).href; } catch (e) { return u; }
  294. }
  295. /* the pieces a line fragment is spelled in, as display-list fonts:
  296. [text, font, synthetic bold stroke px, synthetic italic shear]. null
  297. when a character has no font, an empty list when nothing in it draws
  298. anything. st is { weight, size }: how much the browser emboldens or
  299. slants a face depends on both, and is measured (synthStyle). */
  300. function segsFor(text, names, fonts, bold, italic, st) {
  301. var segs = C.segmentText(text, names, fonts, bold, italic);
  302. if (!segs) return null;
  303. var out = [];
  304. for (var i = 0; i < segs.length; i++) {
  305. var res = segs[i].res;
  306. var b = bold || !!res.bold;
  307. if (res.std) {
  308. out.push([segs[i].text, "s:" + res.std + ":" + (b ? 1 : 0) + ":" + (italic ? 1 : 0), 0, 0]);
  309. } else {
  310. var face = OfficeFonts.faceFor(res.shipped, b, italic);
  311. if (!face) return null;
  312. var syn = (face.synthBold || face.synthItalic) ?
  313. C.synthStyle(face.family, st.weight, italic, st.size, segs[i].text, face.synthBold, face.synthItalic) : null;
  314. out.push([segs[i].text, "f:" + absUrl(face.url), syn ? syn.bold : 0, syn ? syn.skew : 0]);
  315. }
  316. }
  317. return out;
  318. }
  319. /* ---------------- the display list ---------------- */
  320. function rgbOf(c) {
  321. return c ? [c.red, c.green, c.blue] : [0, 0, 0];
  322. }
  323. // object-view-box: inset(t% r% b% l%) -> the kept fraction of the source
  324. function parseInset(v) {
  325. var m = /inset\(\s*([-\d.]+)%?\s*([-\d.]+)?%?\s*([-\d.]+)?%?\s*([-\d.]+)?%?\s*\)/.exec(v || "");
  326. if (!m) return null;
  327. var t = parseFloat(m[1]) || 0;
  328. var rr = m[2] !== undefined ? parseFloat(m[2]) : t;
  329. var bo = m[3] !== undefined ? parseFloat(m[3]) : t;
  330. var l = m[4] !== undefined ? parseFloat(m[4]) : rr;
  331. if (!(t || rr || bo || l)) return null;
  332. return { t: t / 100, r: rr / 100, b: bo / 100, l: l / 100 };
  333. }
  334. function borderRect(b) {
  335. var x = b.box.x, y = b.box.y, w = b.box.w, h = b.box.h, t = b.w;
  336. if (b.centred) {
  337. switch (b.side) {
  338. case "Top": return [x - t / 2, y - t / 2, w + t, t];
  339. case "Bottom": return [x - t / 2, y + h - t / 2, w + t, t];
  340. case "Left": return [x - t / 2, y - t / 2, t, h + t];
  341. default: return [x + w - t / 2, y - t / 2, t, h + t];
  342. }
  343. }
  344. switch (b.side) {
  345. case "Top": return [x, y, w, t];
  346. case "Bottom": return [x, y + h - t, w, t];
  347. case "Left": return [x, y, t, h];
  348. default: return [x + w - t, y, t, h];
  349. }
  350. }
  351. function shapeOps(s, color, dy) {
  352. var col = rgbOf(color);
  353. var cx = s.x + s.w / 2, cy = s.y - dy + s.h / 2, top = s.y - dy;
  354. // the stroke of a hollow glyph, about what Arial's ring has
  355. var stroke = Math.max(0.5, Math.min(s.w, s.h) * 0.1);
  356. switch (s.kind) {
  357. case "disc": return ["ellipse", cx, cy, s.w / 2, s.h / 2, col, 0];
  358. case "ring": return ["ellipse", cx, cy, (s.w - stroke) / 2, (s.h - stroke) / 2, col, stroke];
  359. case "square": return ["rect", s.x, top, s.w, s.h, col, 1];
  360. case "box": return ["frame", s.x + stroke / 2, top + stroke / 2, s.w - stroke, s.h - stroke, col, stroke];
  361. default:
  362. return ["poly", [cx, top, s.x + s.w, cy, cx, top + s.h, s.x, cy], col, s.kind === "diamond" ? 0 : stroke];
  363. }
  364. }
  365. function canvasBytes(canvas) {
  366. return new Promise(function (resolve) {
  367. try {
  368. canvas.toBlob(function (blob) {
  369. if (!blob) { resolve(null); return; }
  370. blob.arrayBuffer().then(function (b) { resolve(new Uint8Array(b)); }, function () { resolve(null); });
  371. }, "image/png");
  372. } catch (e) { resolve(null); }
  373. });
  374. }
  375. function sniff(bytes) {
  376. if (bytes.length > 3 && bytes[0] === 0xFF && bytes[1] === 0xD8) return "jpg";
  377. if (bytes.length > 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) return "png";
  378. return null;
  379. }
  380. // a picture pdf-lib cannot embed as it is (GIF, WebP, SVG, BMP) goes in
  381. // as a PNG of itself at its natural size
  382. function rasterPicture(img) {
  383. try {
  384. var c = document.createElement("canvas");
  385. c.width = Math.max(1, img.naturalWidth || img.width);
  386. c.height = Math.max(1, img.naturalHeight || img.height);
  387. c.getContext("2d").drawImage(img, 0, 0, c.width, c.height);
  388. return canvasBytes(c);
  389. } catch (e) {
  390. return Promise.resolve(null);
  391. }
  392. }
  393. function pictureSpec(img) {
  394. var src = img.currentSrc || img.src || "";
  395. var m = /^data:([^;,]+)/.exec(src);
  396. if (m) {
  397. if (/^image\/(jpe?g|png)$/i.test(m[1])) return Promise.resolve({ src: src });
  398. return rasterPicture(img).then(function (b) { return b ? { bytes: b } : null; });
  399. }
  400. return fetch(src).then(function (r) {
  401. if (!r.ok) throw new Error("cannot read " + src);
  402. return r.arrayBuffer();
  403. }).then(function (buf) {
  404. var bytes = new Uint8Array(buf);
  405. if (sniff(bytes)) return { bytes: bytes };
  406. return rasterPicture(img).then(function (b) { return b ? { bytes: b } : null; });
  407. }).catch(function () {
  408. return rasterPicture(img).then(function (b) { return b ? { bytes: b } : null; });
  409. });
  410. }
  411. function breathe() {
  412. return new Promise(function (res) { setTimeout(res, 0); });
  413. }
  414. /* displayList turns what collect() measured into the job pdfdraw.js
  415. draws: every coordinate relative to its own sheet, every colour a
  416. triple, every font a reference, every picture an entry of its own. */
  417. // headings as bookmarks: the sheet each one is on and how far down it
  418. function outlineOf(o) {
  419. return (o.outline || []).map(function (h) {
  420. var i = pageIndexOf(o.pages, o.sheetH, h.y);
  421. return { title: h.title, level: h.level, page: i, y: Math.max(0, h.y - o.pages[i].sheetTop) };
  422. });
  423. }
  424. function displayList(o, data, fonts, frame) {
  425. var job = {
  426. title: o.title || "", sheetW: o.sheetW, sheetH: o.sheetH, images: {}, pages: [],
  427. outline: outlineOf(o)
  428. };
  429. var imageIds = new Map();
  430. var pending = [];
  431. var nextId = 0;
  432. function pictureId(img) {
  433. var key = img.currentSrc || img.src || img;
  434. if (imageIds.has(key)) return imageIds.get(key);
  435. var id = "i" + (nextId++);
  436. imageIds.set(key, id);
  437. pending.push(pictureSpec(img).then(function (spec) { if (spec) job.images[id] = spec; }));
  438. return id;
  439. }
  440. var chain = Promise.resolve();
  441. o.pages.forEach(function (page, i) {
  442. chain = chain.then(function () {
  443. var items = data.perPage[i];
  444. var dy = page.sheetTop;
  445. var ops = [];
  446. job.pages.push(ops);
  447. items.fills.forEach(function (f) {
  448. ops.push(["rect", f.box.x, f.box.y - dy, f.box.w, f.box.h, rgbOf(f.fill.c), f.fill.a]);
  449. });
  450. items.images.forEach(function (im) {
  451. ops.push(["image", pictureId(im.img), im.box.x, im.box.y - dy, im.box.w, im.box.h, parseInset(im.viewBox)]);
  452. });
  453. items.borders.forEach(function (b) {
  454. var r = borderRect(b);
  455. ops.push(["rect", r[0], r[1] - dy, r[2], r[3], rgbOf(b.fill.c), b.fill.a]);
  456. });
  457. items.texts.forEach(function (r) {
  458. var x = r.origin.x + (r.rect.left - r.origin.left);
  459. var top = r.origin.y + (r.rect.top - r.origin.top) - dy;
  460. var lineH = r.rect.bottom - r.rect.top;
  461. var domW = r.rect.right - r.rect.left;
  462. var bg = C.parseFill(r.background);
  463. if (bg) ops.push(["rect", x, top, domW, lineH, rgbOf(bg.c), bg.a]);
  464. var glyphH = r.metrics.ascent + r.metrics.descent;
  465. var baseline = (lineH - glyphH) / 2 + r.metrics.ascent;
  466. var col = rgbOf(C.parseColor(r.color));
  467. // text where a font can show it; a character none can
  468. // (an emoji) is a picture of itself in its place
  469. C.planRun(r, fonts).forEach(function (pc) {
  470. if (pc.raster) {
  471. var pic = C.rasterText(r, pc.text, pc.w, lineH, baseline);
  472. if (!pic) return;
  473. var id = "r" + (nextId++);
  474. job.images[id] = { src: pic.src };
  475. ops.push(["image", id, x + pc.dx + pic.x, top + pic.y, pic.w, pic.h, null]);
  476. return;
  477. }
  478. var segs = segsFor(pc.text, r.names, fonts, r.weight >= 600, r.italic, r);
  479. if (!segs || !segs.length) return;
  480. ops.push(["text", x + pc.dx, top + baseline, r.size, col, pc.fit, segs, null, r.letterSpacing || 0]);
  481. });
  482. if (r.underline || r.strike) {
  483. var yOff = r.underline ? baseline + r.size * 0.11 : baseline - r.size * 0.28;
  484. ops.push(["rect", x, top + yOff, domW, Math.max(0.7, r.size * 0.06), col, 1]);
  485. }
  486. });
  487. items.extras.forEach(function (x) {
  488. if (x.kind === "marker") {
  489. if (x.shape) {
  490. ops.push(shapeOps(x.shape, x.color, dy));
  491. } else {
  492. var ms = segsFor(x.text, x.names, fonts, x.bold, x.italic, x);
  493. if (ms && ms.length) ops.push(["text", x.x, x.baseline - dy, x.size, rgbOf(x.color), 0, ms, null]);
  494. }
  495. } else if (x.kind === "leader") {
  496. var ls = segsFor(x.ch, x.names, fonts, x.bold, false, x);
  497. if (ls && ls.length) ops.push(["leader", x.box.x, x.box.w, x.baseline - dy, x.size, rgbOf(x.color), x.ch, ls[0][1]]);
  498. } else if (x.kind === "rule") {
  499. ops.push(["rect", x.box.x, x.box.y - dy, x.box.w, x.box.h, rgbOf(x.fill.c), x.fill.a]);
  500. }
  501. });
  502. return breathe();
  503. });
  504. });
  505. return chain.then(function () {
  506. return Promise.all(pending);
  507. }).then(function () {
  508. return job;
  509. });
  510. }
  511. function waitForImages(root) {
  512. var imgs = Array.prototype.slice.call(root.querySelectorAll("img"));
  513. var pending = imgs.filter(function (im) { return !im.complete; });
  514. var fontsP = OfficeFonts.preload().then(function () {
  515. return document.fonts && document.fonts.ready ? document.fonts.ready : null;
  516. });
  517. return Promise.all([fontsP].concat(pending.map(function (im) {
  518. return new Promise(function (res) {
  519. im.addEventListener("load", function () { res(); });
  520. im.addEventListener("error", function () { res(); });
  521. setTimeout(res, 8000);
  522. });
  523. })));
  524. }
  525. /* build runs an export in three steps, and only the first holds the
  526. page, for as long as it takes to read the layout:
  527. 1. snapshot o.enter() puts the page in its export state, and what
  528. is on each sheet is measured - boxes, text runs,
  529. markers - then o.leave() gives the page back. From
  530. here on the document may be edited: nothing below
  531. looks at it again.
  532. 2. prepare fonts are checked for every character and the display
  533. list is written (in steps, between which the page runs)
  534. 3. render a worker turns the list into the file
  535. o: { pageEl, pages() | pages, sheetW, sheetH, title,
  536. outline() -> [{ title, level, y }] (y in #page px, read in
  537. the export state, so it matches the sheets)
  538. enter(), leave(), onProgress(done, total, stage) }
  539. stage is "measure", "prepare", "page" or "save". */
  540. function build(o) {
  541. if (typeof PDFLib === "undefined") return Promise.reject(new Error("the PDF library failed to load"));
  542. if (!o || !o.pageEl) return Promise.reject(new Error("nothing to export"));
  543. var progress = o.onProgress || function () { };
  544. var data, snap, fonts;
  545. progress(0, 1, "measure");
  546. return waitForImages(o.pageEl).then(function () {
  547. return C.loadFontkit();
  548. }).then(function (fontkit) {
  549. try {
  550. if (o.enter) o.enter();
  551. snap = {
  552. pageEl: o.pageEl,
  553. pages: (typeof o.pages === "function" ? o.pages() : o.pages).slice(),
  554. sheetW: o.sheetW, sheetH: o.sheetH, title: o.title,
  555. outline: o.outline ? o.outline() : []
  556. };
  557. if (!snap.pages.length) throw new Error("nothing to export");
  558. data = collect(snap, new Frame(o.pageEl));
  559. } finally {
  560. if (o.leave) o.leave();
  561. }
  562. fonts = C.makeFonts(null, fontkit);
  563. var markers = [], leaders = [];
  564. data.perPage.forEach(function (p) {
  565. p.extras.forEach(function (x) {
  566. if (x.kind === "marker") markers.push(x);
  567. else if (x.kind === "leader") leaders.push(x);
  568. });
  569. });
  570. progress(0, 1, "prepare");
  571. return loadCoverage(data.runs, markers, leaders, fonts);
  572. }).then(function () {
  573. return displayList(snap, data, fonts);
  574. }).then(function (job) {
  575. data = null;
  576. return OfficePdfDraw.run(job, { onProgress: progress, loadFontkit: C.loadFontkit });
  577. });
  578. }
  579. return { build: build };
  580. })();