slides_pdf.js 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. /*
  2. ArozOS Office - Slides PDF export
  3. =================================
  4. Builds the PDF in the browser, out of real PDF objects, from the very
  5. DOM the editor is showing. That is the only place the truth lives: how
  6. a line of text wrapped, where each line landed, which font the browser
  7. actually resolved. A server-side renderer has to guess all of it, and
  8. the guesses drift.
  9. What each element becomes:
  10. text real PDF text (Tj), one show-text per line fragment, placed
  11. at the baseline the browser laid it out on. A character no
  12. font here can show (an emoji) comes in as a picture of
  13. itself in its place in the line (OfficePdfCore.planRun);
  14. the text around it stays text.
  15. image the original JPEG/PNG bytes, embedded once and re-used (a
  16. GIF, WebP, BMP or SVG goes in as a PNG of its first frame);
  17. crops, shaped crops and rounded corners are real PDF clip
  18. paths, flips are a negative scale in the matrix, and
  19. transparency is an ExtGState. A re-coloured picture is
  20. re-encoded through a canvas first, which is a pixel
  21. operation either way.
  22. shape a real vector path, filled and stroked
  23. line a real vector polyline, with arrow heads as filled triangles
  24. table real vector cell fills and rules, text through the rules above
  25. chart the chart's own SVG, translated element by element into PDF
  26. vectors - not a picture of it
  27. video the captured poster frame, as an image
  28. /audio
  29. Rasterizing is the documented last resort, never the first move, and it
  30. is always scoped to the one element that needs it.
  31. Every slide is an entry of the PDF's outline (bookmarks), named by its
  32. title placeholder, else "Slide N" (slideOutline).
  33. The font rule. A PDF can only show text in a font it carries, and the
  34. browser will not hand over the bytes of a system font. Three answers,
  35. tried in that order, per character:
  36. 1. one of the 14 standard PDF fonts, when the family the browser
  37. resolved is metrically identical to it (Arial / Liberation Sans ->
  38. Helvetica, and so on). Costs nothing and every reader has them.
  39. 2. one of the faces the suite ships with itself (common/fonts,
  40. OfficeFonts) - embedded, subset to the glyphs actually used. This
  41. is what carries CJK, and it is why those families are in every
  42. font stack the editor writes.
  43. 3. nothing covers it - emoji, a script we do not ship - and only then
  44. do those characters come in as a picture of themselves, drawn by
  45. the page's own canvas in the page's own fonts.
  46. A system font that is none of the above stands in as the nearest face
  47. of its kind (OfficePdfCore.resolveChar): its shipped metric twin, the
  48. standard font of its kind, Cousine for any monospace family - drawn at
  49. the size that gives it the original's advance. Any other installed
  50. family the editor never measured is substituted by the shipped face the
  51. document's own font stack names next, which is what the browser does
  52. when it has no glyph.
  53. The ink of each fragment is then fitted to the place and width the
  54. browser gave it (Tz), so a substituted face cannot push a line out of
  55. shape.
  56. Where it runs. Each slide is measured and drawn in the page, but onto a
  57. recording (OfficePdfDraw.recorder, common/pdfdraw.js): every pdf-lib
  58. call is written down as data, pictures are named rather than embedded,
  59. and fonts are only parsed here for their glyph widths. The file itself -
  60. embedding and deflating the pictures, subsetting the fonts, writing it
  61. out - is made from that recording in a Web Worker (common/pdfworker.js),
  62. so a large deck does not freeze the editor while it is written.
  63. Usage:
  64. SlidesPdf.build(body, { onProgress: fn(done, total, stage) })
  65. -> Promise<Uint8Array>
  66. stage: "measure" per slide drawn, then "page" and "save" from the
  67. worker
  68. */
  69. var SlidesPdf = (function () {
  70. "use strict";
  71. // a 16:9 slide is 960x540 css px; a PDF point is 1/72", a css px 1/96",
  72. // so the page is 720x405 pt - the 10" x 5.625" of the pptx slide size.
  73. // A deck of another shape states its own (body.size, 960x720 for 4:3),
  74. // and build() takes it from the deck it is given.
  75. var SLIDE_W = 960, SLIDE_H = 540;
  76. /* the shared exporter core (common/pdfcore.js) */
  77. var C = OfficePdfCore;
  78. var PX_TO_PT = C.PX_TO_PT;
  79. var familyList = C.familyList, loadFontkit = C.loadFontkit, makeFonts = C.makeFonts;
  80. var resolveChar = C.resolveChar, segmentText = C.segmentText, faceOf = C.faceOf;
  81. var eachTextNode = C.eachTextNode, px = C.px, clamp = C.clamp;
  82. var parseFill = C.parseFill, parseColor = C.parseColor, contrastOf = C.contrastOf;
  83. var collectRuns = C.collectRuns;
  84. var drawFragment = C.drawFragment, drawRuns = C.drawRuns;
  85. var rasterizeElement = C.rasterizeElement, rasterizeFallback = C.rasterizeFallback;
  86. var filteredImageData = C.filteredImageData;
  87. // a slide page: the core's drawing context at the slide's height
  88. function Page(page, pdfDoc, fonts) {
  89. return new C.Page(page, pdfDoc, fonts, SLIDE_H);
  90. }
  91. /* prepareFonts loads what this slide is about to need, and then checks
  92. that what arrived really covers it. The second look is not paranoia:
  93. the Traditional Chinese face has no simplified forms, so a deck that
  94. mixes them only discovers it needs the next file once the first one
  95. is in hand. Each pass asks for exactly one more face per character
  96. that is still homeless, so nothing large is fetched on spec. */
  97. function prepareFonts(objs, stageEl, fonts) {
  98. var MAX_PASSES = OfficeFonts.FALLBACK.length + 2;
  99. function eachChar(rootEl, fn) {
  100. eachTextNode(rootEl, function (node, text, cs) {
  101. var names = familyList(cs.fontFamily);
  102. var bold = (parseInt(cs.fontWeight, 10) || 400) >= 600;
  103. var italic = cs.fontStyle === "italic" || cs.fontStyle === "oblique";
  104. // what is drawn: the text as the browser shows it, without
  105. // the characters that draw nothing (no face is asked for those)
  106. text = C.visibleText(C.transformText(text, cs.textTransform));
  107. for (var i = 0; i < text.length; i++) {
  108. var cp = text.codePointAt(i);
  109. if (cp > 0xFFFF) i++;
  110. var res = resolveChar(cp, names, fonts, bold, italic);
  111. fn(res, bold || !!(res && res.bold), italic);
  112. }
  113. });
  114. }
  115. function pass(n) {
  116. var asked = false;
  117. eachChar(stageEl, function (res, bold, italic) {
  118. if (res && res.need) {
  119. fonts.want(res.need, bold, italic);
  120. asked = true;
  121. }
  122. });
  123. if (!asked || n >= MAX_PASSES) return fonts.ready();
  124. return fonts.ready().then(function () { return pass(n + 1); });
  125. }
  126. /* Now that coverage is known, embed the faces this slide will draw
  127. with - and only those. It has to be the real decision, object by
  128. object: a text box that falls back to a raster draws with nothing
  129. at all, and a face left embedded but undrawn is a subset of no
  130. glyphs, which is not a font. */
  131. function embedUsed() {
  132. (objs || []).forEach(function (o, i) {
  133. var el = stageEl.children[i];
  134. if (!el || needsRaster(o, el, fonts)) return;
  135. textRootsOf(o, el).forEach(function (root) {
  136. eachChar(root, function (res, bold, italic) {
  137. if (res && res.shipped) fonts.use(res.shipped, bold, italic);
  138. });
  139. });
  140. });
  141. return fonts.ready();
  142. }
  143. return pass(0).then(embedUsed);
  144. }
  145. /* ---------------- geometry -> PDF path operators ---------------- */
  146. // the outline a picture is clipped to: its shaped crop, or a rounded
  147. // rectangle for an unmasked one with rounded corners (border-radius
  148. // on the canvas)
  149. function imageClipKind(p) {
  150. if (p.mask) return p.mask;
  151. return Number(p.radius) > 0 ? "roundRect" : "rect";
  152. }
  153. // shapePathOps turns one of the editor's shape outlines into path
  154. // operators in page space. Used for both shape objects and the clip
  155. // path of a shaped crop, so the two cannot disagree.
  156. function shapePathOps(kind, x, y, w, h, radius, adj, geom) {
  157. var X = function (v) { return px(x + v); };
  158. var Y = function (v) { return px(SLIDE_H - (y + v)); };
  159. var ops = [];
  160. if (kind === "custom" && geom && window.SlidesShapes) {
  161. var cd = SlidesShapes.customPath(geom, w, h, "fill");
  162. if (cd) return svgPathOps(cd, X, Y);
  163. }
  164. if (!kind || kind === "rect") {
  165. ops.push(PDFLib.moveTo(X(0), Y(0)), PDFLib.lineTo(X(w), Y(0)),
  166. PDFLib.lineTo(X(w), Y(h)), PDFLib.lineTo(X(0), Y(h)), PDFLib.closePath());
  167. return ops;
  168. }
  169. if (kind === "roundRect") {
  170. var r = Math.min(radius > 0 ? radius : Math.min(w, h) * 0.15, Math.min(w, h) / 2);
  171. var k = r * 0.5523;
  172. ops.push(PDFLib.moveTo(X(r), Y(0)));
  173. ops.push(PDFLib.lineTo(X(w - r), Y(0)));
  174. ops.push(PDFLib.appendBezierCurve(X(w - r + k), Y(0), X(w), Y(r - k), X(w), Y(r)));
  175. ops.push(PDFLib.lineTo(X(w), Y(h - r)));
  176. ops.push(PDFLib.appendBezierCurve(X(w), Y(h - r + k), X(w - r + k), Y(h), X(w - r), Y(h)));
  177. ops.push(PDFLib.lineTo(X(r), Y(h)));
  178. ops.push(PDFLib.appendBezierCurve(X(r - k), Y(h), X(0), Y(h - r + k), X(0), Y(h - r)));
  179. ops.push(PDFLib.lineTo(X(0), Y(r)));
  180. ops.push(PDFLib.appendBezierCurve(X(0), Y(r - k), X(r - k), Y(0), X(r), Y(0)));
  181. ops.push(PDFLib.closePath());
  182. return ops;
  183. }
  184. if (kind === "ellipse") {
  185. var cx = w / 2, cy = h / 2, kx = cx * 0.5523, ky = cy * 0.5523;
  186. ops.push(PDFLib.moveTo(X(0), Y(cy)));
  187. ops.push(PDFLib.appendBezierCurve(X(0), Y(cy - ky), X(cx - kx), Y(0), X(cx), Y(0)));
  188. ops.push(PDFLib.appendBezierCurve(X(cx + kx), Y(0), X(w), Y(cy - ky), X(w), Y(cy)));
  189. ops.push(PDFLib.appendBezierCurve(X(w), Y(cy + ky), X(cx + kx), Y(h), X(cx), Y(h)));
  190. ops.push(PDFLib.appendBezierCurve(X(cx - kx), Y(h), X(0), Y(cy + ky), X(0), Y(cy)));
  191. ops.push(PDFLib.closePath());
  192. return ops;
  193. }
  194. var d = (window.SlidesShapes) ? SlidesShapes.path(kind, w, h, adj) : "";
  195. if (!d) return shapePathOps("rect", x, y, w, h, 0);
  196. return svgPathOps(d, X, Y);
  197. }
  198. /* svgPathOps turns one of the catalogue's paths into PDF path
  199. operators. It only has to understand M, L, C and Z because that is
  200. all slides_shapes.js ever writes - arcs arrive already converted to
  201. cubics, which is the whole reason for that restriction. */
  202. function svgPathOps(d, X, Y) {
  203. var ops = [];
  204. var re = /([MLCZ])([^MLCZ]*)/g;
  205. var m;
  206. while ((m = re.exec(d))) {
  207. var cmd = m[1];
  208. if (cmd === "Z") { ops.push(PDFLib.closePath()); continue; }
  209. var v = m[2].trim().split(/[\s,]+/).map(Number);
  210. if (cmd === "M") ops.push(PDFLib.moveTo(X(v[0]), Y(v[1])));
  211. else if (cmd === "L") ops.push(PDFLib.lineTo(X(v[0]), Y(v[1])));
  212. else ops.push(PDFLib.appendBezierCurve(X(v[0]), Y(v[1]),
  213. X(v[2]), Y(v[3]), X(v[4]), Y(v[5])));
  214. }
  215. return ops;
  216. }
  217. // boxOf returns an element's box in slide coordinates
  218. function boxOf(el, stageEl) {
  219. var r = el.getBoundingClientRect(), s = stageEl.getBoundingClientRect();
  220. return { x: r.left - s.left, y: r.top - s.top, w: r.width, h: r.height };
  221. }
  222. /* paintedBoxOf is the area an element actually paints: its own box plus
  223. whatever of its content overflows it (objects do not clip - a table's
  224. rows grow past its frame, text runs out of its box), within the
  225. slide, which does clip. */
  226. function paintedBoxOf(el, stageEl) {
  227. var b = boxOf(el, stageEl);
  228. var s = stageEl.getBoundingClientRect();
  229. var x0 = b.x, y0 = b.y, x1 = b.x + b.w, y1 = b.y + b.h;
  230. var all = el.getElementsByTagName("*");
  231. for (var i = 0; i < all.length; i++) {
  232. var r = all[i].getBoundingClientRect();
  233. if (!(r.width > 0) || !(r.height > 0)) continue;
  234. x0 = Math.min(x0, r.left - s.left); y0 = Math.min(y0, r.top - s.top);
  235. x1 = Math.max(x1, r.right - s.left); y1 = Math.max(y1, r.bottom - s.top);
  236. }
  237. x0 = Math.max(x0, 0); y0 = Math.max(y0, 0);
  238. x1 = Math.min(x1, SLIDE_W); y1 = Math.min(y1, SLIDE_H);
  239. return { x: x0, y: y0, w: Math.max(1, x1 - x0), h: Math.max(1, y1 - y0) };
  240. }
  241. /* drawAsRaster puts one element in as an image of itself, at the area
  242. it paints on the slide. A rotated object is drawn unrotated inside the
  243. rotation matrix its caller set up, so the picture stays crisp
  244. rather than being a picture of something already turned. */
  245. function drawAsRaster(pg, o, el, ctx) {
  246. var b = boxOf(el, ctx.stage);
  247. var area = paintedBoxOf(el, ctx.stage);
  248. var ext = { x: area.x - b.x, y: area.y - b.y, w: area.w, h: area.h };
  249. return rasterizeElement(el, b.w, b.h, ext).then(function (src) {
  250. if (src) return src;
  251. area = b; // html2canvas draws the element's own box
  252. return rasterizeFallback(el, b.w, b.h);
  253. }).then(function (src) {
  254. if (!src) return;
  255. return ctx.embed(src).then(function (img) {
  256. if (!img) return;
  257. pg.p.drawImage(img, {
  258. x: px(area.x), y: pg.y(area.y + area.h), width: px(area.w), height: px(area.h)
  259. });
  260. });
  261. });
  262. }
  263. /* textPicture is what drawRuns calls for the few characters no font
  264. can show: the picture is named in the recording on the spot, so it
  265. lands in the drawing order exactly where the text around it does */
  266. function textPicture(pg, ctx) {
  267. return function (src, x, y, w, h) {
  268. var img = ctx.embedNow(src);
  269. if (img) pg.p.drawImage(img, { x: px(x), y: pg.y(y + h), width: px(w), height: px(h) });
  270. };
  271. }
  272. /* ---------------- SVG (charts) -> PDF vectors ---------------- */
  273. /* OfficeCharts draws with rect / line / polyline / polygon / path /
  274. circle / text, so a chart can be put in the PDF as the vectors it
  275. already is. Anything unexpected in the tree makes the caller fall
  276. back to a raster for that one object. */
  277. var SVG_KNOWN = { g: 1, rect: 1, line: 1, circle: 1, polyline: 1,
  278. polygon: 1, path: 1, text: 1, defs: 1, title: 1, desc: 1 };
  279. /* svgTranslatable asks whether drawSvg can express this tree, before
  280. anything is drawn - an element it does not know, or a label in a
  281. script no font here can show, means the chart has to come in as a
  282. picture instead. */
  283. function svgTranslatable(el, fonts) {
  284. for (var i = 0; i < el.children.length; i++) {
  285. var c = el.children[i];
  286. var tag = c.tagName.toLowerCase();
  287. if (!SVG_KNOWN[tag]) return false;
  288. if (tag === "text") {
  289. var str = (c.textContent || "").replace(/[\u0000-\u001F\u007F]/g, " ");
  290. var cs = window.getComputedStyle(c);
  291. if (str.trim() && !segmentText(str, familyList(cs.fontFamily), fonts,
  292. (parseInt(cs.fontWeight, 10) || 400) >= 600, false)) return false;
  293. }
  294. if (tag === "g" && !svgTranslatable(c, fonts)) return false;
  295. }
  296. return true;
  297. }
  298. function drawSvg(pg, svgEl, x, y, w, h) {
  299. var vb = (svgEl.getAttribute("viewBox") || "").split(/[\s,]+/).map(parseFloat);
  300. var vw = vb.length === 4 ? vb[2] : w, vh = vb.length === 4 ? vb[3] : h;
  301. var vx = vb.length === 4 ? vb[0] : 0, vy = vb.length === 4 ? vb[1] : 0;
  302. if (!(vw > 0) || !(vh > 0)) return false;
  303. var k = Math.min(w / vw, h / vh);
  304. var offX = x + (w - vw * k) / 2, offY = y + (h - vh * k) / 2;
  305. var X = function (v) { return offX + (v - vx) * k; };
  306. var Y = function (v) { return offY + (v - vy) * k; };
  307. var ok = true;
  308. var walk = function (el) {
  309. if (!ok) return;
  310. for (var i = 0; i < el.children.length; i++) {
  311. var c = el.children[i];
  312. var tag = c.tagName.toLowerCase();
  313. var cs = window.getComputedStyle(c);
  314. var fill = c.getAttribute("fill");
  315. var stroke = c.getAttribute("stroke");
  316. // charts inherit their text colour; resolve it the way the
  317. // browser did rather than guessing
  318. var fillF = (fill === "none") ? null
  319. : parseFill(fill === "currentColor" || !fill ? cs.color : fill);
  320. var strokeF = (!stroke || stroke === "none") ? null
  321. : parseFill(stroke === "currentColor" ? cs.color : stroke);
  322. var fillCol = fillF ? fillF.c : null, fillA = fillF ? fillF.a : 1;
  323. var strokeCol = strokeF ? strokeF.c : null, strokeA = strokeF ? strokeF.a : 1;
  324. var sw = parseFloat(c.getAttribute("stroke-width") || "1") * k;
  325. switch (tag) {
  326. case "g": walk(c); break;
  327. case "rect":
  328. pg.rect(X(parseFloat(c.getAttribute("x") || 0)),
  329. Y(parseFloat(c.getAttribute("y") || 0)),
  330. parseFloat(c.getAttribute("width") || 0) * k,
  331. parseFloat(c.getAttribute("height") || 0) * k,
  332. { fill: fillCol, stroke: strokeCol, strokeW: strokeCol ? sw : 0,
  333. fillOpacity: fillA, strokeOpacity: strokeA });
  334. break;
  335. case "line":
  336. pg.p.drawLine({
  337. start: { x: px(X(parseFloat(c.getAttribute("x1") || 0))), y: pg.y(Y(parseFloat(c.getAttribute("y1") || 0))) },
  338. end: { x: px(X(parseFloat(c.getAttribute("x2") || 0))), y: pg.y(Y(parseFloat(c.getAttribute("y2") || 0))) },
  339. thickness: px(sw), color: strokeCol || PDFLib.rgb(0, 0, 0)
  340. });
  341. break;
  342. case "circle":
  343. pg.p.drawCircle({
  344. x: px(X(parseFloat(c.getAttribute("cx") || 0))),
  345. y: pg.y(Y(parseFloat(c.getAttribute("cy") || 0))),
  346. size: px(parseFloat(c.getAttribute("r") || 0) * k),
  347. color: fillCol || undefined,
  348. borderColor: strokeCol || undefined,
  349. borderWidth: strokeCol ? px(sw) : undefined
  350. });
  351. break;
  352. case "polyline":
  353. case "polygon":
  354. var pts = (c.getAttribute("points") || "").trim().split(/\s+/).map(function (p) {
  355. var xy = p.split(",");
  356. return [X(parseFloat(xy[0])), Y(parseFloat(xy[1]))];
  357. }).filter(function (p) { return isFinite(p[0]) && isFinite(p[1]); });
  358. if (pts.length < 2) break;
  359. var ops = [];
  360. pts.forEach(function (p, i) {
  361. ops.push(i === 0 ? PDFLib.moveTo(px(p[0]), pg.y(p[1]))
  362. : PDFLib.lineTo(px(p[0]), pg.y(p[1])));
  363. });
  364. if (tag === "polygon") ops.push(PDFLib.closePath());
  365. pg.save();
  366. if (fillCol) ops.unshift(PDFLib.setFillingColor(fillCol));
  367. if (strokeCol) {
  368. ops.unshift(PDFLib.setStrokingColor(strokeCol));
  369. ops.unshift(PDFLib.setLineWidth(px(sw)));
  370. }
  371. ops.push(fillCol && strokeCol ? PDFLib.fillAndStroke()
  372. : (fillCol ? PDFLib.fill() : PDFLib.stroke()));
  373. pg.ops(ops);
  374. pg.restore();
  375. break;
  376. case "path":
  377. var d = c.getAttribute("d");
  378. if (!d) break;
  379. pg.p.drawSvgPath(d, {
  380. x: px(offX - vx * k), y: pg.y(offY - vy * k), scale: k * PX_TO_PT,
  381. color: fillCol || undefined,
  382. borderColor: strokeCol || undefined,
  383. borderWidth: strokeCol ? px(sw) : undefined
  384. });
  385. break;
  386. case "text":
  387. var str = (c.textContent || "").replace(/[\u0000-\u001F\u007F]/g, " ");
  388. if (!str.trim()) break;
  389. // the svg is measured in px like the rest of the
  390. // slide; only the final drawText call is in points.
  391. // A label is placed from its own anchor, so it is
  392. // measured first and never fitted to a box.
  393. var names = familyList(cs.fontFamily);
  394. var bold = (parseInt(cs.fontWeight, 10) || 400) >= 600;
  395. var sizePx = (parseFloat(cs.fontSize) || 12) * k;
  396. var segs = segmentText(str, names, pg.fonts, bold, false);
  397. if (!segs) { ok = false; return; }
  398. var twPx = 0;
  399. segs.forEach(function (seg) {
  400. var f = faceOf(seg.res, pg.fonts, bold, false);
  401. if (f) twPx += f.font.widthOfTextAtSize(seg.text, sizePx * f.scale);
  402. });
  403. var anchor = c.getAttribute("text-anchor") || "start";
  404. var tx = X(parseFloat(c.getAttribute("x") || 0));
  405. if (anchor === "middle") tx -= twPx / 2;
  406. else if (anchor === "end") tx -= twPx;
  407. drawFragment(pg, {
  408. text: str, names: names, bold: bold, italic: false,
  409. weight: parseInt(cs.fontWeight, 10) || 400,
  410. sizePx: sizePx, xPx: tx,
  411. baselinePx: Y(parseFloat(c.getAttribute("y") || 0)),
  412. color: fillCol || PDFLib.rgb(0, 0, 0), fitPx: 0
  413. });
  414. break;
  415. case "defs":
  416. case "title":
  417. case "desc":
  418. break;
  419. default:
  420. ok = false;
  421. return;
  422. }
  423. }
  424. };
  425. walk(svgEl);
  426. return ok;
  427. }
  428. /* ---------------- one object ---------------- */
  429. /* An object's rotation turns the whole object about its own centre.
  430. Rather than rotate every primitive, the drawing runs inside one
  431. matrix and the offscreen element is measured with its CSS rotation
  432. taken off - otherwise getBoundingClientRect would hand back the
  433. bounding box of the rotated result instead of the box itself. */
  434. function withRotation(pg, o, el, fn) {
  435. if (!o.rot) return fn();
  436. var prev = el ? el.style.transform : null;
  437. if (el) {
  438. el.style.transform = "none";
  439. void el.offsetWidth; // force the reflow
  440. }
  441. var rad = -o.rot * Math.PI / 180; // css turns clockwise, pdf does not
  442. var cos = Math.cos(rad), sin = Math.sin(rad);
  443. var cx = px(o.x + o.w / 2), cy = pg.y(o.y + o.h / 2);
  444. pg.save();
  445. pg.ops([PDFLib.concatTransformationMatrix(cos, sin, -sin, cos,
  446. cx - (cos * cx - sin * cy), cy - (sin * cx + cos * cy))]);
  447. var restore = function () {
  448. pg.restore();
  449. if (el) el.style.transform = prev;
  450. };
  451. var out;
  452. try { out = fn(); } catch (e) { restore(); throw e; }
  453. return Promise.resolve(out).then(function (v) { restore(); return v; },
  454. function (e) { restore(); throw e; });
  455. }
  456. /* needsRaster answers the fallback question up front, before anything
  457. is drawn and before any transform is touched. It only inspects fonts
  458. and characters, so a rotated element can be asked safely. */
  459. /* textRootsOf names the elements an object actually takes its text
  460. from, so that asking "can this be drawn as text" and asking "which
  461. faces will it draw with" cannot look at different things. */
  462. function textRootsOf(o, el) {
  463. if (!el) return [];
  464. if (o.type === "text") return [el.querySelector(".sl-text-in")].filter(Boolean);
  465. if (o.type === "shape") return [el.querySelector(".sl-shape-text")].filter(Boolean);
  466. if (o.type === "table") return Array.prototype.slice.call(el.querySelectorAll("td, th"));
  467. if (o.type === "chart") return [el.querySelector("svg")].filter(Boolean);
  468. return [];
  469. }
  470. /* Text no longer sends its object to a picture: a character no font
  471. can show is drawn as a picture of itself in its place in the line
  472. (OfficePdfCore.planRun), and the rest stays text. Only a chart whose
  473. SVG the translator cannot express goes in whole. */
  474. function needsRaster(o, el, fonts) {
  475. if (!el) return false;
  476. if (o.type === "chart") {
  477. var svg = el.querySelector("svg");
  478. return !svg || !svgTranslatable(svg, fonts);
  479. }
  480. return false;
  481. }
  482. function drawObject(pg, o, el, ctx) {
  483. var raster = !!(el && needsRaster(o, el, pg.fonts));
  484. return withRotation(pg, o, el, function () {
  485. return raster ? drawAsRaster(pg, o, el, ctx)
  486. : drawObjectBody(pg, o, el, ctx);
  487. });
  488. }
  489. function drawObjectBody(pg, o, el, ctx) {
  490. var origin = null;
  491. if (el) {
  492. var r = el.getBoundingClientRect();
  493. origin = { left: r.left, top: r.top, x: o.x, y: o.y };
  494. }
  495. switch (o.type) {
  496. case "image":
  497. case "video":
  498. case "audio":
  499. return drawImageObject(pg, o, el, ctx);
  500. case "shape":
  501. return drawShapeObject(pg, o, el, origin, ctx);
  502. case "line":
  503. drawLineObject(pg, o);
  504. return Promise.resolve();
  505. case "table":
  506. return drawTableObject(pg, o, el, ctx);
  507. case "chart":
  508. return drawChartObject(pg, o, el, ctx);
  509. case "text":
  510. return drawTextObject(pg, o, el, origin, ctx);
  511. }
  512. return Promise.resolve();
  513. }
  514. /* ---- text object ---- */
  515. function drawTextObject(pg, o, el, origin, ctx) {
  516. var inner = el ? el.querySelector(".sl-text-in") : null;
  517. if (!inner) return Promise.resolve();
  518. var runs = collectRuns(inner, origin);
  519. if (runs.length) drawRuns(pg, runs, textPicture(pg, ctx));
  520. return Promise.resolve();
  521. }
  522. /* ---- image object ---- */
  523. function drawImageObject(pg, o, el, ctx) {
  524. var embedImage = ctx.embed;
  525. var p = o.props || {};
  526. var src = p.src;
  527. if (o.type === "video" || o.type === "audio") src = p.png || "";
  528. if (!src) return Promise.resolve();
  529. var filter = (window.SlidesImageTools ? SlidesImageTools.imageFilter(p) : "");
  530. var prep = filter ? filteredImageData(src, filter) : Promise.resolve(src);
  531. // an SVG picture is drawn to a PNG here, at the size it is shown
  532. // (with its crop) - a worker has no way to draw one. GIF, WebP and
  533. // BMP are decoded where the file is written (pdfdraw.js).
  534. if (/^data:image\/svg/i.test(src)) {
  535. var sc = p.crop && p.crop.length === 4 ? p.crop.map(function (v) { return Number(v) || 0; }) : [0, 0, 0, 0];
  536. var sw = Math.max(1, o.w / Math.max(0.001, 1 - sc[0] - sc[2]));
  537. var sh = Math.max(1, o.h / Math.max(0.001, 1 - sc[1] - sc[3]));
  538. var k = Math.min(C.RASTER_SCALE, 4096 / Math.max(sw, sh));
  539. prep = filteredImageData(src, filter || "none", Math.round(sw * k), Math.round(sh * k));
  540. }
  541. // a fill on the frame shows through the picture's transparent parts
  542. var under = null, underImg = null;
  543. if (o.type === "image" && p.fillGrad && p.fillGrad.stops && p.fillGrad.stops.length) {
  544. prep = Promise.all([prep, embedImage(gradientPng(p.fillGrad, Math.max(1, o.w), Math.max(1, o.h)))])
  545. .then(function (r) { underImg = r[1]; return r[0]; });
  546. } else if (o.type === "image" && p.fill && p.fill !== "none") {
  547. under = parseFill(p.fill);
  548. }
  549. return prep.then(function (finalSrc) {
  550. return embedImage(finalSrc || src);
  551. }).then(function (img) {
  552. if (!img) return;
  553. var crop = p.crop;
  554. var kw = 1, kh = 1, cl = 0, ct = 0;
  555. if (crop && crop.length === 4) {
  556. cl = Number(crop[0]) || 0; ct = Number(crop[1]) || 0;
  557. kw = 1 - cl - (Number(crop[2]) || 0);
  558. kh = 1 - ct - (Number(crop[3]) || 0);
  559. if (!(kw > 0.001) || !(kh > 0.001)) { kw = kh = 1; cl = ct = 0; }
  560. }
  561. // the visible window is the object box; the whole picture is
  562. // that box scaled up by the crop, shifted so the kept part lines
  563. // up - the same identity the editor and the pptx reader use
  564. var fullW = o.w / kw, fullH = o.h / kh;
  565. var fullX = o.x - cl * fullW, fullY = o.y - ct * fullH;
  566. pg.save();
  567. // clip to the frame, in the shape the picture is masked to
  568. var clipOps = shapePathOps(imageClipKind(p), o.x, o.y, o.w, o.h, p.radius, p.adj);
  569. clipOps.push(PDFLib.clip(), PDFLib.endPath());
  570. pg.ops(clipOps);
  571. if (p.opacity && p.opacity < 1) {
  572. pg.ops([PDFLib.setGraphicsState(pg.alpha(clamp(p.opacity, 0, 1)))]);
  573. }
  574. if (underImg) {
  575. pg.p.drawImage(underImg, { x: px(o.x), y: pg.y(o.y + o.h), width: px(o.w), height: px(o.h) });
  576. } else if (under) {
  577. pg.rect(o.x, o.y, o.w, o.h, { fill: under.c, fillOpacity: under.a });
  578. }
  579. // flips are a negative scale about the frame's centre: the
  580. // part the crop kept is what gets mirrored, as in PowerPoint
  581. // and the editor (flipOriginStyle in slides.js)
  582. var sx = p.flipH ? -1 : 1, sy = p.flipV ? -1 : 1;
  583. var drawX = fullX, drawY = fullY;
  584. if (sx < 0 || sy < 0) {
  585. var cx = px(o.x + o.w / 2), cy = pg.y(o.y + o.h / 2);
  586. pg.ops([PDFLib.concatTransformationMatrix(sx, 0, 0, sy,
  587. cx - sx * cx, cy - sy * cy)]);
  588. }
  589. pg.p.drawImage(img, {
  590. x: px(drawX), y: pg.y(drawY + fullH),
  591. width: px(fullW), height: px(fullH)
  592. });
  593. pg.restore();
  594. // the picture's outline, along the frame (or the shape it is
  595. // cropped to), centred on it as the editor and PowerPoint draw it
  596. var sw = Number(p.strokeW) || 0;
  597. var sc = (sw > 0 && p.stroke && p.stroke !== "none") ? parseColor(p.stroke) : null;
  598. if (sc && o.type === "image") {
  599. var sops = shapePathOps(imageClipKind(p), o.x, o.y, o.w, o.h, p.radius, p.adj);
  600. sops.unshift(PDFLib.setStrokingColor(sc), PDFLib.setLineWidth(px(sw)));
  601. var idash = SlidesLines.dashArray(p, sw);
  602. if (idash) sops.unshift(PDFLib.setDashPattern(idash.map(px), 0));
  603. sops.push(PDFLib.stroke());
  604. pg.save();
  605. pg.ops(sops);
  606. pg.restore();
  607. }
  608. });
  609. }
  610. /* ---- shape object ---- */
  611. function drawShapeObject(pg, o, el, origin, ctx) {
  612. var p = o.props || {};
  613. var g = p.fillGrad;
  614. // a gradient fill is painted as a picture of itself, clipped to the
  615. // outline (gradientPng); that picture has to be in hand first
  616. if (g && g.stops && g.stops.length && ctx && ctx.embed) {
  617. return ctx.embed(gradientPng(g, Math.max(1, o.w), Math.max(1, o.h))).then(function (img) {
  618. return drawShapeBody(pg, o, el, origin, img, ctx);
  619. });
  620. }
  621. return drawShapeBody(pg, o, el, origin, null, ctx);
  622. }
  623. function drawShapeBody(pg, o, el, origin, gradImg, ctx) {
  624. var p = o.props || {};
  625. var kind = window.SlidesShapes ? SlidesShapes.canonical(p.kind || "rect") : (p.kind || "rect");
  626. var open = window.SlidesShapes && SlidesShapes.isOpen(kind);
  627. var evenOdd = window.SlidesShapes && SlidesShapes.evenOdd(kind);
  628. var strokeW = Number(p.strokeW) || 0;
  629. var fillCss = p.fill, strokeCss = p.stroke;
  630. // the same rule the canvas follows: a bracket, brace or arc is a
  631. // line, so it is stroked and never filled (see shapeSvg)
  632. if (open) {
  633. if (!strokeCss || strokeCss === "none") {
  634. strokeCss = (fillCss && fillCss !== "none") ? fillCss : "#333333";
  635. }
  636. if (!strokeW) strokeW = 2;
  637. fillCss = "none";
  638. }
  639. // a fill may be partly transparent (#rrggbbaa, from a pptx alpha)
  640. var fillF = (fillCss && fillCss !== "none") ? parseFill(fillCss) : null;
  641. var fill = fillF ? fillF.c : null;
  642. var stroke = (strokeW > 0 && strokeCss && strokeCss !== "none") ? parseColor(strokeCss) : null;
  643. if (gradImg && !open) {
  644. var cops = shapePathOps(kind, o.x, o.y, o.w, o.h, p.radius, p.adj, p.geom);
  645. cops.push(evenOdd ? PDFLib.clipEvenOdd() : PDFLib.clip(), PDFLib.endPath());
  646. pg.save();
  647. pg.ops(cops);
  648. pg.p.drawImage(gradImg, { x: px(o.x), y: pg.y(o.y + o.h), width: px(o.w), height: px(o.h) });
  649. pg.restore();
  650. fill = null;
  651. }
  652. // a see-through fill is painted on its own, under its own alpha,
  653. // so the outline drawn after it stays opaque
  654. if (fill && fillF.a < 1) {
  655. var fops = shapePathOps(kind, o.x, o.y, o.w, o.h, p.radius, p.adj, p.geom);
  656. fops.unshift(PDFLib.setFillingColor(fill));
  657. fops.unshift(PDFLib.setGraphicsState(pg.alpha(fillF.a)));
  658. fops.push(evenOdd ? PDFLib.PDFOperator.of(PDFLib.PDFOperatorNames.FillEvenOdd)
  659. : PDFLib.fill());
  660. pg.save();
  661. pg.ops(fops);
  662. pg.restore();
  663. fill = null;
  664. }
  665. if (fill || stroke) {
  666. var ops = shapePathOps(kind, o.x, o.y, o.w, o.h, p.radius, p.adj, p.geom);
  667. if (fill) ops.unshift(PDFLib.setFillingColor(fill));
  668. if (stroke) {
  669. ops.unshift(PDFLib.setStrokingColor(stroke));
  670. ops.unshift(PDFLib.setLineWidth(px(strokeW)));
  671. var sdash = SlidesLines.dashArray(p, strokeW);
  672. if (sdash) {
  673. ops.unshift(PDFLib.setDashPattern(sdash.map(px), 0));
  674. if (SlidesLines.capOf(p) === "butt") ops.unshift(PDFLib.setLineCap(PDFLib.LineCapStyle.Butt));
  675. }
  676. }
  677. if (fill && stroke) {
  678. ops.push(evenOdd ? PDFLib.PDFOperator.of(PDFLib.PDFOperatorNames.FillEvenOddAndStroke)
  679. : PDFLib.fillAndStroke());
  680. } else if (fill) {
  681. ops.push(evenOdd ? PDFLib.PDFOperator.of(PDFLib.PDFOperatorNames.FillEvenOdd)
  682. : PDFLib.fill());
  683. } else {
  684. ops.push(PDFLib.stroke());
  685. }
  686. pg.save();
  687. pg.ops(ops);
  688. pg.restore();
  689. }
  690. // markings the canvas draws over the outline - the bars of a
  691. // predefined process, the fold of a folded corner
  692. var det = window.SlidesShapes ? SlidesShapes.detail(kind, o.w, o.h, p.adj) : "";
  693. if (det) {
  694. var dc = stroke || parseColor(contrastOf(fillCss)) || PDFLib.rgb(0.2, 0.2, 0.2);
  695. var X = function (v) { return px(o.x + v); };
  696. var Y = function (v) { return px(SLIDE_H - (o.y + v)); };
  697. var dops = svgPathOps(det, X, Y);
  698. dops.unshift(PDFLib.setLineWidth(px(strokeW > 0 ? strokeW : 1)));
  699. dops.unshift(PDFLib.setStrokingColor(dc));
  700. dops.push(PDFLib.stroke());
  701. pg.save();
  702. pg.ops(dops);
  703. pg.restore();
  704. }
  705. // the caption rides on the same text rules as a text box
  706. var inner = el ? el.querySelector(".sl-shape-text") : null;
  707. if (!inner) return Promise.resolve();
  708. var runs = collectRuns(inner, origin || { left: 0, top: 0, x: o.x, y: o.y });
  709. if (runs.length) drawRuns(pg, runs, ctx ? textPicture(pg, ctx) : null);
  710. return Promise.resolve();
  711. }
  712. /* ---- line object ---- */
  713. function drawLineObject(pg, o) {
  714. var p = o.props || {};
  715. var pts = (p.points && p.points.length >= 2)
  716. ? p.points.map(function (pt) { return [o.x + pt[0], o.y + pt[1]]; })
  717. : [[o.x, o.y], [o.x + o.w, o.y + o.h]];
  718. var col = parseColor(p.stroke) || PDFLib.rgb(0.13, 0.13, 0.14);
  719. var sw = Number(p.strokeW) || 2;
  720. // the stroke, its dash and both ends are the very geometry the
  721. // canvas draws (slides_lines.js)
  722. var geo = SlidesLines.geometry(pts, p, sw);
  723. var dash = SlidesLines.dashArray(p, sw);
  724. var round = SlidesLines.capOf(p) === "round";
  725. var ops = [PDFLib.setStrokingColor(col), PDFLib.setLineWidth(px(sw)),
  726. PDFLib.setLineCap(round ? PDFLib.LineCapStyle.Round : PDFLib.LineCapStyle.Butt),
  727. PDFLib.setLineJoin(PDFLib.LineJoinStyle.Round)];
  728. if (dash) ops.push(PDFLib.setDashPattern(dash.map(px), 0));
  729. geo.line.forEach(function (pt, i) {
  730. ops.push(i === 0 ? PDFLib.moveTo(px(pt[0]), pg.y(pt[1])) : PDFLib.lineTo(px(pt[0]), pg.y(pt[1])));
  731. });
  732. ops.push(PDFLib.stroke());
  733. pg.save();
  734. pg.ops(ops);
  735. pg.restore();
  736. geo.heads.forEach(function (h) {
  737. var hpts = h.pts;
  738. if (h.kind === "circle") {
  739. // a circle as a fine polygon: a head is a few pixels across
  740. hpts = [];
  741. for (var k = 0; k < 32; k++) {
  742. var a = k / 32 * Math.PI * 2;
  743. hpts.push([h.cx + h.r * Math.cos(a), h.cy + h.r * Math.sin(a)]);
  744. }
  745. }
  746. var hops = h.fill ? [PDFLib.setFillingColor(col)]
  747. : [PDFLib.setStrokingColor(col), PDFLib.setLineWidth(px(sw)),
  748. PDFLib.setLineCap(PDFLib.LineCapStyle.Round),
  749. PDFLib.setLineJoin(PDFLib.LineJoinStyle.Round)];
  750. hpts.forEach(function (pt, i) {
  751. hops.push(i === 0 ? PDFLib.moveTo(px(pt[0]), pg.y(pt[1])) : PDFLib.lineTo(px(pt[0]), pg.y(pt[1])));
  752. });
  753. var closed = h.kind === "circle" || h.closed;
  754. if (closed) hops.push(PDFLib.closePath());
  755. hops.push(h.fill ? PDFLib.fill() : PDFLib.stroke());
  756. pg.save();
  757. pg.ops(hops);
  758. pg.restore();
  759. });
  760. }
  761. /* ---- table object ---- */
  762. function drawTableObject(pg, o, el, ctx) {
  763. if (!el) return Promise.resolve();
  764. var host = el.getBoundingClientRect();
  765. var origin = { left: host.left, top: host.top, x: o.x, y: o.y };
  766. var cells = el.querySelectorAll("td, th");
  767. var jobs = [];
  768. for (var i = 0; i < cells.length; i++) {
  769. (function (cell) {
  770. var cs = window.getComputedStyle(cell);
  771. var cr = cell.getBoundingClientRect();
  772. var cx = o.x + (cr.left - host.left), cy = o.y + (cr.top - host.top);
  773. var bg = parseFill(cs.backgroundColor);
  774. if (bg) pg.rect(cx, cy, cr.width, cr.height, { fill: bg.c, fillOpacity: bg.a });
  775. var bd = parseFill(cs.borderTopColor);
  776. var bw = parseFloat(cs.borderTopWidth) || 0;
  777. if (bd && bw > 0) {
  778. pg.rect(cx, cy, cr.width, cr.height,
  779. { stroke: bd.c, strokeW: bw, strokeOpacity: bd.a });
  780. }
  781. var runs = collectRuns(cell, origin);
  782. if (runs.length) drawRuns(pg, runs, textPicture(pg, ctx));
  783. })(cells[i]);
  784. }
  785. return Promise.all(jobs);
  786. }
  787. /* ---- chart object ---- */
  788. function drawChartObject(pg, o, el, ctx) {
  789. var svg = el ? el.querySelector("svg") : null;
  790. if (svg) drawSvg(pg, svg, o.x, o.y, o.w, o.h);
  791. return Promise.resolve();
  792. }
  793. /* ---- a picture or gradient background (slide.bgImage / bgGrad) ----
  794. The picture goes in as itself, clipped to the page; a gradient is
  795. painted onto a canvas the size of the slide and goes in as a picture
  796. of that - smooth colour ramps compress to almost nothing, and a
  797. canvas draws them exactly the way the editor's CSS does. */
  798. function gradientPng(g, w, h) {
  799. var cv = document.createElement("canvas");
  800. cv.width = Math.max(1, Math.round(w));
  801. cv.height = Math.max(1, Math.round(h));
  802. var c2 = cv.getContext("2d");
  803. var grad;
  804. if (g.kind === "radial") {
  805. var cx = (isFinite(Number(g.cx)) ? Number(g.cx) : 0.5) * w;
  806. var cy = (isFinite(Number(g.cy)) ? Number(g.cy) : 0.5) * h;
  807. // CSS "circle farthest-corner"
  808. var r = Math.max(Math.hypot(cx, cy), Math.hypot(w - cx, cy),
  809. Math.hypot(cx, h - cy), Math.hypot(w - cx, h - cy));
  810. grad = c2.createRadialGradient(cx, cy, 0, cx, cy, r);
  811. } else {
  812. // the CSS gradient line: through the centre at the angle, long
  813. // enough that the corners land on the first and last stop
  814. var a = (Number(g.angle) || 0) * Math.PI / 180;
  815. var dx = Math.sin(a), dy = -Math.cos(a);
  816. var half = (Math.abs(w * dx) + Math.abs(h * dy)) / 2;
  817. grad = c2.createLinearGradient(w / 2 - dx * half, h / 2 - dy * half,
  818. w / 2 + dx * half, h / 2 + dy * half);
  819. }
  820. (g.stops || []).forEach(function (st) {
  821. try { grad.addColorStop(clamp(Number(st.pos) || 0, 0, 1), String(st.color)); } catch (e) { }
  822. });
  823. c2.fillStyle = grad;
  824. c2.fillRect(0, 0, cv.width, cv.height);
  825. return cv.toDataURL("image/png");
  826. }
  827. function drawBackground(pg, slide, embedImage) {
  828. var im = slide.bgImage;
  829. var g = slide.bgGrad;
  830. if (im && im.src) {
  831. return embedImage(im.src).then(function (img) {
  832. if (!img) return;
  833. var x = Number(im.x) || 0, y = Number(im.y) || 0;
  834. var w = Number(im.w) || SLIDE_W, h = Number(im.h) || SLIDE_H;
  835. pg.save();
  836. pg.ops([PDFLib.rectangle(0, 0, px(SLIDE_W), px(SLIDE_H)), PDFLib.clip(), PDFLib.endPath()]);
  837. var op = Number(im.opacity);
  838. if (op > 0 && op < 1) pg.ops([PDFLib.setGraphicsState(pg.alpha(op))]);
  839. var draw = function (dx, dy) {
  840. pg.p.drawImage(img, { x: px(dx), y: pg.y(dy + h), width: px(w), height: px(h) });
  841. };
  842. if (im.tile && w >= 4 && h >= 4) {
  843. var x0 = x - Math.ceil(x / w) * w, y0 = y - Math.ceil(y / h) * h;
  844. for (var ty = y0; ty < SLIDE_H; ty += h) {
  845. for (var tx = x0; tx < SLIDE_W; tx += w) draw(tx, ty);
  846. }
  847. } else {
  848. draw(x, y);
  849. }
  850. pg.restore();
  851. });
  852. }
  853. if (g && g.stops && g.stops.length) {
  854. return embedImage(gradientPng(g, SLIDE_W, SLIDE_H)).then(function (img) {
  855. if (img) pg.p.drawImage(img, { x: 0, y: 0, width: px(SLIDE_W), height: px(SLIDE_H) });
  856. });
  857. }
  858. return Promise.resolve();
  859. }
  860. /* ---------------- the build ---------------- */
  861. /* stage renders one slide offscreen at exactly the slide's size so
  862. every measurement below is taken at scale 1, whatever zoom the editor
  863. is at */
  864. function withStage(slide, fn) {
  865. var box = "width:" + SLIDE_W + "px;height:" + SLIDE_H + "px;";
  866. var holder = document.createElement("div");
  867. holder.style.cssText = "position:fixed;left:-20000px;top:0;" + box +
  868. "overflow:hidden;contain:layout;";
  869. var el = document.createElement("div");
  870. el.className = "sl-slidebase";
  871. el.style.cssText = box + "position:relative;overflow:hidden;";
  872. holder.appendChild(el);
  873. document.body.appendChild(holder);
  874. SlidesApp.renderSlideContent(el, slide);
  875. return waitForImages(el).then(function () {
  876. return fn(el);
  877. }).then(function (r) {
  878. holder.remove();
  879. return r;
  880. }, function (e) {
  881. holder.remove();
  882. throw e;
  883. });
  884. }
  885. function waitForImages(root) {
  886. var imgs = Array.prototype.slice.call(root.querySelectorAll("img"));
  887. var pending = imgs.filter(function (im) { return !im.complete; });
  888. // the shipped faces have to be in place before anything is
  889. // measured: a line laid out in a fallback wraps somewhere else
  890. var fonts = OfficeFonts.preload().then(function () {
  891. return OfficeFonts.ready();
  892. }).then(function () {
  893. return document.fonts && document.fonts.ready ? document.fonts.ready : null;
  894. });
  895. if (!pending.length) return fonts;
  896. return Promise.all([fonts].concat(pending.map(function (im) {
  897. return new Promise(function (res) {
  898. var done = function () { res(); };
  899. im.addEventListener("load", done);
  900. im.addEventListener("error", done);
  901. setTimeout(done, 6000);
  902. });
  903. })));
  904. }
  905. /* the PDF's outline (bookmarks): one entry per slide, named by its
  906. title placeholder - an imported deck's title and centre title are one
  907. too - else "Slide N" */
  908. function slideOutline(slides) {
  909. var parser = new DOMParser();
  910. return slides.map(function (slide, i) {
  911. var title = "";
  912. (slide.objects || []).some(function (o) {
  913. if (!o || !o.props || o.props.ph !== "title" || !o.props.html) return false;
  914. // a line break or a new paragraph reads as a space
  915. var html = String(o.props.html).replace(/<(br|\/p|\/div|\/li)\b/gi, " $&");
  916. title = (parser.parseFromString(html, "text/html").body.textContent || "")
  917. .split(String.fromCharCode(0x200B)).join("").replace(/\s+/g, " ").trim();
  918. return !!title;
  919. });
  920. return { title: title || "Slide " + (i + 1), level: 1, page: i, y: 0 };
  921. });
  922. }
  923. function build(body, opts) {
  924. opts = opts || {};
  925. if (typeof PDFLib === "undefined") {
  926. return Promise.reject(new Error("the PDF library failed to load"));
  927. }
  928. var slides = (body && body.slides) || [];
  929. if (!slides.length) return Promise.reject(new Error("the presentation has no slides"));
  930. var sz = body.size || [];
  931. SLIDE_W = Number(sz[0]) > 0 ? Number(sz[0]) : 960;
  932. SLIDE_H = Number(sz[1]) > 0 ? Number(sz[1]) : 540;
  933. return loadFontkit().then(function (fontkit) {
  934. return PDFLib.PDFDocument.create().then(function (pdfDoc) {
  935. pdfDoc.registerFontkit(fontkit);
  936. return { doc: pdfDoc, kit: fontkit };
  937. });
  938. }).then(function (made) {
  939. // this document is never saved: it only lends its fonts their
  940. // metrics - the drawing goes to the recording
  941. var pdfDoc = made.doc;
  942. var fonts = makeFonts(pdfDoc, made.kit);
  943. var rec = OfficePdfDraw.recorder();
  944. var embedImage = rec.embed;
  945. var theme = SlidesApp.themeOf();
  946. var chain = Promise.resolve();
  947. slides.forEach(function (slide, idx) {
  948. chain = chain.then(function () {
  949. var page = rec.addPage([px(SLIDE_W), px(SLIDE_H)]);
  950. var pg = new Page(page, pdfDoc, fonts);
  951. var bg = parseColor(slide.bg || theme.bg);
  952. if (bg) pg.rect(0, 0, SLIDE_W, SLIDE_H, { fill: bg });
  953. return drawBackground(pg, slide, embedImage).then(function () {
  954. return withStage(slide, drawSlide);
  955. });
  956. function drawSlide(stageEl) {
  957. var ctx = { stage: stageEl, embed: embedImage, embedNow: rec.embedNow };
  958. // every face this slide needs is in hand before a
  959. // single object is measured, so the drawing below
  960. // can stay synchronous
  961. var objs = slide.objects || [];
  962. return prepareFonts(objs, stageEl, fonts).then(function () {
  963. var seq = Promise.resolve();
  964. objs.forEach(function (o, i) {
  965. seq = seq.then(function () {
  966. return drawObject(pg, o, stageEl.children[i], ctx);
  967. });
  968. });
  969. return seq;
  970. });
  971. }
  972. }).then(function () {
  973. if (opts.onProgress) opts.onProgress(idx + 1, slides.length, "measure");
  974. // let the editor breathe between slides
  975. return new Promise(function (res) { setTimeout(res, 0); });
  976. });
  977. });
  978. return chain.then(function () {
  979. var job = rec.job(opts.title);
  980. job.outline = slideOutline(slides);
  981. return OfficePdfDraw.run(job, {
  982. onProgress: opts.onProgress, loadFontkit: loadFontkit
  983. });
  984. });
  985. });
  986. }
  987. return {
  988. build: build
  989. };
  990. })();