pdfdraw.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. /*
  2. ArozOS Office - PDF assembly from a display list
  3. ================================================
  4. The half of a browser-side PDF export that needs no page to look at.
  5. The exporter measures the document in the page (where every line, box
  6. and baseline is) and writes down what to draw as plain data - a display
  7. list. This file turns that list into a PDF with pdf-lib.
  8. It is written to run in a Web Worker (common/pdfworker.js), because this
  9. is the part that takes the time: embedding and deflating every picture,
  10. subsetting the fonts and serializing the file used to hold the page
  11. still for most of a large export. Nothing here touches the DOM, so the
  12. same code also runs in the page when a worker cannot be started.
  13. The job:
  14. {
  15. title, sheetW, sheetH, // px (96/in)
  16. images: { id: { src } | { bytes } }, // data URL / URL, or JPEG/PNG bytes
  17. pages: [ [op, ...], ... ],
  18. outline: [ { title, level, page, y } ] // optional bookmarks: level
  19. // 1-6, page index, y px
  20. } // from the page's top
  21. Coordinates are px from the page's top-left corner. Ops are arrays:
  22. ["rect", x, y, w, h, rgb, alpha]
  23. ["image", id, x, y, w, h, crop] crop {t,r,b,l} fractions | null
  24. ["text", x, baseline, size, rgb, fitW, segs, deco, letterSpacing]
  25. segs [[text, font, bold, skew]] font "s:Helvetica:bold:italic" | "f:<url>"
  26. bold: synthetic bold stroke width in px (0: none), skew:
  27. synthetic italic shear (0: upright) - both as measured
  28. in the page (OfficePdfCore.synthStyle)
  29. deco [y, h, w] underline/strike bar, w used when nothing drew
  30. letterSpacing px after every character, optional
  31. ["leader", x, w, baseline, size, rgb, ch, font]
  32. ["ellipse", cx, cy, rx, ry, rgb, strokeW] strokeW 0 = filled
  33. ["poly", [x, y, ...], rgb, strokeW]
  34. ["frame", x, y, w, h, rgb, strokeW]
  35. A page may instead be a recording, { size: [w, h] (pt), calls: [...] },
  36. made by recorder() below: the pdf-lib page calls an exporter made (Slides
  37. draws with pdf-lib directly), written down as data and made again here.
  38. A font is named "k:<standard font>" or "f:<url of a shipped face>", a
  39. picture by its id in job.images.
  40. Usage:
  41. OfficePdfDraw.render(job, { fontkit, onProgress }) -> Promise<Uint8Array>
  42. OfficePdfDraw.run(job, { onProgress, loadFontkit }) (in the page:
  43. renders in a worker, or here when no worker can start)
  44. var rec = OfficePdfDraw.recorder(); (in the page)
  45. rec.addPage([w, h]) -> a stand-in for a pdf-lib PDFPage
  46. rec.embed(src) -> Promise<picture handle> for drawImage
  47. rec.embedNow(src) -> the same handle, synchronously
  48. rec.job(title) -> the job
  49. */
  50. var OfficePdfDraw = (function () {
  51. "use strict";
  52. var PX = 0.75;
  53. var STD_VARIANTS = {
  54. Helvetica: ["Helvetica", "HelveticaBold", "HelveticaOblique", "HelveticaBoldOblique"],
  55. TimesRoman: ["TimesRoman", "TimesRomanBold", "TimesRomanItalic", "TimesRomanBoldItalic"],
  56. Courier: ["Courier", "CourierBold", "CourierOblique", "CourierBoldOblique"]
  57. };
  58. function rgb(c) {
  59. return PDFLib.rgb(c[0], c[1], c[2]);
  60. }
  61. function base64Bytes(src) {
  62. var comma = src.indexOf(",");
  63. if (comma < 0 || src.substring(0, comma).indexOf(";base64") < 0) return null;
  64. var bin = atob(src.substring(comma + 1));
  65. var out = new Uint8Array(bin.length);
  66. for (var i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
  67. return out;
  68. }
  69. function sniff(bytes) {
  70. if (bytes.length > 3 && bytes[0] === 0xFF && bytes[1] === 0xD8) return "jpg";
  71. if (bytes.length > 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) return "png";
  72. return null;
  73. }
  74. /* decodeToPng re-encodes a picture pdf-lib cannot embed (GIF, WebP,
  75. BMP) through the browser's own decoder. It works in the worker
  76. (createImageBitmap + OffscreenCanvas) and in the page alike; null
  77. when the bytes are nothing the browser can draw. */
  78. function decodeToPng(bytes) {
  79. if (typeof createImageBitmap !== "function" || typeof Blob === "undefined") return Promise.resolve(null);
  80. return createImageBitmap(new Blob([bytes])).then(function (bmp) {
  81. var w = bmp.width, h = bmp.height;
  82. if (typeof OffscreenCanvas !== "undefined") {
  83. var oc = new OffscreenCanvas(w, h);
  84. oc.getContext("2d").drawImage(bmp, 0, 0);
  85. bmp.close();
  86. return oc.convertToBlob({ type: "image/png" });
  87. }
  88. var c = document.createElement("canvas");
  89. c.width = w; c.height = h;
  90. c.getContext("2d").drawImage(bmp, 0, 0);
  91. bmp.close();
  92. return new Promise(function (res) { c.toBlob(res, "image/png"); });
  93. }).then(function (blob) {
  94. return blob ? blob.arrayBuffer() : null;
  95. }).then(function (buf) {
  96. return buf ? new Uint8Array(buf) : null;
  97. }).catch(function () { return null; });
  98. }
  99. function render(job, opts) {
  100. opts = opts || {};
  101. var pdfDoc;
  102. var fontCache = {}; // font ref -> Promise<PDFFont|null>
  103. var fontReady = {}; // font ref -> PDFFont|null
  104. var imageCache = {}; // id -> Promise<PDFImage|null>
  105. function loadFont(ref) {
  106. if (fontCache[ref]) return fontCache[ref];
  107. var p;
  108. if (ref.indexOf("k:") === 0) {
  109. p = Promise.resolve(pdfDoc.embedStandardFont(PDFLib.StandardFonts[ref.substring(2)]));
  110. } else if (ref.indexOf("s:") === 0) {
  111. var parts = ref.split(":");
  112. var names = STD_VARIANTS[parts[1]] || STD_VARIANTS.Helvetica;
  113. var key = names[(parts[2] === "1" ? 1 : 0) + (parts[3] === "1" ? 2 : 0)];
  114. p = Promise.resolve(pdfDoc.embedStandardFont(PDFLib.StandardFonts[key]));
  115. } else {
  116. var url = ref.substring(2);
  117. p = fetch(url).then(function (r) {
  118. if (!r.ok) throw new Error("cannot read " + url);
  119. return r.arrayBuffer();
  120. }).then(function (buf) {
  121. return pdfDoc.embedFont(new Uint8Array(buf), { subset: true, features: { liga: false } });
  122. });
  123. }
  124. fontCache[ref] = p.then(function (f) { fontReady[ref] = f; return f; }, function () {
  125. fontReady[ref] = null;
  126. return null;
  127. });
  128. return fontCache[ref];
  129. }
  130. function loadImage(id) {
  131. if (imageCache[id]) return imageCache[id];
  132. var spec = (job.images || {})[id] || {};
  133. var bytesP;
  134. if (spec.bytes) {
  135. bytesP = Promise.resolve(spec.bytes);
  136. } else if (spec.src && spec.src.indexOf("data:") === 0) {
  137. bytesP = Promise.resolve(base64Bytes(spec.src));
  138. } else if (spec.src) {
  139. bytesP = fetch(spec.src).then(function (r) {
  140. if (!r.ok) throw new Error("cannot read " + spec.src);
  141. return r.arrayBuffer();
  142. }).then(function (b) { return new Uint8Array(b); });
  143. } else {
  144. bytesP = Promise.resolve(null);
  145. }
  146. imageCache[id] = bytesP.then(function (bytes) {
  147. if (!bytes) return null;
  148. var kind = sniff(bytes);
  149. if (kind === "jpg") return pdfDoc.embedJpg(bytes);
  150. if (kind === "png") return pdfDoc.embedPng(bytes);
  151. // a GIF, WebP or BMP: the picture the browser decodes from
  152. // it (a GIF's first frame), as a PNG
  153. return decodeToPng(bytes).then(function (png) {
  154. return png ? pdfDoc.embedPng(png) : null;
  155. });
  156. }).catch(function () { return null; }).then(function (img) {
  157. imageReady[id] = img;
  158. return img;
  159. });
  160. return imageCache[id];
  161. }
  162. // everything a page refers to is loaded before it is drawn, so the
  163. // drawing itself stays synchronous
  164. function preload(ops) {
  165. var jobs = [];
  166. ops.forEach(function (op) {
  167. if (op[0] === "image") jobs.push(loadImage(op[1]));
  168. else if (op[0] === "text") op[6].forEach(function (s) { jobs.push(loadFont(s[1])); });
  169. else if (op[0] === "leader") jobs.push(loadFont(op[7]));
  170. });
  171. return Promise.all(jobs);
  172. }
  173. function drawPage(page, ops, images) {
  174. var H = job.sheetH;
  175. var y = function (top) { return (H - top) * PX; };
  176. var push = function (list) { page.pushOperators.apply(page, list); };
  177. ops.forEach(function (op, idx) {
  178. switch (op[0]) {
  179. case "rect":
  180. page.drawRectangle({
  181. x: op[1] * PX, y: y(op[2] + op[4]), width: op[3] * PX, height: op[4] * PX,
  182. color: rgb(op[5]), opacity: op[6]
  183. });
  184. break;
  185. case "frame":
  186. page.drawRectangle({
  187. x: op[1] * PX, y: y(op[2] + op[4]), width: op[3] * PX, height: op[4] * PX,
  188. borderColor: rgb(op[5]), borderWidth: op[6] * PX
  189. });
  190. break;
  191. case "image":
  192. var emb = images[idx];
  193. if (!emb) break;
  194. var b = { x: op[2], y: op[3], w: op[4], h: op[5] };
  195. var crop = op[6];
  196. push([PDFLib.pushGraphicsState()]);
  197. if (crop) {
  198. push([
  199. PDFLib.moveTo(b.x * PX, y(b.y)), PDFLib.lineTo((b.x + b.w) * PX, y(b.y)),
  200. PDFLib.lineTo((b.x + b.w) * PX, y(b.y + b.h)), PDFLib.lineTo(b.x * PX, y(b.y + b.h)),
  201. PDFLib.closePath(), PDFLib.clip(), PDFLib.endPath()
  202. ]);
  203. var kw = 1 - crop.l - crop.r, kh = 1 - crop.t - crop.b;
  204. if (kw > 0.001 && kh > 0.001) {
  205. var fw = b.w / kw, fh = b.h / kh;
  206. b = { x: b.x - crop.l * fw, y: b.y - crop.t * fh, w: fw, h: fh };
  207. }
  208. }
  209. page.drawImage(emb, { x: b.x * PX, y: y(b.y + b.h), width: b.w * PX, height: b.h * PX });
  210. push([PDFLib.popGraphicsState()]);
  211. break;
  212. case "text":
  213. drawText(page, op, y, push);
  214. break;
  215. case "leader":
  216. var font = fontReady[op[7]];
  217. if (!font) break;
  218. var cw = font.widthOfTextAtSize(op[6], op[4]);
  219. if (!(cw > 0)) break;
  220. var n = Math.floor((op[2] - cw) / cw);
  221. if (n < 1) break;
  222. page.drawText(new Array(n + 1).join(op[6]), {
  223. x: (op[1] + op[2] - n * cw) * PX, y: y(op[3]),
  224. size: op[4] * PX, font: font, color: rgb(op[5])
  225. });
  226. break;
  227. case "ellipse":
  228. page.drawEllipse(op[6] > 0 ? {
  229. x: op[1] * PX, y: y(op[2]), xScale: op[3] * PX, yScale: op[4] * PX,
  230. borderColor: rgb(op[5]), borderWidth: op[6] * PX
  231. } : {
  232. x: op[1] * PX, y: y(op[2]), xScale: op[3] * PX, yScale: op[4] * PX,
  233. color: rgb(op[5])
  234. });
  235. break;
  236. case "poly":
  237. var pts = op[1];
  238. if (pts.length < 4) break;
  239. var list = [PDFLib.pushGraphicsState()];
  240. list.push(op[3] > 0 ? PDFLib.setStrokingColor(rgb(op[2])) : PDFLib.setFillingColor(rgb(op[2])));
  241. if (op[3] > 0) list.push(PDFLib.setLineWidth(op[3] * PX));
  242. list.push(PDFLib.moveTo(pts[0] * PX, y(pts[1])));
  243. for (var i = 2; i + 1 < pts.length; i += 2) list.push(PDFLib.lineTo(pts[i] * PX, y(pts[i + 1])));
  244. list.push(PDFLib.closePath(), op[3] > 0 ? PDFLib.stroke() : PDFLib.fill(), PDFLib.popGraphicsState());
  245. push(list);
  246. break;
  247. }
  248. });
  249. }
  250. /* one line fragment, in as many pieces as it takes fonts to spell
  251. it, squeezed or stretched to the width the browser gave it */
  252. function drawText(page, op, y, push) {
  253. var x = op[1], baseline = op[2], size = op[3], col = rgb(op[4]), fitW = op[5];
  254. var ls = op[8] || 0;
  255. var segs = [];
  256. var total = 0;
  257. for (var i = 0; i < op[6].length; i++) {
  258. var s = op[6][i];
  259. var font = fontReady[s[1]];
  260. if (!font) return;
  261. var w = font.widthOfTextAtSize(s[0], size) + (ls ? ls * Array.from(s[0]).length : 0);
  262. // s[2]: the synthetic bold stroke in px (true: the old fixed one)
  263. var bw = typeof s[2] === "number" ? s[2] : (s[2] ? size / 28 : 0);
  264. segs.push({ text: s[0], font: font, bold: bw, skew: s[3] || 0, w: w });
  265. total += w;
  266. }
  267. var scale = 1;
  268. if (fitW > 0 && total > 0) {
  269. var ratio = fitW / total;
  270. // a ratio far from 1 means the measurement, not the font, is
  271. // wrong (a collapsed space, a transform) - leave it alone
  272. if (ratio > 0.5 && ratio < 2 && Math.abs(ratio - 1) > 0.005) scale = ratio;
  273. }
  274. var cursor = x;
  275. segs.forEach(function (seg) {
  276. var ops = [PDFLib.pushGraphicsState()];
  277. if (scale !== 1) ops.push(PDFLib.setCharacterSqueeze(scale * 100));
  278. if (ls) ops.push(PDFLib.setCharacterSpacing(ls * PX));
  279. if (seg.bold > 0.01) {
  280. ops.push(PDFLib.setTextRenderingMode(PDFLib.TextRenderingMode.FillAndOutline));
  281. ops.push(PDFLib.setLineWidth(seg.bold * PX));
  282. ops.push(PDFLib.setStrokingColor(col));
  283. }
  284. push(ops);
  285. var opt = { x: cursor * PX, y: y(baseline), size: size * PX, font: seg.font, color: col };
  286. // a synthetic italic: the text matrix's shear by height
  287. if (seg.skew > 0.001) opt.ySkew = PDFLib.radians(Math.atan(seg.skew));
  288. page.drawText(seg.text, opt);
  289. push([PDFLib.popGraphicsState()]);
  290. cursor += seg.w * scale;
  291. });
  292. var deco = op[7];
  293. if (deco) {
  294. var dw = total * scale || deco[2];
  295. page.drawRectangle({ x: x * PX, y: y(deco[0] + deco[1]), width: dw * PX, height: deco[1] * PX, color: col });
  296. }
  297. }
  298. /* ---- recorded pages ---- */
  299. // what a recorded argument refers to: fonts and pictures by name
  300. function refsIn(v, fonts, images) {
  301. if (!v || typeof v !== "object") return;
  302. if (v.__font) { fonts.push(v.__font); return; }
  303. if (v.__img) { images.push(v.__img); return; }
  304. if (Array.isArray(v)) { v.forEach(function (x) { refsIn(x, fonts, images); }); return; }
  305. for (var k in v) if (Object.prototype.hasOwnProperty.call(v, k)) refsIn(v[k], fonts, images);
  306. }
  307. function preloadCalls(calls) {
  308. var fonts = [], images = [];
  309. calls.forEach(function (c) { refsIn(c, fonts, images); });
  310. return Promise.all(fonts.map(loadFont).concat(images.map(loadImage)));
  311. }
  312. function decode(v) {
  313. if (!v || typeof v !== "object") return v;
  314. if (v.__font) return fontReady[v.__font];
  315. if (v.__img) return imageReady[v.__img];
  316. if (Array.isArray(v)) return v.map(decode);
  317. var out = {};
  318. for (var k in v) if (Object.prototype.hasOwnProperty.call(v, k)) out[k] = decode(v[k]);
  319. return out;
  320. }
  321. function replay(page, calls) {
  322. var gs = {};
  323. calls.forEach(function (c) {
  324. switch (c[0]) {
  325. case "ops":
  326. // operator arguments were kept as the text they write
  327. page.pushOperators.apply(page, c[1].map(function (o) {
  328. return PDFLib.PDFOperator.of(o[0], o[1]);
  329. }));
  330. break;
  331. case "alpha":
  332. if (!gs[c[1]]) {
  333. var ref = pdfDoc.context.register(pdfDoc.context.obj({ Type: "ExtGState", ca: c[2], CA: c[2] }));
  334. page.node.setExtGState(PDFLib.PDFName.of(c[1]), ref);
  335. gs[c[1]] = true;
  336. }
  337. break;
  338. case "drawImage":
  339. var img = imageReady[c[1].__img];
  340. if (img) page.drawImage(img, decode(c[2]));
  341. break;
  342. case "drawText":
  343. var o = decode(c[2]);
  344. if (o.font) page.drawText(c[1], o);
  345. break;
  346. case "drawSvgPath":
  347. page.drawSvgPath(c[1], decode(c[2]));
  348. break;
  349. default:
  350. if (typeof page[c[0]] === "function") page[c[0]](decode(c[1]));
  351. }
  352. });
  353. }
  354. var imageReady = {};
  355. function tick() {
  356. return new Promise(function (res) { setTimeout(res, 0); });
  357. }
  358. var total = job.pages.length;
  359. return PDFLib.PDFDocument.create().then(function (doc) {
  360. pdfDoc = doc;
  361. if (opts.fontkit) doc.registerFontkit(opts.fontkit);
  362. if (job.title) doc.setTitle(job.title);
  363. doc.setProducer("ArozOS Office");
  364. var chain = Promise.resolve();
  365. job.pages.forEach(function (ops, i) {
  366. if (!Array.isArray(ops)) {
  367. chain = chain.then(function () {
  368. return preloadCalls(ops.calls);
  369. }).then(function () {
  370. replay(pdfDoc.addPage(ops.size), ops.calls);
  371. if (opts.onProgress) opts.onProgress(i + 1, total, "page");
  372. return tick();
  373. });
  374. return;
  375. }
  376. chain = chain.then(function () {
  377. return preload(ops);
  378. }).then(function () {
  379. return Promise.all(ops.map(function (op) {
  380. return op[0] === "image" ? loadImage(op[1]) : null;
  381. }));
  382. }).then(function (images) {
  383. var page = pdfDoc.addPage([job.sheetW * PX, job.sheetH * PX]);
  384. drawPage(page, ops, images);
  385. if (opts.onProgress) opts.onProgress(i + 1, total, "page");
  386. return tick();
  387. });
  388. });
  389. return chain;
  390. }).then(function () {
  391. if (job.outline && job.outline.length) writeOutline(pdfDoc, job.outline);
  392. if (opts.onProgress) opts.onProgress(total, total, "save");
  393. return pdfDoc.save({ objectsPerTick: 20 });
  394. });
  395. }
  396. /* The document outline (bookmarks). Entries nest by level - a level 3
  397. right after a level 1 goes under the 1 - and all start open; each
  398. opens its page with the entry's y at the top of the view. */
  399. function writeOutline(doc, items) {
  400. var ctx = doc.context;
  401. var pages = doc.getPages();
  402. var root = { ref: ctx.nextRef(), level: 0, kids: [] };
  403. var stack = [root];
  404. items.forEach(function (it) {
  405. var page = pages[it.page];
  406. if (!page || !it.title) return;
  407. while (stack.length > 1 && stack[stack.length - 1].level >= it.level) stack.pop();
  408. var node = { ref: ctx.nextRef(), level: it.level, kids: [], it: it, page: page };
  409. stack[stack.length - 1].kids.push(node);
  410. stack.push(node);
  411. });
  412. if (!root.kids.length) return;
  413. function count(n) {
  414. return n.kids.reduce(function (sum, k) { return sum + 1 + count(k); }, 0);
  415. }
  416. function linkKids(n, dict) {
  417. if (!n.kids.length) return dict;
  418. dict.First = n.kids[0].ref;
  419. dict.Last = n.kids[n.kids.length - 1].ref;
  420. dict.Count = count(n);
  421. return dict;
  422. }
  423. (function write(n) {
  424. n.kids.forEach(function (k, i) {
  425. var dict = {
  426. Title: PDFLib.PDFHexString.fromText(k.it.title),
  427. Parent: n.ref,
  428. Dest: [k.page.ref, "XYZ", null, k.page.getHeight() - (k.it.y || 0) * PX, null]
  429. };
  430. if (i > 0) dict.Prev = n.kids[i - 1].ref;
  431. if (i < n.kids.length - 1) dict.Next = n.kids[i + 1].ref;
  432. ctx.assign(k.ref, ctx.obj(linkKids(k, dict)));
  433. write(k);
  434. });
  435. })(root);
  436. ctx.assign(root.ref, ctx.obj(linkKids(root, { Type: "Outlines" })));
  437. doc.catalog.set(PDFLib.PDFName.of("Outlines"), root.ref);
  438. }
  439. /* ---------------- recording (in the page) ---------------- */
  440. function encodeArg(v) {
  441. if (v === undefined || v === null || typeof v !== "object") return v;
  442. if (v.__ref) return { __font: v.__ref };
  443. if (v.__img) return { __img: v.__img };
  444. if (Array.isArray(v)) return v.map(encodeArg);
  445. var out = {};
  446. for (var k in v) {
  447. if (!Object.prototype.hasOwnProperty.call(v, k) || v[k] === undefined) continue;
  448. out[k] = encodeArg(v[k]);
  449. }
  450. return out;
  451. }
  452. function recorder() {
  453. var pages = [];
  454. var images = {};
  455. var bySrc = {};
  456. var seq = 0;
  457. function RecPage(calls) {
  458. this.calls = calls;
  459. this.node = {};
  460. }
  461. ["drawRectangle", "drawLine", "drawCircle", "drawEllipse", "drawSquare"].forEach(function (m) {
  462. RecPage.prototype[m] = function (o) { this.calls.push([m, encodeArg(o)]); };
  463. });
  464. RecPage.prototype.drawText = function (text, o) { this.calls.push(["drawText", String(text), encodeArg(o)]); };
  465. RecPage.prototype.drawImage = function (img, o) {
  466. if (img && img.__img) this.calls.push(["drawImage", { __img: img.__img }, encodeArg(o)]);
  467. };
  468. RecPage.prototype.drawSvgPath = function (d, o) { this.calls.push(["drawSvgPath", String(d), encodeArg(o)]); };
  469. RecPage.prototype.pushOperators = function () {
  470. var list = [];
  471. for (var i = 0; i < arguments.length; i++) {
  472. var op = arguments[i];
  473. // PDFOperator writes each argument with String(); keeping
  474. // that text keeps the content stream byte for byte
  475. list.push([op.name, (op.args || []).map(function (a) { return String(a); })]);
  476. }
  477. this.calls.push(["ops", list]);
  478. };
  479. RecPage.prototype.recordAlpha = function (key, a) { this.calls.push(["alpha", key, a]); };
  480. function pictureRef(src) {
  481. if (!src) return null;
  482. if (bySrc[src]) return bySrc[src];
  483. var id = "p" + (seq++);
  484. var abs = src;
  485. if (src.indexOf("data:") !== 0) {
  486. try { abs = new URL(src, document.baseURI).href; } catch (e) { abs = src; }
  487. }
  488. images[id] = { src: abs };
  489. bySrc[src] = { __img: id };
  490. return bySrc[src];
  491. }
  492. return {
  493. addPage: function (size) {
  494. var calls = [];
  495. pages.push({ size: size, calls: calls });
  496. return new RecPage(calls);
  497. },
  498. // a picture is named, not embedded: the worker embeds it once
  499. embed: function (src) {
  500. return Promise.resolve(pictureRef(src));
  501. },
  502. // the same, for a caller that has to draw it on the spot
  503. embedNow: function (src) {
  504. return pictureRef(src);
  505. },
  506. job: function (title) {
  507. return { title: title || "", images: images, pages: pages };
  508. }
  509. };
  510. }
  511. /* ---------------- running a job (in the page) ---------------- */
  512. var WORKER_URL = "../common/pdfworker.js";
  513. /* The worker is where the time goes (pictures, fonts, compression).
  514. When one cannot be started at all - an old browser, a page opened
  515. from disk - the same code runs in the page instead, just less
  516. politely. */
  517. function run(job, o) {
  518. o = o || {};
  519. return new Promise(function (resolve, reject) {
  520. var worker;
  521. var started = false;
  522. function inPage() {
  523. var fk = o.loadFontkit ? o.loadFontkit() : Promise.resolve(self.fontkit);
  524. fk.then(function (kit) {
  525. return render(job, { fontkit: kit, onProgress: o.onProgress });
  526. }).then(resolve, reject);
  527. }
  528. try {
  529. worker = new Worker(WORKER_URL);
  530. } catch (e) {
  531. inPage();
  532. return;
  533. }
  534. worker.onmessage = function (e) {
  535. var m = e.data || {};
  536. started = true;
  537. if (m.type === "progress") {
  538. if (o.onProgress) o.onProgress(m.done, m.total, m.stage);
  539. } else if (m.type === "done") {
  540. worker.terminate();
  541. resolve(m.bytes);
  542. } else if (m.type === "error") {
  543. worker.terminate();
  544. reject(new Error(m.message || "the PDF could not be written"));
  545. }
  546. };
  547. worker.onerror = function (e) {
  548. if (e && e.preventDefault) e.preventDefault();
  549. worker.terminate();
  550. if (!started) inPage();
  551. else reject(new Error((e && e.message) || "the PDF worker failed"));
  552. };
  553. var transfer = [];
  554. Object.keys(job.images || {}).forEach(function (id) {
  555. var b = job.images[id].bytes;
  556. if (b && b.buffer && transfer.indexOf(b.buffer) < 0) transfer.push(b.buffer);
  557. });
  558. worker.postMessage({ job: job }, transfer);
  559. });
  560. }
  561. return { render: render, recorder: recorder, run: run };
  562. })();