docs_pdf.js 30 KB

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