docs_pdfimport.js 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349
  1. /*
  2. ArozOS Office - Docs: importing a PDF (DocsPdfImport)
  3. =====================================================
  4. File > Import > PDF turns a PDF into an editable document: real text
  5. in paragraphs that re-wrap, headings, lists, tables, pictures - never a
  6. picture of the page. A PDF stores none of that structure, only glyphs
  7. at positions, so it is rebuilt here from the geometry, the way Word's
  8. "PDF Reflow" does:
  9. 1. common/pdfread.js reads every page into text runs (font, size,
  10. colour, position), pictures and vector shapes.
  11. 2. Per page (analyzePage): the shapes are sorted into table rules,
  12. underlines, shading and drawings. A grid of rules is a table; a
  13. cluster of drawings with little text in it is a figure, kept as a
  14. picture of that region; vector bullets become bullet characters.
  15. What is left is cut into reading-order regions (columns are found
  16. as a vertical gutter that runs past several lines on both sides),
  17. and each region's runs into lines.
  18. 3. Over the whole document (buildBody): running headers, footers and
  19. page numbers (lines that repeat on most pages) are taken out, the
  20. page size and margins are read from the text block, and lines are
  21. joined into paragraphs - a line continues the one above when the
  22. spacing and style match and the one above was full. Alignment,
  23. indents, spacing, line spacing, lists and heading levels follow
  24. from the same geometry.
  25. 4. The result is a Docs body in the rich model (docs.js header,
  26. mod/office/docx/reader.go): inline CSS in points, data-ls line
  27. spacing, ul/ol.doc-list, table.of-table, span.doc-tab with
  28. data-tabs stops.
  29. Pictures and figures are stored through opts.storeImage (a link to the
  30. window's working copy in ArozOS, inline in the web edition), so a
  31. picture-heavy PDF does not become a huge body.
  32. DocsPdfImport.convert(bytes, {
  33. name, // the PDF's file name
  34. storeImage(blob, name) -> Promise<src>,
  35. progress(msg, done, total),
  36. password(retry, cb(pw|null))
  37. }) -> Promise<body>
  38. */
  39. (function () {
  40. "use strict";
  41. var PT_PER_MM = 72 / 25.4;
  42. var PAGE_SIZES = { "A4": [210, 297], "Letter": [215.9, 279.4], "Legal": [215.9, 355.6] };
  43. /* ---------------- small helpers ---------------- */
  44. function median(a) {
  45. if (!a.length) return 0;
  46. var s = a.slice().sort(function (x, y) { return x - y; });
  47. var m = s.length >> 1;
  48. return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
  49. }
  50. function pct(a, p) {
  51. if (!a.length) return 0;
  52. var s = a.slice().sort(function (x, y) { return x - y; });
  53. return s[Math.max(0, Math.min(s.length - 1, Math.floor(p * (s.length - 1) + 0.5)))];
  54. }
  55. function r1(v) { return Math.round(v * 10) / 10; }
  56. function r2(v) { return Math.round(v * 100) / 100; }
  57. function pt(v) { return r1(v) + "pt"; }
  58. function hex(c) {
  59. if (!c) return "#000000";
  60. var s = "#";
  61. for (var i = 0; i < 3; i++) {
  62. var v = Math.max(0, Math.min(255, Math.round(c[i])));
  63. s += (v < 16 ? "0" : "") + v.toString(16);
  64. }
  65. return s;
  66. }
  67. function isWhite(c) { return c && c !== "pattern" && c[0] >= 245 && c[1] >= 245 && c[2] >= 245; }
  68. function isLight(c) { return c && c[0] >= 225 && c[1] >= 225 && c[2] >= 225; }
  69. function cpOf(s, i) { return s.codePointAt ? s.codePointAt(i) : s.charCodeAt(i); }
  70. function isCJK(cp) {
  71. return (cp >= 0x2E80 && cp <= 0x9FFF) || (cp >= 0xAC00 && cp <= 0xD7AF) ||
  72. (cp >= 0xF900 && cp <= 0xFAFF) || (cp >= 0xFE30 && cp <= 0xFE4F) ||
  73. (cp >= 0xFF00 && cp <= 0xFFEF) || (cp >= 0x20000 && cp <= 0x2FFFF);
  74. }
  75. function lastCp(s) {
  76. if (!s) return 0;
  77. var c = s.charCodeAt(s.length - 1);
  78. if (c >= 0xDC00 && c <= 0xDFFF && s.length > 1) return cpOf(s, s.length - 2);
  79. return c;
  80. }
  81. function inBox(x, y, b, tol) {
  82. tol = tol || 0;
  83. return x >= b.x0 - tol && x <= b.x1 + tol && y >= b.y0 - tol && y <= b.y1 + tol;
  84. }
  85. function runCx(r) { return (r.x0 + r.x1) / 2; }
  86. function runCy(r) { return r.base - r.size * 0.3; }
  87. // a turn of the event loop between pages (a message, not a timer: a
  88. // background tab runs timers once a second)
  89. function yield0() {
  90. return new Promise(function (res) {
  91. if (typeof MessageChannel !== "function") { setTimeout(res, 0); return; }
  92. var ch = new MessageChannel();
  93. ch.port1.onmessage = function () { res(); };
  94. ch.port2.postMessage(0);
  95. });
  96. }
  97. /* A canvas as a file. toDataURL rather than toBlob: toBlob's callback
  98. can take a second to come back (it waits on the browser's idle
  99. time), which is minutes over a document of pictures */
  100. function canvasBlob(canvas, type, quality) {
  101. try {
  102. var url = canvas.toDataURL(type, quality);
  103. var bin = atob(url.substring(url.indexOf(",") + 1));
  104. var arr = new Uint8Array(bin.length);
  105. for (var i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
  106. return new Blob([arr], { type: url.substring(5, url.indexOf(";")) || type });
  107. } catch (e) {
  108. return null;
  109. }
  110. }
  111. /* ---------------- runs ---------------- */
  112. // the same text drawn twice at (almost) the same place: an overprinted
  113. // fake bold, a drop shadow, or an OCR layer under visible text
  114. function dedupe(runs) {
  115. var buckets = {};
  116. var out = [];
  117. runs.forEach(function (r) {
  118. var key = Math.round(r.base);
  119. var dup = null;
  120. for (var k = key - 1; k <= key + 1 && !dup; k++) {
  121. var b = buckets[k];
  122. if (!b) continue;
  123. for (var i = 0; i < b.length; i++) {
  124. var o = b[i];
  125. // drawn over itself, not beside itself: "ll" is two letters
  126. var w = Math.max(0.5, Math.min(o.x1 - o.x0, r.x1 - r.x0));
  127. var overlap = Math.min(o.x1, r.x1) - Math.max(o.x0, r.x0);
  128. if (o.text === r.text && overlap >= w * 0.7 && Math.abs(o.x0 - r.x0) < r.size * 0.25 &&
  129. Math.abs(o.base - r.base) < r.size * 0.25 && Math.abs(o.size - r.size) < 0.5) {
  130. dup = o;
  131. break;
  132. }
  133. }
  134. }
  135. if (dup) {
  136. if (Math.abs(dup.x0 - r.x0) > 0.05 || Math.abs(dup.base - r.base) > 0.05) dup.overprinted = true;
  137. // what was drawn last is what shows
  138. if (!r.invisible) { dup.color = r.color; dup.invisible = false; }
  139. return;
  140. }
  141. (buckets[key] = buckets[key] || []).push(r);
  142. out.push(r);
  143. });
  144. return out;
  145. }
  146. function prepareRuns(page) {
  147. var runs = page.runs.filter(function (r) {
  148. return r.text && Math.abs(r.angle) < 3 && r.size >= 2 && r.size < 500 &&
  149. r.x1 > -5 && r.x0 < page.width + 5 && r.bottom > -5 && r.top < page.height + 5;
  150. });
  151. var inv = 0, vis = 0;
  152. runs.forEach(function (r) {
  153. if (r.invisible) inv += r.text.length; else vis += r.text.length;
  154. });
  155. // a scanned page with a recognised text layer: the text is the page
  156. var ocr = inv > 20 && inv >= vis;
  157. runs = runs.filter(function (r) { return ocr || !r.invisible; });
  158. if (ocr) runs.forEach(function (r) { if (r.invisible) { r.color = [0, 0, 0]; r.invisible = false; } });
  159. runs = dedupe(runs);
  160. runs.forEach(function (r) {
  161. r.bold = !!(r.font.bold || r.fakeBold || r.overprinted);
  162. r.italic = !!r.font.italic;
  163. });
  164. return { runs: runs, ocr: ocr };
  165. }
  166. /* ---------------- shapes ---------------- */
  167. function classifyShapes(shapes, W, H) {
  168. var hl = [], vl = [], fills = [], draws = [];
  169. shapes.forEach(function (s) {
  170. if (s.alpha === 0) return;
  171. var w = s.x1 - s.x0, h = s.y1 - s.y0;
  172. if (s.x1 < 0 || s.y1 < 0 || s.x0 > W || s.y0 > H) return;
  173. var solidFill = s.fill && s.fill !== "pattern";
  174. // a page-sized background
  175. if (w * h > 0.6 * W * H && s.fill && !s.stroke) return;
  176. if (s.fill === "pattern") {
  177. draws.push({ x0: s.x0, y0: s.y0, x1: s.x1, y1: s.y1, n: 4, curve: true, pts: s.count, pattern: true });
  178. } else if (solidFill && !isWhite(s.fill)) {
  179. if (s.rect && h <= 2.5 && w > h * 2) {
  180. hl.push({ a: s.x0, b: s.x1, pos: (s.y0 + s.y1) / 2, w: Math.max(0.5, h), color: s.fill });
  181. } else if (s.rect && w <= 2.5 && h > w * 2) {
  182. vl.push({ a: s.y0, b: s.y1, pos: (s.x0 + s.x1) / 2, w: Math.max(0.5, w), color: s.fill });
  183. } else if (s.rect) {
  184. fills.push({ x0: s.x0, y0: s.y0, x1: s.x1, y1: s.y1, color: s.fill });
  185. } else {
  186. draws.push({ x0: s.x0, y0: s.y0, x1: s.x1, y1: s.y1, n: 1, curve: s.curve, pts: s.count, color: s.fill });
  187. }
  188. }
  189. if (s.stroke && !isWhite(s.stroke)) {
  190. var diag = false;
  191. if (s.segs) {
  192. s.segs.forEach(function (g) {
  193. var dx = Math.abs(g[2] - g[0]), dy = Math.abs(g[3] - g[1]);
  194. if (dy <= 0.8 && dx >= 2) {
  195. hl.push({ a: Math.min(g[0], g[2]), b: Math.max(g[0], g[2]), pos: (g[1] + g[3]) / 2, w: s.lw, color: s.stroke });
  196. } else if (dx <= 0.8 && dy >= 2) {
  197. vl.push({ a: Math.min(g[1], g[3]), b: Math.max(g[1], g[3]), pos: (g[0] + g[2]) / 2, w: s.lw, color: s.stroke });
  198. } else if (dx > 0.8 || dy > 0.8) {
  199. diag = true;
  200. }
  201. });
  202. }
  203. if (!s.segs || diag) {
  204. draws.push({ x0: s.x0, y0: s.y0, x1: s.x1, y1: s.y1, n: 1, curve: s.curve, pts: s.count, color: s.stroke });
  205. }
  206. }
  207. });
  208. return { hl: mergeLines(hl), vl: mergeLines(vl), fills: fills, draws: draws };
  209. }
  210. // collinear pieces of one rule (a dashed line, a table border drawn
  211. // cell by cell) become one
  212. function mergeLines(lines) {
  213. lines.sort(function (p, q) { return p.pos - q.pos || p.a - q.a; });
  214. var groups = [];
  215. lines.forEach(function (l) {
  216. var g = groups.length ? groups[groups.length - 1] : null;
  217. if (g && Math.abs(l.pos - g.pos) <= 1.2) g.items.push(l);
  218. else groups.push({ pos: l.pos, items: [l] });
  219. });
  220. var out = [];
  221. groups.forEach(function (g) {
  222. g.items.sort(function (p, q) { return p.a - q.a; });
  223. var cur = null;
  224. g.items.forEach(function (l) {
  225. if (cur && l.a <= cur.b + 1.5) {
  226. cur.b = Math.max(cur.b, l.b);
  227. cur.w = Math.max(cur.w, l.w);
  228. } else {
  229. cur = { a: l.a, b: l.b, pos: l.pos, w: l.w, color: l.color };
  230. out.push(cur);
  231. }
  232. });
  233. });
  234. return out;
  235. }
  236. /* ---------------- tables ---------------- */
  237. function cluster(values, tol) {
  238. var s = values.slice().sort(function (a, b) { return a - b; });
  239. var out = [];
  240. var grp = [];
  241. s.forEach(function (v) {
  242. if (grp.length && v - grp[grp.length - 1] > tol) {
  243. out.push(median(grp));
  244. grp = [];
  245. }
  246. grp.push(v);
  247. });
  248. if (grp.length) out.push(median(grp));
  249. return out;
  250. }
  251. function coverage(lines, pos, a, b) {
  252. if (b <= a) return 0;
  253. var segs = [];
  254. lines.forEach(function (l) {
  255. if (Math.abs(l.pos - pos) > 2.5) return;
  256. var s = Math.max(a, l.a), e = Math.min(b, l.b);
  257. if (e > s) segs.push([s, e]);
  258. });
  259. segs.sort(function (p, q) { return p[0] - q[0]; });
  260. var tot = 0, end = a;
  261. segs.forEach(function (sg) {
  262. var s = Math.max(sg[0], end);
  263. if (sg[1] > s) { tot += sg[1] - s; end = sg[1]; }
  264. });
  265. return tot / (b - a);
  266. }
  267. function lineAt(lines, pos, a, b) {
  268. var best = null, bestCov = 0;
  269. lines.forEach(function (l) {
  270. if (Math.abs(l.pos - pos) > 2.5) return;
  271. var c = Math.min(b, l.b) - Math.max(a, l.a);
  272. if (c > bestCov) { bestCov = c; best = l; }
  273. });
  274. return best && bestCov >= (b - a) * 0.5 ? best : null;
  275. }
  276. function findTables(hl, vl, runs, W, H) {
  277. var n = hl.length + vl.length;
  278. if (hl.length < 2 || vl.length < 2 || hl.length * vl.length > 4000000) return [];
  279. var parent = [];
  280. for (var i = 0; i < n; i++) parent.push(i);
  281. function find(x) { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }
  282. var tol = 2.5;
  283. for (var h = 0; h < hl.length; h++) {
  284. var L = hl[h];
  285. for (var v = 0; v < vl.length; v++) {
  286. var V = vl[v];
  287. if (V.pos >= L.a - tol && V.pos <= L.b + tol && L.pos >= V.a - tol && L.pos <= V.b + tol) {
  288. var ra = find(h), rb = find(hl.length + v);
  289. if (ra !== rb) parent[ra] = rb;
  290. }
  291. }
  292. }
  293. var comps = {};
  294. for (i = 0; i < n; i++) {
  295. var root = find(i);
  296. var c = comps[root] = comps[root] || { h: [], v: [] };
  297. if (i < hl.length) c.h.push(hl[i]); else c.v.push(vl[i - hl.length]);
  298. }
  299. var tables = [];
  300. Object.keys(comps).forEach(function (k) {
  301. var c = comps[k];
  302. if (c.h.length < 2 || c.v.length < 2) return;
  303. var xs = cluster(c.v.map(function (l) { return l.pos; }), 2.5);
  304. var ys = cluster(c.h.map(function (l) { return l.pos; }), 2.5);
  305. if (xs.length < 2 || ys.length < 2) return;
  306. var box = { x0: xs[0], y0: ys[0], x1: xs[xs.length - 1], y1: ys[ys.length - 1] };
  307. var bw = box.x1 - box.x0, bh = box.y1 - box.y0;
  308. if (bw < 20 || bh < 8) return;
  309. var rows = ys.length - 1, cols = xs.length - 1;
  310. var inside = runs.filter(function (r) { return inBox(runCx(r), runCy(r), box, 1); });
  311. if (rows * cols === 1) {
  312. // a frame round the page or a figure, not a boxed paragraph
  313. if (bh > H * 0.4 || bw * bh > W * H * 0.5 || !inside.length) return;
  314. }
  315. if (!inside.length && rows * cols < 4) return;
  316. tables.push(buildGrid(c, xs, ys, box, inside));
  317. });
  318. return tables;
  319. }
  320. function buildGrid(comp, xs, ys, box, runs) {
  321. var rows = ys.length - 1, cols = xs.length - 1;
  322. var parent = [];
  323. var i;
  324. for (i = 0; i < rows * cols; i++) parent.push(i);
  325. function find(x) { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }
  326. function union(a, b) { a = find(a); b = find(b); if (a !== b) parent[Math.max(a, b)] = Math.min(a, b); }
  327. function groupsOf() {
  328. var g = {};
  329. for (var q = 0; q < rows * cols; q++) {
  330. var rt = find(q);
  331. var e = g[rt] = g[rt] || { r0: 99999, r1: -1, c0: 99999, c1: -1, n: 0 };
  332. var rr = Math.floor(q / cols), cc = q % cols;
  333. e.r0 = Math.min(e.r0, rr); e.r1 = Math.max(e.r1, rr);
  334. e.c0 = Math.min(e.c0, cc); e.c1 = Math.max(e.c1, cc);
  335. e.n++;
  336. }
  337. return g;
  338. }
  339. function rectangular(g) {
  340. for (var key in g) {
  341. var e = g[key];
  342. if (e.n !== (e.r1 - e.r0 + 1) * (e.c1 - e.c0 + 1)) return false;
  343. }
  344. return true;
  345. }
  346. var merges = function (vertical) {
  347. for (var r = 0; r < rows; r++) {
  348. for (var c = 0; c < cols; c++) {
  349. if (c + 1 < cols && coverage(comp.v, xs[c + 1], ys[r], ys[r + 1]) < 0.6) union(r * cols + c, r * cols + c + 1);
  350. if (vertical && r + 1 < rows && coverage(comp.h, ys[r + 1], xs[c], xs[c + 1]) < 0.6) union(r * cols + c, (r + 1) * cols + c);
  351. }
  352. }
  353. };
  354. merges(true);
  355. var groups = groupsOf();
  356. if (!rectangular(groups)) {
  357. for (i = 0; i < rows * cols; i++) parent[i] = i;
  358. merges(false);
  359. groups = groupsOf();
  360. if (!rectangular(groups)) {
  361. for (i = 0; i < rows * cols; i++) parent[i] = i;
  362. groups = groupsOf();
  363. }
  364. }
  365. var cells = [];
  366. var anchorOf = {};
  367. Object.keys(groups).forEach(function (k) {
  368. var e = groups[k];
  369. var cell = {
  370. r: e.r0, c: e.c0, rs: e.r1 - e.r0 + 1, cs: e.c1 - e.c0 + 1,
  371. x0: xs[e.c0], x1: xs[e.c1 + 1], y0: ys[e.r0], y1: ys[e.r1 + 1],
  372. runs: [], images: []
  373. };
  374. cell.top = lineAt(comp.h, cell.y0, cell.x0, cell.x1);
  375. cell.bottom = lineAt(comp.h, cell.y1, cell.x0, cell.x1);
  376. cell.left = lineAt(comp.v, cell.x0, cell.y0, cell.y1);
  377. cell.right = lineAt(comp.v, cell.x1, cell.y0, cell.y1);
  378. cells.push(cell);
  379. for (var rr = e.r0; rr <= e.r1; rr++) {
  380. for (var cc = e.c0; cc <= e.c1; cc++) anchorOf[rr * cols + cc] = cell;
  381. }
  382. });
  383. var t = { kind: "table", x0: box.x0, y0: box.y0, x1: box.x1, y1: box.y1, xs: xs, ys: ys,
  384. rows: rows, cols: cols, cells: cells, cellAt: anchorOf, comp: comp };
  385. runs.forEach(function (r) {
  386. var cell = cellFor(t, runCx(r), runCy(r));
  387. if (cell) { cell.runs.push(r); r.used = true; }
  388. });
  389. return t;
  390. }
  391. function cellFor(t, x, y) {
  392. var c = -1, r = -1;
  393. for (var i = 0; i < t.cols; i++) if (x >= t.xs[i] - 1 && x <= t.xs[i + 1] + 1) { c = i; break; }
  394. for (var j = 0; j < t.rows; j++) if (y >= t.ys[j] - 1 && y <= t.ys[j + 1] + 1) { r = j; break; }
  395. if (c < 0 || r < 0) return null;
  396. return t.cellAt[r * t.cols + c];
  397. }
  398. /* ---------------- figures ---------------- */
  399. function clusterBoxes(items, gap) {
  400. var groups = [];
  401. items.sort(function (a, b) { return a.y0 - b.y0; });
  402. items.forEach(function (it) {
  403. var hit = null;
  404. for (var i = 0; i < groups.length; i++) {
  405. var g = groups[i];
  406. if (it.x0 <= g.x1 + gap && it.x1 >= g.x0 - gap && it.y0 <= g.y1 + gap && it.y1 >= g.y0 - gap) {
  407. if (!hit) {
  408. hit = g;
  409. g.items.push(it);
  410. g.x0 = Math.min(g.x0, it.x0); g.y0 = Math.min(g.y0, it.y0);
  411. g.x1 = Math.max(g.x1, it.x1); g.y1 = Math.max(g.y1, it.y1);
  412. } else {
  413. // the item joins two groups: merge them
  414. hit.items = hit.items.concat(g.items);
  415. hit.x0 = Math.min(hit.x0, g.x0); hit.y0 = Math.min(hit.y0, g.y0);
  416. hit.x1 = Math.max(hit.x1, g.x1); hit.y1 = Math.max(hit.y1, g.y1);
  417. groups.splice(i, 1);
  418. i--;
  419. }
  420. }
  421. }
  422. if (!hit) groups.push({ x0: it.x0, y0: it.y0, x1: it.x1, y1: it.y1, items: [it] });
  423. });
  424. // a merge can make a group reach one it skipped: settle
  425. var changed = true;
  426. while (changed) {
  427. changed = false;
  428. for (var a = 0; a < groups.length && !changed; a++) {
  429. for (var b = a + 1; b < groups.length; b++) {
  430. var p = groups[a], q = groups[b];
  431. if (q.x0 <= p.x1 + gap && q.x1 >= p.x0 - gap && q.y0 <= p.y1 + gap && q.y1 >= p.y0 - gap) {
  432. p.items = p.items.concat(q.items);
  433. p.x0 = Math.min(p.x0, q.x0); p.y0 = Math.min(p.y0, q.y0);
  434. p.x1 = Math.max(p.x1, q.x1); p.y1 = Math.max(p.y1, q.y1);
  435. groups.splice(b, 1);
  436. changed = true;
  437. break;
  438. }
  439. }
  440. }
  441. }
  442. return groups;
  443. }
  444. function findFigures(graphics, runs, images, W, H) {
  445. var items = graphics.filter(function (g) {
  446. var w = g.x1 - g.x0, h = g.y1 - g.y0;
  447. return w * h >= 1 || w >= 6 || h >= 6;
  448. });
  449. if (!items.length) return [];
  450. var groups = clusterBoxes(items, 4);
  451. var figs = [];
  452. groups.forEach(function (g) {
  453. var w = g.x1 - g.x0, h = g.y1 - g.y0;
  454. if (w < 18 || h < 18 || (w * h > W * H * 0.85)) return;
  455. var n = 0, curvePts = 0, pattern = false;
  456. g.items.forEach(function (it) {
  457. n += it.n || 1;
  458. if (it.curve) curvePts += it.pts || 0;
  459. if (it.pattern) pattern = true;
  460. });
  461. if (!(n >= 6 || curvePts >= 24 || pattern)) return;
  462. var box = { x0: g.x0, y0: g.y0, x1: g.x1, y1: g.y1 };
  463. var inside = runs.filter(function (r) { return !r.used && inBox(runCx(r), runCy(r), box, 0.5); });
  464. var chars = 0, longRun = 0;
  465. inside.forEach(function (r) {
  466. chars += r.text.length;
  467. longRun = Math.max(longRun, r.text.length);
  468. });
  469. // text with lines of its own is a text box drawn round, not a picture
  470. if (n < 40 && (chars > 400 || longRun > 45)) return;
  471. // text that leaves the drawing's box stays text
  472. var pad = 1;
  473. box = { x0: box.x0 - pad, y0: box.y0 - pad, x1: box.x1 + pad, y1: box.y1 + pad };
  474. inside.forEach(function (r) {
  475. box.x0 = Math.min(box.x0, r.x0 - 0.5); box.x1 = Math.max(box.x1, r.x1 + 0.5);
  476. box.y0 = Math.min(box.y0, r.top - 0.5); box.y1 = Math.max(box.y1, r.bottom + 0.5);
  477. r.used = true;
  478. });
  479. images.forEach(function (im) {
  480. var cx = (im.x0 + im.x1) / 2, cy = (im.y0 + im.y1) / 2;
  481. if (inBox(cx, cy, box, 2)) {
  482. im.used = true;
  483. box.x0 = Math.min(box.x0, im.x0); box.x1 = Math.max(box.x1, im.x1);
  484. box.y0 = Math.min(box.y0, im.y0); box.y1 = Math.max(box.y1, im.y1);
  485. }
  486. });
  487. box.x0 = Math.max(0, box.x0); box.y0 = Math.max(0, box.y0);
  488. box.x1 = Math.min(W, box.x1); box.y1 = Math.min(H, box.y1);
  489. g.items.forEach(function (it) { it.used = true; });
  490. figs.push({ kind: "figure", x0: box.x0, y0: box.y0, x1: box.x1, y1: box.y1 });
  491. });
  492. return figs;
  493. }
  494. /* ---------------- one page ---------------- */
  495. function analyzePage(page) {
  496. var W = page.width, H = page.height;
  497. var prep = prepareRuns(page);
  498. var runs = prep.runs;
  499. var sh = classifyShapes(page.shapes, W, H);
  500. var tables = findTables(sh.hl, sh.vl, runs, W, H);
  501. var usedH = [], usedV = [];
  502. tables.forEach(function (t) {
  503. usedH = usedH.concat(t.comp.h);
  504. usedV = usedV.concat(t.comp.v);
  505. });
  506. var freeH = sh.hl.filter(function (l) { return usedH.indexOf(l) < 0; });
  507. var freeV = sh.vl.filter(function (l) { return usedV.indexOf(l) < 0; });
  508. // cell backgrounds
  509. sh.fills.forEach(function (f) {
  510. tables.forEach(function (t) {
  511. t.cells.forEach(function (c) {
  512. var ix = Math.min(c.x1, f.x1) - Math.max(c.x0, f.x0);
  513. var iy = Math.min(c.y1, f.y1) - Math.max(c.y0, f.y0);
  514. if (ix > 0 && iy > 0 && ix * iy >= (c.x1 - c.x0) * (c.y1 - c.y0) * 0.75) {
  515. c.bg = f.color;
  516. f.used = true;
  517. }
  518. });
  519. });
  520. });
  521. // underlines and strike-throughs
  522. var freeRuns = runs.filter(function (r) { return !r.used; });
  523. freeH.forEach(function (l) {
  524. if (l.b - l.a > W * 0.9) return;
  525. freeRuns.forEach(function (r) {
  526. var ov = Math.min(r.x1, l.b) - Math.max(r.x0, l.a);
  527. if (ov < (r.x1 - r.x0) * 0.6) return;
  528. var d = l.pos - r.base;
  529. if (d >= -r.size * 0.05 && d <= r.size * 0.3) { r.underline = true; l.used = true; }
  530. else if (d <= -r.size * 0.15 && d >= -r.size * 0.45 && l.w < r.size * 0.15) { r.strike = true; l.used = true; }
  531. });
  532. });
  533. freeH = freeH.filter(function (l) { return !l.used; });
  534. // what is left is drawing: figures, vector bullets, rules
  535. var graphics = sh.draws.slice();
  536. sh.fills.forEach(function (f) {
  537. if (f.used) return;
  538. var holds = freeRuns.some(function (r) { return inBox(runCx(r), runCy(r), f, 0.5); });
  539. if (!holds) graphics.push({ x0: f.x0, y0: f.y0, x1: f.x1, y1: f.y1, n: 1, color: f.color, fill: f });
  540. });
  541. freeH.concat(freeV).forEach(function (l) {
  542. var horiz = freeH.indexOf(l) >= 0;
  543. graphics.push(horiz ?
  544. { x0: l.a, x1: l.b, y0: l.pos - l.w / 2, y1: l.pos + l.w / 2, n: 1, rule: l, horiz: true } :
  545. { x0: l.pos - l.w / 2, x1: l.pos + l.w / 2, y0: l.a, y1: l.b, n: 1, rule: l });
  546. });
  547. var images = page.images.filter(function (im) {
  548. return (im.x1 - im.x0) >= 3 && (im.y1 - im.y0) >= 3;
  549. });
  550. // the same picture painted twice
  551. images = images.filter(function (im, i) {
  552. for (var j = i + 1; j < images.length; j++) {
  553. var o = images[j];
  554. if (Math.abs(o.x0 - im.x0) < 1 && Math.abs(o.y0 - im.y0) < 1 &&
  555. Math.abs(o.x1 - im.x1) < 1 && Math.abs(o.y1 - im.y1) < 1) return false;
  556. }
  557. return true;
  558. });
  559. // a background picture or a scan under its own text layer
  560. images.forEach(function (im) {
  561. var area = (im.x1 - im.x0) * (im.y1 - im.y0);
  562. if (area < W * H * 0.45) return;
  563. var over = 0;
  564. freeRuns.forEach(function (r) { if (inBox(runCx(r), runCy(r), im)) over += r.text.length; });
  565. if (over >= 20 || prep.ocr) im.used = true;
  566. });
  567. var figures = findFigures(graphics, freeRuns, images.filter(function (im) { return !im.used; }), W, H);
  568. freeRuns = freeRuns.filter(function (r) { return !r.used; });
  569. // shading: a filled box behind text
  570. sh.fills.forEach(function (f) {
  571. if (f.used || isWhite(f.color)) return;
  572. freeRuns.forEach(function (r) {
  573. if (!inBox(runCx(r), runCy(r), f, 0.5)) return;
  574. var area = (f.x1 - f.x0) * (f.y1 - f.y0);
  575. if (!r.bgBox || area < r.bgArea) {
  576. r.bg = f.color;
  577. r.bgBox = f;
  578. r.bgArea = area;
  579. }
  580. });
  581. });
  582. // vector bullets: a dot or a square just left of a line of text
  583. var synth = [];
  584. graphics.forEach(function (g) {
  585. if (g.used || g.rule) return;
  586. var w = g.x1 - g.x0, h = g.y1 - g.y0;
  587. if (w < 1.2 || h < 1.2 || w > 9 || h > 9 || w > h * 1.8 || h > w * 1.8) return;
  588. var cy = (g.y0 + g.y1) / 2;
  589. var next = null;
  590. freeRuns.forEach(function (r) {
  591. if (cy < r.top || cy > r.bottom) return;
  592. if (r.x0 < g.x1 - 0.5 || r.x0 > g.x1 + r.size * 3) return;
  593. if (!next || r.x0 < next.x0) next = r;
  594. });
  595. if (!next || w > next.size * 0.7) return;
  596. g.used = true;
  597. synth.push({
  598. text: g.curve ? "\u2022" : "\u25AA", x0: g.x0, x1: g.x1, base: next.base, size: next.size,
  599. top: next.top, bottom: next.bottom, font: next.font, color: g.color || [0, 0, 0],
  600. bold: false, italic: false, spaceBefore: false, letterSpacing: 0
  601. });
  602. });
  603. freeRuns = freeRuns.concat(synth);
  604. // white text that no longer has its dark box behind it
  605. freeRuns.forEach(function (r) {
  606. if (isLight(r.color) && (!r.bg || isLight(r.bg))) { r.color = [0, 0, 0]; r.bg = null; }
  607. });
  608. tables.forEach(function (t) {
  609. t.cells.forEach(function (c) {
  610. c.runs.forEach(function (r) {
  611. if (isLight(r.color) && (!c.bg || isLight(c.bg))) r.color = [0, 0, 0];
  612. });
  613. });
  614. });
  615. // links
  616. page.links.forEach(function (lk) {
  617. runs.forEach(function (r) {
  618. if (inBox(runCx(r), runCy(r), lk, 1)) r.url = lk.url;
  619. });
  620. });
  621. /* pictures: inline - an icon in a line of text, or a character the
  622. PDF's writer could only draw as a picture of itself (a PDF made
  623. without a font for the script has one per character) - or blocks
  624. of their own */
  625. var blocks = [];
  626. var inlineImgs = [];
  627. var small = images.filter(function (im) {
  628. var h = im.y1 - im.y0;
  629. return !im.used && h <= 48 && (im.x1 - im.x0) <= h * 4;
  630. });
  631. small.forEach(function (im) {
  632. var h = im.y1 - im.y0;
  633. var near = freeRuns.filter(function (r) {
  634. return r.bottom > im.y0 && r.top < im.y1 &&
  635. (Math.abs(r.x0 - im.x1) < r.size * 3 || Math.abs(im.x0 - r.x1) < r.size * 3);
  636. });
  637. var lineSize = near.length ? median(near.map(function (r) { return r.size; })) : 0;
  638. if (near.length && h <= lineSize * 2.2) {
  639. im.line = { base: median(near.map(function (r) { return r.base; })), size: lineSize, font: near[0].font };
  640. }
  641. });
  642. // a picture beside an inline one, as tall and on the same line, is
  643. // inline too: the rest of a run of character pictures
  644. var sameRow = function (a, b) {
  645. var ha = a.y1 - a.y0, hb = b.y1 - b.y0;
  646. return Math.abs(a.y1 - b.y1) <= ha * 0.25 && Math.abs(ha - hb) <= ha * 0.3 &&
  647. Math.min(Math.abs(a.x0 - b.x1), Math.abs(b.x0 - a.x1)) <= ha * 1.5;
  648. };
  649. var grew = true;
  650. while (grew) {
  651. grew = false;
  652. small.forEach(function (im) {
  653. if (im.line) return;
  654. for (var i = 0; i < small.length; i++) {
  655. var o = small[i];
  656. if (o === im || !o.line || !sameRow(im, o)) continue;
  657. im.line = { base: o.line.base + (im.y1 - o.y1), size: o.line.size, font: o.line.font };
  658. grew = true;
  659. return;
  660. }
  661. });
  662. }
  663. // a line drawn only in character pictures: two or more in a row
  664. small.forEach(function (im) {
  665. if (im.line) return;
  666. var row = small.filter(function (o) { return o !== im && !o.line && sameRow(im, o); });
  667. if (!row.length) return;
  668. var h = im.y1 - im.y0;
  669. im.line = { base: im.y1 - h * 0.17, size: h / 1.2, font: null };
  670. });
  671. images.forEach(function (im) {
  672. if (im.used) return;
  673. if (im.line) {
  674. inlineImgs.push({
  675. kind: "img", img: im, text: "", x0: im.x0, x1: im.x1, top: im.y0, bottom: im.y1,
  676. base: im.line.base, size: im.line.size, font: im.line.font, color: [0, 0, 0], inline: true,
  677. spaceBefore: !!im.spaceBefore
  678. });
  679. } else {
  680. blocks.push({ kind: "image", img: im, x0: im.x0, y0: im.y0, x1: im.x1, y1: im.y1 });
  681. }
  682. });
  683. tables.forEach(function (t) {
  684. blocks.push(t);
  685. // a picture inside a cell is that cell's
  686. blocks = blocks.filter(function (b) {
  687. if (b.kind !== "image") return true;
  688. var cell = cellFor(t, (b.x0 + b.x1) / 2, (b.y0 + b.y1) / 2);
  689. if (!cell) return true;
  690. cell.images.push(b);
  691. return false;
  692. });
  693. });
  694. figures.forEach(function (f) { blocks.push(f); });
  695. // lines along a picture's edges are its border (Google Docs draws a
  696. // picture outline as four lines)
  697. blocks.forEach(function (b) {
  698. if (b.kind !== "image") return;
  699. var along = function (l, pos, a0, a1) {
  700. return !l.used && Math.abs(l.pos - pos) <= Math.max(2, l.w) &&
  701. Math.min(l.b, a1) - Math.max(l.a, a0) >= (a1 - a0) * 0.8;
  702. };
  703. var edges = [];
  704. freeH.forEach(function (l) { if (along(l, b.y0, b.x0, b.x1) || along(l, b.y1, b.x0, b.x1)) edges.push(l); });
  705. freeV.forEach(function (l) { if (along(l, b.x0, b.y0, b.y1) || along(l, b.x1, b.y0, b.y1)) edges.push(l); });
  706. if (edges.length < 2) return;
  707. edges.forEach(function (l) {
  708. l.used = true;
  709. graphics.forEach(function (g) { if (g.rule === l) g.used = true; });
  710. });
  711. b.border = { w: edges[0].w, color: edges[0].color };
  712. });
  713. // a rule on its own line
  714. freeH.forEach(function (l) {
  715. if (l.used || l.b - l.a < W * 0.25) return;
  716. var g = graphics.filter(function (x) { return x.rule === l; })[0];
  717. if (g && g.used) return;
  718. var close = freeRuns.some(function (r) {
  719. return l.pos > r.top - 1.5 && l.pos < r.bottom + 1.5 && r.x1 > l.a && r.x0 < l.b;
  720. });
  721. if (!close) blocks.push({ kind: "hr", x0: l.a, x1: l.b, y0: l.pos - 0.5, y1: l.pos + 0.5, color: l.color, w: l.w });
  722. });
  723. var atoms = freeRuns.concat(inlineImgs);
  724. atoms.forEach(function (a) { a.kind = a.kind || "run"; a.y0 = a.top; a.y1 = a.bottom; });
  725. blocks.forEach(function (b) { b.top = b.y0; b.bottom = b.y1; });
  726. var regions = segment(atoms.concat(blocks), { left: null, right: null, col: -1 }, 0);
  727. regions.forEach(function (rg) { rg.items = linesOf(rg.atoms); });
  728. return {
  729. number: page.number, width: W, height: H, regions: regions,
  730. images: blocks.filter(function (b) { return b.kind === "image"; }).concat(inlineImgs),
  731. figures: figures, tables: tables
  732. };
  733. }
  734. /* ---------------- reading order ---------------- */
  735. function charsPerLine(atoms) {
  736. var byLine = {};
  737. atoms.forEach(function (a) {
  738. if (a.kind !== "run") return;
  739. var k = Math.round(a.base);
  740. byLine[k] = (byLine[k] || 0) + a.text.length;
  741. });
  742. var keys = Object.keys(byLine);
  743. if (!keys.length) return { lines: 0, avg: 0 };
  744. var tot = 0;
  745. keys.forEach(function (k) { tot += byLine[k]; });
  746. return { lines: keys.length, avg: tot / keys.length };
  747. }
  748. /* A column gutter: a vertical strip no atom crosses, running past at
  749. least three lines of real text (not a column of labels or numbers)
  750. on each side. The part of the region above and below the stretch it
  751. runs is cut off first, so a title across both columns does not hide
  752. the gutter under it. */
  753. function findGutter(atoms) {
  754. var x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
  755. var sizes = [];
  756. atoms.forEach(function (a) {
  757. x0 = Math.min(x0, a.x0); x1 = Math.max(x1, a.x1);
  758. y0 = Math.min(y0, a.y0); y1 = Math.max(y1, a.y1);
  759. if (a.kind === "run") sizes.push(a.size);
  760. });
  761. var w = x1 - x0;
  762. if (w < 100 || sizes.length < 6) return null;
  763. var size = median(sizes);
  764. var half = Math.max(2, size * 0.25);
  765. var best = null;
  766. for (var x = x0 + w * 0.15; x <= x1 - w * 0.15; x += 2) {
  767. var cross = atoms.filter(function (a) { return a.x0 < x + half && a.x1 > x - half; });
  768. cross.sort(function (a, b) { return a.y0 - b.y0; });
  769. var free = [];
  770. var at = y0;
  771. cross.forEach(function (a) {
  772. if (a.y0 > at) free.push([at, a.y0]);
  773. at = Math.max(at, a.y1);
  774. });
  775. if (y1 > at) free.push([at, y1]);
  776. free.forEach(function (iv) {
  777. if (iv[1] - iv[0] < size * 3) return;
  778. var left = [], right = [];
  779. atoms.forEach(function (a) {
  780. var cy = (a.y0 + a.y1) / 2;
  781. if (cy < iv[0] || cy > iv[1]) return;
  782. if (a.x1 <= x + half) left.push(a);
  783. else if (a.x0 >= x - half) right.push(a);
  784. });
  785. var L = charsPerLine(left), R = charsPerLine(right);
  786. var score = Math.min(L.lines, R.lines);
  787. if (score < 3 || L.avg < 12 || R.avg < 12) return;
  788. var lw = Math.max.apply(null, left.map(function (a) { return a.x1; })) - x0;
  789. var rw = x1 - Math.min.apply(null, right.map(function (a) { return a.x0; }));
  790. if (lw < w * 0.2 || rw < w * 0.2) return;
  791. var span = iv[1] - iv[0];
  792. if (!best || score > best.score || (score === best.score && span > best.span)) {
  793. best = { x: x, y0: iv[0], y1: iv[1], score: score, span: span, half: half };
  794. }
  795. });
  796. }
  797. return best;
  798. }
  799. function bandsOf(atoms) {
  800. var sizes = atoms.filter(function (a) { return a.kind === "run"; }).map(function (a) { return a.size; });
  801. var gap = Math.max(4, (sizes.length ? median(sizes) : 10) * 0.9);
  802. var sorted = atoms.slice().sort(function (a, b) { return a.y0 - b.y0; });
  803. var bands = [];
  804. var cur = null, bottom = -Infinity;
  805. sorted.forEach(function (a) {
  806. if (cur && a.y0 - bottom >= gap) { bands.push(cur); cur = null; }
  807. if (!cur) { cur = []; bottom = -Infinity; }
  808. cur.push(a);
  809. bottom = Math.max(bottom, a.y1);
  810. });
  811. if (cur) bands.push(cur);
  812. return bands;
  813. }
  814. function segment(atoms, bounds, depth) {
  815. if (!atoms.length) return [];
  816. if (depth < 8) {
  817. var g = findGutter(atoms);
  818. if (g) {
  819. var above = [], below = [], left = [], right = [];
  820. atoms.forEach(function (a) {
  821. var cy = (a.y0 + a.y1) / 2;
  822. if (cy < g.y0) above.push(a);
  823. else if (cy > g.y1) below.push(a);
  824. else if (a.x1 <= g.x + g.half) left.push(a);
  825. else right.push(a);
  826. });
  827. var lb = {
  828. left: bounds.left, col: 0,
  829. right: Math.max.apply(null, left.map(function (a) { return a.x1; }))
  830. };
  831. var rb = {
  832. left: Math.min.apply(null, right.map(function (a) { return a.x0; })), col: 1,
  833. right: bounds.right
  834. };
  835. return segment(above, bounds, depth + 1)
  836. .concat(segment(left, lb, depth + 1))
  837. .concat(segment(right, rb, depth + 1))
  838. .concat(segment(below, bounds, depth + 1));
  839. }
  840. var bands = bandsOf(atoms);
  841. if (bands.length > 1) {
  842. var out = [];
  843. bands.forEach(function (b) { out = out.concat(segment(b, bounds, depth + 1)); });
  844. return out;
  845. }
  846. }
  847. return [{ atoms: atoms, bounds: bounds }];
  848. }
  849. /* ---------------- lines ---------------- */
  850. function isLeader(t) { return /^[.\u2026\u00B7\u2219_\-\s]{4,}$/.test(t) && /[.\u2026\u00B7_]{3}/.test(t); }
  851. /* "Introduction ........" drawn as one run: the dots become a run of
  852. their own, which finishLine turns into a dotted tab stop */
  853. function splitLeaders(atoms) {
  854. var out = [];
  855. atoms.forEach(function (a) {
  856. var m = a.kind === "run" && !isLeader(a.text) &&
  857. a.text.match(/^(.*?\S)?(\s*[.\u2026\u00B7]{4,}\s*)(\S.*)?$/);
  858. if (!m || (!m[1] && !m[3])) { out.push(a); return; }
  859. var parts = [m[1], m[2], m[3]].filter(function (p) { return p; });
  860. var tot = a.text.length;
  861. var x = a.x0, w = a.x1 - a.x0;
  862. parts.forEach(function (p, i) {
  863. var piece = {};
  864. for (var k in a) piece[k] = a[k];
  865. piece.text = i === 0 || !isLeader(p) ? p.replace(/^\s+|\s+$/g, "") || p : p;
  866. piece.x0 = x;
  867. piece.x1 = x + w * p.length / tot;
  868. piece.spaceBefore = i === 0 ? a.spaceBefore : false;
  869. x = piece.x1;
  870. out.push(piece);
  871. });
  872. });
  873. return out;
  874. }
  875. function linesOf(atoms) {
  876. var text = splitLeaders(atoms.filter(function (a) { return a.kind === "run" || a.kind === "img"; }));
  877. var blocks = atoms.filter(function (a) { return a.kind !== "run" && a.kind !== "img"; });
  878. text.sort(function (a, b) { return a.base - b.base || a.x0 - b.x0; });
  879. var lines = [];
  880. text.forEach(function (a) {
  881. var hit = null;
  882. for (var i = lines.length - 1; i >= 0 && i >= lines.length - 4; i--) {
  883. var L = lines[i];
  884. var tol = Math.min(L.size, a.size) * 0.35;
  885. if (Math.abs(L.base - a.base) <= tol) { hit = L; break; }
  886. var ov = Math.min(L.bottom, a.bottom) - Math.max(L.top, a.top);
  887. var hmin = Math.min(L.bottom - L.top, a.bottom - a.top);
  888. // a superscript or a smaller run sitting inside the line
  889. if (ov > hmin * 0.6 && (a.size < L.size * 0.85 || L.size < a.size * 0.85)) { hit = L; break; }
  890. }
  891. if (hit) {
  892. hit.atoms.push(a);
  893. hit.top = Math.min(hit.top, a.top);
  894. hit.bottom = Math.max(hit.bottom, a.bottom);
  895. if (a.kind === "run" && a.size > hit.size) { hit.size = a.size; hit.base = a.base; }
  896. } else {
  897. lines.push({ atoms: [a], base: a.base, size: a.size, top: a.top, bottom: a.bottom });
  898. }
  899. });
  900. lines.forEach(finishLine);
  901. var items = lines.filter(function (l) { return l.tokens.length; });
  902. items = items.concat(blocks);
  903. items.sort(function (a, b) { return (a.kind ? a.y0 : a.top) - (b.kind ? b.y0 : b.top); });
  904. return items;
  905. }
  906. /* A line's atoms in x order, as tokens: text with the spaces put back
  907. (a PDF often draws none, only a gap), and tab breaks where the gap is
  908. a column's worth. */
  909. function finishLine(L) {
  910. L.atoms.sort(function (a, b) { return a.x0 - b.x0; });
  911. var runs = L.atoms.filter(function (a) { return a.kind === "run"; });
  912. if (runs.length) {
  913. // the line's own size and baseline: its main text, not a raised note
  914. var bySize = {};
  915. runs.forEach(function (r) { var k = r1(r.size); bySize[k] = (bySize[k] || 0) + r.text.length; });
  916. var main = Object.keys(bySize).sort(function (a, b) { return bySize[b] - bySize[a]; })[0];
  917. L.size = parseFloat(main);
  918. var mainRuns = runs.filter(function (r) { return Math.abs(r.size - L.size) < 0.2; });
  919. L.base = median(mainRuns.map(function (r) { return r.base; }));
  920. }
  921. var gaps = [];
  922. for (var i = 1; i < L.atoms.length; i++) gaps.push(L.atoms[i].x0 - L.atoms[i - 1].x1);
  923. var mg = gaps.length ? median(gaps.filter(function (g) { return g > 0; })) : 0;
  924. var tabGap = Math.max(L.size * 1.8, mg * 3, 9);
  925. var tokens = [];
  926. var segs = [];
  927. var seg = null;
  928. var prev = null;
  929. L.atoms.forEach(function (a) {
  930. var gap = prev ? a.x0 - prev.x1 : 0;
  931. if (a.kind === "run" && isLeader(a.text)) {
  932. // a dotted leader is the look of a tab stop, not text
  933. if (seg) seg.leader = true;
  934. prev = a;
  935. return;
  936. }
  937. // code: in a fixed-pitch font a gap is so many spaces, never a tab
  938. var mono = prev && prev.kind === "run" && a.kind === "run" && prev.font && a.font &&
  939. prev.font.mono && a.font.mono && Math.abs(prev.size - a.size) < 0.5;
  940. if (mono && seg && !seg.leader) {
  941. var cw = (prev.x1 - prev.x0) / Math.max(1, Array.from ? Array.from(prev.text).length : prev.text.length);
  942. var n = cw > 0 ? Math.round(gap / cw) : 0;
  943. if (/\s$/.test(prev.text) || /^\s/.test(a.text)) n = Math.max(0, n - 1);
  944. if (n > 0) tokens.push({ space: true, next: a, n: n });
  945. tokens.push({ run: a });
  946. seg.x1 = Math.max(seg.x1, a.x1);
  947. prev = a;
  948. return;
  949. }
  950. if (!seg || gap > tabGap || (seg && seg.leader)) {
  951. if (seg) tokens.push({ tab: true, leader: !!seg.leader });
  952. seg = { x0: a.x0, x1: a.x1, leader: false };
  953. segs.push(seg);
  954. } else if (prev && a.kind === "run" && prev.kind === "run") {
  955. var pc = lastCp(prev.text), nc = cpOf(a.text, 0);
  956. var cjk = isCJK(pc) && isCJK(nc);
  957. var need = a.spaceBefore ? !cjk || gap > a.size * 0.5 :
  958. (cjk ? gap > a.size * 0.8 : gap > Math.min(prev.size, a.size) * ((isCJK(pc) || isCJK(nc)) ? 0.25 : 0.13));
  959. if (need && !/\s$/.test(prev.text) && !/^\s/.test(a.text)) tokens.push({ space: true, next: a });
  960. } else if (prev && (gap > L.size * 0.2 || a.spaceBefore)) {
  961. tokens.push({ space: true, next: a });
  962. }
  963. tokens.push(a.kind === "img" ? { img: a } : { run: a });
  964. seg.x1 = Math.max(seg.x1, a.x1);
  965. prev = a;
  966. });
  967. // a tab still pending after the last text (a trailing leader) is dropped
  968. L.tokens = tokens;
  969. L.segs = segs;
  970. L.x0 = segs.length ? segs[0].x0 : 0;
  971. L.x1 = segs.length ? segs[segs.length - 1].x1 : 0;
  972. L.text = tokens.map(function (t) { return t.run ? t.run.text : t.space ? " " : t.tab ? "\t" : ""; }).join("");
  973. delete L.atoms;
  974. }
  975. /* ---------------- paragraphs ---------------- */
  976. var BULLET_RE = /^([\u2022\u25CF\u25CB\u25E6\u25AA\u25A0\u25A1\u25B8\u25BA\u25B6\u27A2\u27A4\u2713\u2714\u2756\u25C6\u25C7\u2043\u2219\u00B7\u2013\u2014\-*\u2023\u2794\u21E8])\s*/;
  977. var NUMBER_RE = /^(\(?)(\d{1,3}|[a-z]|[A-Z]|[ivxlc]{1,6}|[IVXLC]{1,6})([.)\u3001\uFF0E])(?=\s|$)/;
  978. var NUMBER_PAREN_RE = /^\((\d{1,3}|[a-z]|[ivx]{1,5})\)/;
  979. /* What a line starts with when it is a list item, and where its text
  980. starts. The marker is read off the line's first word, which may be
  981. several runs ("1" and "." drawn apart, a bullet glued to its text). */
  982. function listMarker(L) {
  983. var toks = L.tokens;
  984. var word = "", i;
  985. var starts = []; // [token index, offset of that token in word]
  986. for (i = 0; i < toks.length; i++) {
  987. var t = toks[i];
  988. if (t.space || t.tab) break;
  989. if (!t.run) { if (!word) return null; break; }
  990. starts.push([i, word.length]);
  991. var ws = t.run.text.search(/\s/);
  992. if (ws === 0) break;
  993. if (ws > 0) { word += t.run.text.substring(0, ws); break; }
  994. word += t.run.text;
  995. }
  996. if (!word || !starts.length) return null;
  997. var info = null, mlen = 0;
  998. var m = word.match(BULLET_RE);
  999. if (m) {
  1000. info = { kind: "bullet", marker: m[1] };
  1001. mlen = m[1].length;
  1002. // a dash or an asterisk only when it stands apart from the text,
  1003. // the way a list draws it (a dash in a wrapped sentence does not)
  1004. if (/[-*–—]/.test(m[1]) && word.length !== 1) return null;
  1005. } else {
  1006. var p = word.match(NUMBER_PAREN_RE);
  1007. var n = word.match(NUMBER_RE);
  1008. if (p && p[0].length === word.length) info = { kind: "number", raw: p[1], prefix: "(", suffix: ")" };
  1009. else if (n && n[0].length === word.length) info = { kind: "number", raw: n[2], prefix: n[1] || "", suffix: n[3] };
  1010. if (!info) return null;
  1011. mlen = word.length;
  1012. info.fmt = numberFormat(info.raw);
  1013. info.value = numberValue(info.raw, info.fmt);
  1014. }
  1015. // the token and character the item's text starts at
  1016. var markEnd = null, textX = null, markTok = starts[0][0];
  1017. for (var k = starts.length - 1; k >= 0; k--) {
  1018. if (starts[k][1] < mlen) {
  1019. markTok = starts[k][0];
  1020. var tk = toks[starts[k][0]].run;
  1021. var within = mlen - starts[k][1];
  1022. var frac = within / Math.max(1, tk.text.length);
  1023. markEnd = tk.x0 + (tk.x1 - tk.x0) * Math.min(1, frac);
  1024. if (within < tk.text.replace(/\s+$/, "").length) {
  1025. // the text goes on in the same run
  1026. info.splitTok = starts[k][0];
  1027. info.split = within;
  1028. textX = markEnd;
  1029. }
  1030. break;
  1031. }
  1032. }
  1033. if (textX === null) {
  1034. for (var q = markTok + 1; q < toks.length; q++) {
  1035. var tq = toks[q];
  1036. if (tq.run || tq.img) {
  1037. // a glued-on bullet's text is the next run, a spaced one's
  1038. // the one after the gap
  1039. textX = (tq.run || tq.img).x0;
  1040. info.skip = q;
  1041. break;
  1042. }
  1043. }
  1044. if (mlen < word.length && info.skip === undefined) return null;
  1045. }
  1046. if (textX === null) return null;
  1047. info.markerX = L.x0;
  1048. info.textX = textX;
  1049. info.gap = textX - markEnd;
  1050. if (/[-*–—]/.test(info.marker || "") && info.gap < L.size * 0.4) return null;
  1051. return info;
  1052. }
  1053. function numberFormat(raw) {
  1054. if (/^\d+$/.test(raw)) return "decimal";
  1055. if (/^[ivxlc]+$/.test(raw) && raw.length > 1 || raw === "i") return "lowerRoman";
  1056. if (/^[IVXLC]+$/.test(raw) && raw.length > 1 || raw === "I") return "upperRoman";
  1057. if (/^[a-z]$/.test(raw)) return "lowerLetter";
  1058. return "upperLetter";
  1059. }
  1060. function numberValue(raw, fmt) {
  1061. if (fmt === "decimal") return parseInt(raw, 10);
  1062. if (fmt === "lowerLetter" || fmt === "upperLetter") return raw.toLowerCase().charCodeAt(0) - 96;
  1063. var map = { i: 1, v: 5, x: 10, l: 50, c: 100 };
  1064. var s = raw.toLowerCase(), v = 0;
  1065. for (var i = 0; i < s.length; i++) {
  1066. var a = map[s[i]], b = map[s[i + 1]] || 0;
  1067. v += a < b ? -a : a;
  1068. }
  1069. return v;
  1070. }
  1071. function styleOf(r) {
  1072. return [r.famKey, r1(r.size), r.bold ? 1 : 0, r.italic ? 1 : 0].join("|");
  1073. }
  1074. function lineStyle(L) {
  1075. var n = {};
  1076. L.tokens.forEach(function (t) {
  1077. if (!t.run) return;
  1078. var k = styleOf(t.run);
  1079. n[k] = (n[k] || 0) + t.run.text.length;
  1080. });
  1081. var best = null;
  1082. Object.keys(n).forEach(function (k) { if (!best || n[k] > n[best]) best = k; });
  1083. return best || "";
  1084. }
  1085. function allBold(L) {
  1086. var any = false;
  1087. for (var i = 0; i < L.tokens.length; i++) {
  1088. var t = L.tokens[i];
  1089. if (!t.run || !/\S/.test(t.run.text)) continue;
  1090. any = true;
  1091. if (!t.run.bold) return false;
  1092. }
  1093. return any;
  1094. }
  1095. /* How wide the line's first word is - what would have had to fit at
  1096. the end of the line above for the writer to leave it there. A word
  1097. may be many runs (Google Docs draws every glyph by itself). */
  1098. function firstWordWidth(L) {
  1099. var x0 = null, x1 = null;
  1100. for (var i = 0; i < L.tokens.length; i++) {
  1101. var t = L.tokens[i];
  1102. if (t.space || t.tab) { if (x0 !== null) break; continue; }
  1103. if (t.img) {
  1104. if (x0 === null) return t.img.x1 - t.img.x0;
  1105. break;
  1106. }
  1107. var r = t.run;
  1108. if (!r) continue;
  1109. var txt = r.text;
  1110. // a CJK line may break before any character
  1111. if (isCJK(cpOf(txt, 0))) {
  1112. var cw = (r.x1 - r.x0) / Math.max(1, txt.length);
  1113. return x0 === null ? cw * 1.2 : (r.x0 - x0) + cw;
  1114. }
  1115. if (x0 === null) x0 = r.x0;
  1116. var cut = txt.search(/\s/);
  1117. if (cut >= 0) {
  1118. x1 = r.x0 + (r.x1 - r.x0) * cut / Math.max(1, txt.length);
  1119. break;
  1120. }
  1121. x1 = r.x1;
  1122. }
  1123. if (x0 === null) return L.size * 2;
  1124. return x1 - x0;
  1125. }
  1126. var ENDS_SENTENCE = /[.!?:;\u3002\uFF01\uFF1F\uFF1A\uFF1B"\u201D\u300D\u300F)]$/;
  1127. /* Lines of one region into paragraphs (and the blocks between them) */
  1128. function paragraphsOf(region, colL, colR) {
  1129. var items = region.items;
  1130. var out = [];
  1131. var para = null;
  1132. var colW = colR - colL;
  1133. function flush() { if (para) { out.push(para); para = null; } }
  1134. function lineFull(A, B) {
  1135. var room = colR - A.x1;
  1136. return room < firstWordWidth(B) + A.size * 0.6;
  1137. }
  1138. function centered(L) {
  1139. var c = (L.x0 + L.x1) / 2;
  1140. return L.x0 > colL + L.size && Math.abs(c - (colL + colR) / 2) <= Math.max(3, colW * 0.025);
  1141. }
  1142. items.forEach(function (it) {
  1143. if (it.kind) { flush(); out.push({ block: it }); return; }
  1144. var L = it;
  1145. L.marker = listMarker(L);
  1146. if (L.marker && L.marker.kind === "number" && L.marker.gap < L.size * 0.25 && L.marker.skip === undefined) {
  1147. // "1.5 litres" is a number, not an item - unless it hangs
  1148. L.marker.weak = true;
  1149. }
  1150. L.style = lineStyle(L);
  1151. L.bold = allBold(L);
  1152. L.hasTab = L.tokens.some(function (t) { return t.tab; });
  1153. if (para && continues(para, L)) {
  1154. para.lines.push(L);
  1155. return;
  1156. }
  1157. flush();
  1158. para = { lines: [L] };
  1159. });
  1160. flush();
  1161. function continues(P, L) {
  1162. var A = P.lines[P.lines.length - 1];
  1163. if (L.hasTab || A.hasTab) return false;
  1164. if (L.marker && !L.marker.weak) return false;
  1165. if (L.style !== A.style) {
  1166. // the same size and family with a word in bold is still one
  1167. // paragraph; a size or a whole-line weight change is not
  1168. var as = A.style.split("|"), ls = L.style.split("|");
  1169. if (as[0] !== ls[0] || Math.abs(parseFloat(as[1]) - parseFloat(ls[1])) > 0.6) return false;
  1170. if (A.bold !== L.bold) return false;
  1171. }
  1172. var pitch = L.base - A.base;
  1173. if (pitch <= A.size * 0.6) return false;
  1174. if (P.lines.length >= 2) {
  1175. var pp = P.lines[1].base - P.lines[0].base;
  1176. if (Math.abs(pitch - pp) > Math.max(1.5, pp * 0.2)) return false;
  1177. } else {
  1178. // a line hanging under a list item's text may sit on a looser
  1179. // pitch (a slide's) than a paragraph break would allow
  1180. var hangs = P.lines[0].marker && !P.lines[0].marker.weak &&
  1181. Math.abs(L.x0 - P.lines[0].marker.textX) <= Math.max(1.5, L.size * 0.3);
  1182. if (pitch > Math.max(A.size, L.size) * (hangs ? 2.2 : 1.75)) return false;
  1183. }
  1184. var bothCentered = centered(A) && centered(L) &&
  1185. Math.abs((A.x0 + A.x1) / 2 - (L.x0 + L.x1) / 2) < L.size;
  1186. if (bothCentered && P.lines.every(centered)) { P.breaks = true; return true; }
  1187. var tol = Math.max(1.5, L.size * 0.3);
  1188. var first = P.lines[0];
  1189. if (!lineFull(A, L)) {
  1190. /* a line in a box narrower than the column (a slide's text
  1191. box) never reaches its edge; it still carries on when it
  1192. hangs under a list item's text, or when the line above
  1193. did not end a sentence and this one starts in lower case */
  1194. var cont = P.lines.length >= 2 ? P.lines[1].x0 : (first.marker ? first.marker.textX : A.x0);
  1195. if (Math.abs(L.x0 - cont) > tol) return false;
  1196. if (first.marker && !first.marker.weak) return true;
  1197. var at = A.text.replace(/\s+$/, "");
  1198. return !ENDS_SENTENCE.test(at) && /^[a-z]/.test(L.text.replace(/^\s+/, ""));
  1199. }
  1200. if (P.lines.length >= 2) return Math.abs(L.x0 - P.lines[1].x0) <= tol;
  1201. if (Math.abs(L.x0 - A.x0) <= tol) return true;
  1202. if (L.x0 < A.x0 && A.x0 - L.x0 <= L.size * 6) return true; // first-line indent
  1203. if (first.marker && Math.abs(L.x0 - first.marker.textX) <= tol) return true; // hanging
  1204. return false;
  1205. }
  1206. // the geometry of each paragraph
  1207. out.forEach(function (P) {
  1208. if (P.block) return;
  1209. var Ls = P.lines;
  1210. var first = Ls[0], last = Ls[Ls.length - 1];
  1211. P.firstBase = first.base;
  1212. P.lastBase = last.base;
  1213. P.top = Math.min.apply(null, Ls.map(function (l) { return l.top; }));
  1214. P.bottom = Math.max.apply(null, Ls.map(function (l) { return l.bottom; }));
  1215. P.size = median(Ls.map(function (l) { return l.size; }));
  1216. if (Ls.length > 1) P.pitch = median(Ls.slice(1).map(function (l, i) { return l.base - Ls[i].base; }));
  1217. P.x0 = Math.min.apply(null, Ls.map(function (l) { return l.x0; }));
  1218. P.x1 = Math.max.apply(null, Ls.map(function (l) { return l.x1; }));
  1219. P.bold = Ls.every(function (l) { return l.bold; });
  1220. P.chars = Ls.reduce(function (n, l) { return n + l.text.length; }, 0);
  1221. P.marker = first.marker && !first.marker.weak ? first.marker : null;
  1222. var cont = Ls.length > 1 ? Ls[1].x0 : first.x0;
  1223. P.align = "left";
  1224. var tolC = Math.max(3, colW * 0.025);
  1225. if (Ls.every(centered) && (Ls.length > 1 || first.x1 < colR - first.size)) {
  1226. P.align = "center";
  1227. } else if (Ls.every(function (l) { return Math.abs(l.x1 - colR) <= 2; }) && first.x0 > colL + first.size * 2) {
  1228. P.align = "right";
  1229. } else if (Ls.length >= 3) {
  1230. // ragged text never ends two lines on the same point
  1231. var inner = Ls.slice(0, -1);
  1232. var spread = Math.max.apply(null, inner.map(function (l) { return l.x1; })) -
  1233. Math.min.apply(null, inner.map(function (l) { return l.x1; }));
  1234. if (spread <= 1.2 && inner[0].x1 > colR - colW * 0.1) P.align = "justify";
  1235. } else if (Ls.length === 2 && Math.abs(first.x1 - colR) <= 1 && Math.abs(Ls[1].x0 - first.x0) <= tolC) {
  1236. P.align = "justify";
  1237. }
  1238. if (P.align === "center" || P.align === "right") {
  1239. P.marginLeft = 0;
  1240. P.indent = 0;
  1241. if (P.lines.length > 1) P.breaks = true;
  1242. } else if (P.marker) {
  1243. P.marginLeft = P.marker.textX - colL;
  1244. P.hang = P.marker.textX - P.marker.markerX;
  1245. } else {
  1246. P.marginLeft = Math.max(0, cont - colL);
  1247. P.indent = first.x0 - cont;
  1248. }
  1249. });
  1250. return out;
  1251. }
  1252. /* ---------------- the document ---------------- */
  1253. function lineZoneKey(L) {
  1254. return L.text.replace(/\d+/g, "#").replace(/\s+/g, " ").trim().toLowerCase();
  1255. }
  1256. var PAGE_NUM_RE = /^(page\s*|p\.\s*|\u7B2C\s*)?([\-\u2013\u2014]\s*)?(\d{1,4}|[ivxlc]{1,7})(\s*[\-\u2013\u2014])?(\s*(of|\/|\u9801|\u9875)\s*\d{1,4})?(\s*\u9801|\s*\u9875)?$/i;
  1257. /* A picture in the top or bottom band at the same place on most pages
  1258. is the page's letterhead or footer art */
  1259. function blockZoneKey(b, pg) {
  1260. if (b.kind !== "image" && b.kind !== "figure") return "";
  1261. var zone = b.y1 < pg.height * 0.15 ? "h" : b.y0 > pg.height * 0.85 ? "f" : "";
  1262. if (!zone) return "";
  1263. return zone + ":pic:" + [b.x0, b.y0, b.x1, b.y1].map(function (v) { return Math.round(v / 3); }).join(",");
  1264. }
  1265. function stripRunning(pages) {
  1266. var res = { header: "", footer: "", pageNumbers: false, headerTop: null, footerBottom: null,
  1267. headerPic: null, footerPic: null };
  1268. var count = {};
  1269. var multi = pages.length >= 2;
  1270. pages.forEach(function (pg) {
  1271. var seen = {};
  1272. pg.regions.forEach(function (rg) {
  1273. rg.items.forEach(function (L) {
  1274. if (L.kind) {
  1275. var bk = blockZoneKey(L, pg);
  1276. if (bk && !seen[bk]) { seen[bk] = true; count[bk] = (count[bk] || 0) + 1; }
  1277. return;
  1278. }
  1279. var zone = L.bottom < pg.height * 0.1 ? "h" : L.top > pg.height * 0.9 ? "f" : "";
  1280. if (!zone) return;
  1281. var k = zone + ":" + lineZoneKey(L);
  1282. if (seen[k]) return;
  1283. seen[k] = true;
  1284. count[k] = (count[k] || 0) + 1;
  1285. });
  1286. });
  1287. });
  1288. var need = Math.max(2, Math.ceil(pages.length * 0.4));
  1289. pages.forEach(function (pg) {
  1290. pg.regions.forEach(function (rg) {
  1291. rg.items = rg.items.filter(function (L) {
  1292. if (L.kind) {
  1293. var bk = blockZoneKey(L, pg);
  1294. if (!bk || !multi || count[bk] < need) return true;
  1295. if (bk.charAt(0) === "h") { if (!res.headerPic) res.headerPic = L; }
  1296. else if (!res.footerPic) res.footerPic = L;
  1297. return false;
  1298. }
  1299. var zone = L.bottom < pg.height * 0.1 ? "h" : L.top > pg.height * 0.9 ? "f" : "";
  1300. if (!zone) return true;
  1301. var text = L.text.trim();
  1302. var isNum = text.length <= 16 && PAGE_NUM_RE.test(text);
  1303. var repeated = multi && count[zone + ":" + lineZoneKey(L)] >= need;
  1304. if (isNum && (repeated || zone === "f" || multi)) {
  1305. res.pageNumbers = true;
  1306. if (zone === "f") res.footerBottom = res.footerBottom === null ? pg.height - L.bottom : Math.min(res.footerBottom, pg.height - L.bottom);
  1307. return false;
  1308. }
  1309. if (!repeated) return true;
  1310. var clean = text.replace(/\s*(page\s*)?\d{1,4}(\s*(of|\/)\s*\d{1,4})?\s*$/i, "").trim();
  1311. if (clean !== text) res.pageNumbers = true;
  1312. if (zone === "h") {
  1313. if (!res.header) res.header = clean;
  1314. res.headerTop = res.headerTop === null ? L.top : Math.min(res.headerTop, L.top);
  1315. } else {
  1316. if (!res.footer) res.footer = clean;
  1317. res.footerBottom = res.footerBottom === null ? pg.height - L.bottom : Math.min(res.footerBottom, pg.height - L.bottom);
  1318. }
  1319. return false;
  1320. });
  1321. });
  1322. pg.regions = pg.regions.filter(function (rg) { return rg.items.length; });
  1323. });
  1324. return res;
  1325. }
  1326. /* The text block: the edges most lines reach, over every page at once
  1327. (a page of short lines says nothing about where the margin is), and
  1328. the top and bottom of the fuller pages */
  1329. function textBounds(pages) {
  1330. var xs0 = [], xs1 = [], tops = [], bots = [];
  1331. pages.forEach(function (pg) {
  1332. var top = Infinity, bottom = -Infinity;
  1333. pg.regions.forEach(function (rg) {
  1334. rg.items.forEach(function (it) {
  1335. if (it.kind === "hr") return;
  1336. // the margins are where text goes: a picture or a rule
  1337. // may run to the edge of the paper
  1338. if (it.kind) return;
  1339. xs0.push(it.x0);
  1340. xs1.push(it.x1);
  1341. top = Math.min(top, it.top);
  1342. bottom = Math.max(bottom, it.bottom);
  1343. });
  1344. });
  1345. if (top < Infinity) { tops.push(top); bots.push(bottom); }
  1346. });
  1347. if (!xs0.length) return null;
  1348. return {
  1349. left: pct(xs0, 0.03),
  1350. right: pct(xs1, 0.97),
  1351. top: pct(tops, 0.25),
  1352. bottom: pct(bots, 0.95),
  1353. pages: tops.length
  1354. };
  1355. }
  1356. function pickPaper(Wpt, Hpt) {
  1357. var w = Wpt / PT_PER_MM, h = Hpt / PT_PER_MM;
  1358. var land = w > h;
  1359. var a = Math.min(w, h), b = Math.max(w, h);
  1360. var best = "A4", bestD = Infinity;
  1361. Object.keys(PAGE_SIZES).forEach(function (k) {
  1362. var d = Math.abs(PAGE_SIZES[k][0] - a) + Math.abs(PAGE_SIZES[k][1] - b);
  1363. if (d < bestD) { bestD = d; best = k; }
  1364. });
  1365. var s = PAGE_SIZES[best];
  1366. return { size: best, orientation: land ? "landscape" : "portrait", w: land ? s[1] : s[0], h: land ? s[0] : s[1] };
  1367. }
  1368. /* ---------------- styles ---------------- */
  1369. function familyOf(r) {
  1370. var f = r.font || {};
  1371. var fam = f.family;
  1372. if (!fam) fam = f.mono ? "Courier New" : f.serif ? "Times New Roman" : "Arial";
  1373. if (fam === "Helvetica") fam = "Arial";
  1374. return fam;
  1375. }
  1376. function stackOf(fam, r) {
  1377. var f = (r && r.font) || {};
  1378. var generic = f.mono ? "monospace" : f.serif ? "serif" : "sans-serif";
  1379. if (window.OfficeFonts && OfficeFonts.stack) return OfficeFonts.stack(fam, generic);
  1380. return '"' + fam + '", ' + generic;
  1381. }
  1382. function sizeKey(v) { return Math.round(v * 2) / 2; }
  1383. /* the editor's line height for a font stack, as a share of the size -
  1384. what DocsLayout lays a line out with */
  1385. var ratioCache = {};
  1386. function ratioOf(stack) {
  1387. if (ratioCache[stack]) return ratioCache[stack];
  1388. var r = { asc: 0.905, desc: 0.212 };
  1389. try {
  1390. if (window.DocsLayout && DocsLayout.fontRatios) r = DocsLayout.fontRatios(stack);
  1391. } catch (e) { }
  1392. ratioCache[stack] = r;
  1393. return r;
  1394. }
  1395. function loadFonts(stacks) {
  1396. var list = Object.keys(stacks);
  1397. var fams = list.map(function (s) { return stacks[s]; });
  1398. var sub = (window.OfficeFonts && OfficeFonts.substitute) ? OfficeFonts.substitute(fams) : Promise.resolve();
  1399. return Promise.resolve(sub).catch(function () { }).then(function () {
  1400. if (!document.fonts || !document.fonts.load) return;
  1401. return Promise.all(list.map(function (s) {
  1402. return Promise.all([
  1403. document.fonts.load("16px " + s, "Hxg\u4E2D"),
  1404. document.fonts.load("bold 16px " + s, "Hxg\u4E2D")
  1405. ]).catch(function () { });
  1406. }));
  1407. }).then(function () {
  1408. return new Promise(function (res) { setTimeout(res, 30); });
  1409. }).then(function () {
  1410. if (window.DocsLayout && DocsLayout.clearMetrics) DocsLayout.clearMetrics();
  1411. ratioCache = {};
  1412. });
  1413. }
  1414. /* ---------------- HTML ---------------- */
  1415. function el(tag, style, cls) {
  1416. var e = document.createElement(tag);
  1417. if (style) e.setAttribute("style", style);
  1418. if (cls) e.className = cls;
  1419. return e;
  1420. }
  1421. function Emitter(ctx) {
  1422. this.ctx = ctx;
  1423. }
  1424. // the runs of a line range as spans, the paragraph's own look left off
  1425. Emitter.prototype.inline = function (host, tokens, base, opts) {
  1426. var ctx = this.ctx;
  1427. var link = null, linkUrl = null;
  1428. var target = host;
  1429. function place(node, url) {
  1430. if (url !== linkUrl) {
  1431. linkUrl = url || null;
  1432. if (url) {
  1433. link = el("a", "color:inherit;text-decoration:inherit;");
  1434. link.setAttribute("href", url);
  1435. host.appendChild(link);
  1436. target = link;
  1437. } else {
  1438. link = null;
  1439. target = host;
  1440. }
  1441. }
  1442. target.appendChild(node);
  1443. }
  1444. var buf = null; // [styleKey, url, text, run]
  1445. var pendingSpace = false; // a space after a picture, for what follows
  1446. function flushBuf() {
  1447. if (!buf) return;
  1448. var r = buf[3];
  1449. var css = runCss(r, base, ctx);
  1450. var node;
  1451. var script = r.script;
  1452. if (script) {
  1453. node = document.createElement(script);
  1454. if (css) node.setAttribute("style", css);
  1455. node.appendChild(document.createTextNode(buf[2]));
  1456. } else if (css) {
  1457. node = el("span", css);
  1458. node.appendChild(document.createTextNode(buf[2]));
  1459. } else {
  1460. node = document.createTextNode(buf[2]);
  1461. }
  1462. place(node, buf[1]);
  1463. buf = null;
  1464. }
  1465. tokens.forEach(function (t) {
  1466. if (t.tab) {
  1467. flushBuf();
  1468. var tab = el("span", null, "doc-tab");
  1469. tab.appendChild(document.createTextNode("\t"));
  1470. place(tab, null);
  1471. return;
  1472. }
  1473. if (t.br) {
  1474. flushBuf();
  1475. place(document.createElement("br"), null);
  1476. return;
  1477. }
  1478. if (t.img) {
  1479. flushBuf();
  1480. var im = t.img.img;
  1481. if (!im.src) return;
  1482. if (pendingSpace) {
  1483. place(document.createTextNode(" "), null);
  1484. pendingSpace = false;
  1485. }
  1486. var w = im.x1 - im.x0, h = im.y1 - im.y0;
  1487. // as far below the baseline as it reaches in the PDF
  1488. var drop = t.img.bottom - t.img.base;
  1489. var img = el("img", "width:" + pt(w) + ";height:" + pt(h) + ";" +
  1490. (drop > 0.3 ? "vertical-align:" + pt(-drop) + ";" : ""));
  1491. img.setAttribute("src", im.src);
  1492. place(img, t.img.url || null);
  1493. return;
  1494. }
  1495. if (t.space) {
  1496. if (buf) buf[2] += t.n > 1 ? new Array(t.n + 1).join(" ") : " ";
  1497. else pendingSpace = true;
  1498. return;
  1499. }
  1500. var r = t.run;
  1501. if (!r) return;
  1502. var text = t.text !== undefined ? t.text : r.text;
  1503. if (!text) return;
  1504. var k = runKey(r);
  1505. var url = r.url || null;
  1506. if (buf && buf[0] === k && buf[1] === url) { buf[2] += text; return; }
  1507. flushBuf();
  1508. if (pendingSpace) {
  1509. text = " " + text;
  1510. pendingSpace = false;
  1511. }
  1512. buf = [k, url, text, r];
  1513. });
  1514. flushBuf();
  1515. };
  1516. function runKey(r) {
  1517. return [r.famKey, sizeKey(r.size), r.bold ? 1 : 0, r.italic ? 1 : 0, hex(r.color), r.underline ? 1 : 0,
  1518. r.strike ? 1 : 0, r.bg ? hex(r.bg) : "", r.script || "", r1(r.letterSpacing || 0)].join("|");
  1519. }
  1520. function runCss(r, base, ctx) {
  1521. var css = "";
  1522. if (r.famKey !== base.famKey) css += "font-family:" + ctx.stacks[r.famKey] + ";";
  1523. if (!r.script && Math.abs(sizeKey(r.size) - base.size) > 0.01) css += "font-size:" + sizeKey(r.size) + "pt;";
  1524. if (r.script) css += "font-size:" + sizeKey(r.size) + "pt;";
  1525. if (!!r.bold !== !!base.bold) css += "font-weight:" + (r.bold ? "bold" : "normal") + ";";
  1526. if (!!r.italic !== !!base.italic) css += "font-style:" + (r.italic ? "italic" : "normal") + ";";
  1527. var c = hex(r.color);
  1528. if (c !== base.color) css += "color:" + c + ";";
  1529. var deco = [];
  1530. if (r.underline) deco.push("underline");
  1531. if (r.strike) deco.push("line-through");
  1532. if (deco.length) css += "text-decoration:" + deco.join(" ") + ";";
  1533. if (r.bg && r.bgSpan) css += "background-color:" + hex(r.bg) + ";";
  1534. if (r.letterSpacing) css += "letter-spacing:" + pt(r.letterSpacing) + ";";
  1535. return css;
  1536. }
  1537. // the look most of a paragraph's text has
  1538. function dominant(tokens) {
  1539. var n = {}, pick = {};
  1540. tokens.forEach(function (t) {
  1541. var r = t.run;
  1542. if (!r || r.script || !r.text) return;
  1543. var k = [r.famKey, sizeKey(r.size), r.bold ? 1 : 0, r.italic ? 1 : 0, hex(r.color)].join("|");
  1544. n[k] = (n[k] || 0) + r.text.length;
  1545. pick[k] = r;
  1546. });
  1547. var best = null;
  1548. Object.keys(n).forEach(function (k) { if (!best || n[k] > n[best]) best = k; });
  1549. if (!best) {
  1550. // a line of pictures only: the size of the text they stand for
  1551. var size = 11;
  1552. for (var i = 0; i < tokens.length; i++) {
  1553. if (tokens[i].img && tokens[i].img.size) { size = sizeKey(tokens[i].img.size); break; }
  1554. }
  1555. return { famKey: "", size: size, bold: false, italic: false, color: "#000000" };
  1556. }
  1557. var r = pick[best];
  1558. return { famKey: r.famKey, size: sizeKey(r.size), bold: !!r.bold, italic: !!r.italic, color: hex(r.color) };
  1559. }
  1560. function blockCss(base, ctx, heading) {
  1561. var css = "";
  1562. if (base.famKey) css += "font-family:" + ctx.stacks[base.famKey] + ";";
  1563. css += "font-size:" + base.size + "pt;";
  1564. if (heading) {
  1565. css += "font-weight:" + (base.bold ? "bold" : "normal") + ";";
  1566. css += "font-style:" + (base.italic ? "italic" : "normal") + ";";
  1567. css += "color:" + base.color + ";";
  1568. } else {
  1569. if (base.bold) css += "font-weight:bold;";
  1570. if (base.italic) css += "font-style:italic;";
  1571. if (base.color !== "#000000") css += "color:" + base.color + ";";
  1572. }
  1573. return css;
  1574. }
  1575. // a paragraph's lines as one stream of tokens: wrapped lines joined by a
  1576. // space (or nothing between CJK, or a hyphen taken back), kept ones by <br>
  1577. function paragraphTokens(P, skipMarker) {
  1578. var out = [];
  1579. P.lines.forEach(function (L, i) {
  1580. var toks = L.tokens;
  1581. if (i === 0 && skipMarker && P.marker) {
  1582. var m = P.marker;
  1583. if (m.skip !== undefined) {
  1584. toks = toks.slice(m.skip);
  1585. } else {
  1586. var ti = m.splitTok || 0;
  1587. var t0 = toks[ti];
  1588. var rest = t0.run.text.substring(m.split).replace(/^\s+/, "");
  1589. toks = [{ run: t0.run, text: rest }].concat(toks.slice(ti + 1));
  1590. }
  1591. while (toks.length && (toks[0].space || toks[0].tab)) toks = toks.slice(1);
  1592. }
  1593. if (i > 0) {
  1594. if (P.breaks) {
  1595. out.push({ br: true });
  1596. } else {
  1597. var prev = out.length ? out[out.length - 1] : null;
  1598. var ptxt = prev && prev.run ? (prev.text !== undefined ? prev.text : prev.run.text) : "";
  1599. var first = null;
  1600. for (var k = 0; k < toks.length; k++) if (toks[k].run) { first = toks[k]; break; }
  1601. var ntxt = first ? (first.text !== undefined ? first.text : first.run.text) : "";
  1602. var pc = lastCp(ptxt), nc = ntxt ? cpOf(ntxt, 0) : 0;
  1603. if (/[A-Za-z]-$/.test(ptxt) && /^[a-z]/.test(ntxt)) {
  1604. // a word hyphenated at the line end
  1605. var keep = prev.text !== undefined ? prev.text : prev.run.text;
  1606. prev.text = keep.substring(0, keep.length - 1);
  1607. } else if (!(isCJK(pc) && isCJK(nc)) && !/\s$/.test(ptxt)) {
  1608. out.push({ space: true, next: first ? first.run : null });
  1609. }
  1610. }
  1611. }
  1612. toks.forEach(function (t) {
  1613. out.push(t.run ? { run: t.run, text: t.text } : t);
  1614. });
  1615. });
  1616. return out;
  1617. }
  1618. Emitter.prototype.paragraph = function (P, spaceBefore) {
  1619. var ctx = this.ctx;
  1620. var toks = paragraphTokens(P, false);
  1621. var base = dominant(toks);
  1622. var tag = P.heading || "p";
  1623. var e = el(tag);
  1624. var css = blockCss(base, ctx, !!P.heading);
  1625. if (P.heading) {
  1626. css += "margin-top:" + pt(spaceBefore) + ";margin-bottom:0pt;";
  1627. } else if (spaceBefore > 0.4) {
  1628. css += "padding-top:" + pt(spaceBefore) + ";";
  1629. }
  1630. if (P.align !== "left") css += "text-align:" + P.align + ";";
  1631. if (P.marginLeft > 1) css += "margin-left:" + pt(P.marginLeft) + ";";
  1632. if (P.indent && Math.abs(P.indent) > 1) css += "text-indent:" + pt(P.indent) + ";";
  1633. if (P.bg) css += "background-color:" + hex(P.bg) + ";";
  1634. // spaces that line code up must not collapse
  1635. if (toks.some(function (t) { return t.space && t.n > 1; })) css += "white-space:pre-wrap;";
  1636. e.setAttribute("style", css);
  1637. if (P.title) e.className = "doc-title";
  1638. if (P.ls) e.setAttribute("data-ls", String(P.ls));
  1639. if (P.tabs) e.setAttribute("data-tabs", P.tabs);
  1640. if (P.pageBreak) e.setAttribute("data-page-break-before", "1");
  1641. if (P.colSpan) e.classList.add("col-span-all");
  1642. this.inline(e, toks, base);
  1643. if (!e.firstChild) e.appendChild(document.createElement("br"));
  1644. return e;
  1645. };
  1646. Emitter.prototype.listItem = function (P, spaceBefore) {
  1647. var toks = paragraphTokens(P, true);
  1648. var base = dominant(toks);
  1649. var li = el("li");
  1650. var css = blockCss(base, this.ctx, false);
  1651. if (spaceBefore > 0.4) css += "padding-top:" + pt(spaceBefore) + ";";
  1652. if (P.ls) li.setAttribute("data-ls", String(P.ls));
  1653. li.setAttribute("style", css);
  1654. this.inline(li, toks, base);
  1655. if (!li.firstChild) li.appendChild(document.createElement("br"));
  1656. return li;
  1657. };
  1658. /* ---------------- conversion ---------------- */
  1659. function convert(bytes, opts) {
  1660. opts = opts || {};
  1661. var progress = opts.progress || function () { };
  1662. var store = opts.storeImage || function (blob) {
  1663. return new Promise(function (res) {
  1664. var fr = new FileReader();
  1665. fr.onload = function () { res(fr.result); };
  1666. fr.onerror = function () { res(null); };
  1667. fr.readAsDataURL(blob);
  1668. });
  1669. };
  1670. var stem = String(opts.name || "document").replace(/\.[^.]*$/, "").replace(/[^A-Za-z0-9_-]+/g, "_").substring(0, 40) || "pdf";
  1671. var imgSeq = 0;
  1672. var doc = null;
  1673. // lineArt: a rendered figure - PNG keeps its thin lines sharp
  1674. function encode(canvas, lineArt) {
  1675. return new Promise(function (res) {
  1676. if (!canvas) { res(null); return; }
  1677. var opaque = true;
  1678. var big = canvas.width * canvas.height > 90000;
  1679. // the reader knows whether the picture it placed is opaque; a
  1680. // rendered region (a figure) is on white
  1681. if (canvas._opaque !== undefined) {
  1682. opaque = canvas._opaque;
  1683. } else if (big) {
  1684. try {
  1685. var probe = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data;
  1686. for (var i = 3; i < probe.length; i += 4 * 7) if (probe[i] < 250) { opaque = false; break; }
  1687. } catch (e) { opaque = false; }
  1688. }
  1689. var jpeg = big && opaque && !lineArt;
  1690. var blob = canvasBlob(canvas, jpeg ? "image/jpeg" : "image/png", 0.9);
  1691. if (!blob) { res(null); return; }
  1692. // the same picture on many pages (a letterhead, an icon) is
  1693. // stored once
  1694. blobKey(blob).then(function (key) {
  1695. if (!stored[key]) {
  1696. imgSeq++;
  1697. stored[key] = store(blob, stem + "-" + imgSeq + (jpeg ? ".jpg" : ".png"));
  1698. }
  1699. stored[key].then(res, function () { res(null); });
  1700. });
  1701. });
  1702. }
  1703. var stored = {};
  1704. function blobKey(blob) {
  1705. if (!blob.arrayBuffer) return Promise.resolve("n" + (++imgSeq));
  1706. return blob.arrayBuffer().then(function (buf) {
  1707. var a = new Uint8Array(buf);
  1708. var h = 0x811c9dc5;
  1709. for (var i = 0; i < a.length; i++) {
  1710. h ^= a[i];
  1711. h = Math.imul(h, 16777619) >>> 0;
  1712. }
  1713. return a.length + ":" + h;
  1714. }, function () { return "n" + (++imgSeq); });
  1715. }
  1716. return OfficePdfRead.open(bytes, { password: opts.password }).then(function (d) {
  1717. doc = d;
  1718. var pages = [];
  1719. var n = 0;
  1720. function next() {
  1721. n++;
  1722. if (n > doc.numPages) return Promise.resolve(pages);
  1723. progress("Reading page " + n + " of " + doc.numPages, n - 1, doc.numPages);
  1724. return doc.page(n).then(function (page) {
  1725. var pg = analyzePage(page);
  1726. var jobs = [];
  1727. pg.images.forEach(function (it) {
  1728. var im = it.img;
  1729. jobs.push(im.canvas().then(encode).then(function (src) { im.src = src; }));
  1730. });
  1731. pg.tables.forEach(function (t) {
  1732. t.cells.forEach(function (c) {
  1733. c.images.forEach(function (b) {
  1734. jobs.push(b.img.canvas().then(encode).then(function (src) { b.img.src = src; }));
  1735. });
  1736. });
  1737. });
  1738. pg.figures.forEach(function (f) {
  1739. var w = f.x1 - f.x0, h = f.y1 - f.y0;
  1740. var scale = Math.max(1.5, Math.min(3, 1400 / Math.max(w, h)));
  1741. jobs.push(page.render([f.x0, f.y0, f.x1, f.y1], scale).then(function (c) {
  1742. return encode(c, true);
  1743. }).then(function (src) {
  1744. f.src = src;
  1745. }, function () { f.src = null; }));
  1746. });
  1747. return Promise.all(jobs).then(function () {
  1748. page.release();
  1749. pages.push(pg);
  1750. return yield0().then(next);
  1751. });
  1752. });
  1753. }
  1754. return next();
  1755. }).then(function (pages) {
  1756. progress("Building the document", doc.numPages, doc.numPages);
  1757. return buildBody(pages, opts);
  1758. }).then(function (body) {
  1759. if (doc) doc.close();
  1760. return body;
  1761. }, function (err) {
  1762. if (doc) doc.close();
  1763. throw err;
  1764. });
  1765. }
  1766. function buildBody(pages, opts) {
  1767. var running = stripRunning(pages);
  1768. var first = pages[0] || { width: 595, height: 842 };
  1769. var paper = pickPaper(first.width, first.height);
  1770. var tb = textBounds(pages) || { left: 72, right: first.width - 72, top: 72, bottom: first.height - 72 };
  1771. if (tb.right - tb.left < 50) { tb.left = 72; tb.right = first.width - 72; }
  1772. // margins: the PDF's, with the text column kept as wide as it was
  1773. var textW = tb.right - tb.left;
  1774. var leftMm = Math.max(5, Math.min(60, tb.left / PT_PER_MM));
  1775. var rightMm = paper.w - leftMm - textW / PT_PER_MM;
  1776. if (rightMm < 5) {
  1777. rightMm = Math.max(5, Math.min(60, (first.width - tb.right) / PT_PER_MM));
  1778. }
  1779. var topMm = Math.max(5, Math.min(60, tb.top / PT_PER_MM - 1));
  1780. // where the fullest pages stop, with the page as tall as it was; a
  1781. // single page that is not full says nothing, so it mirrors the top
  1782. var textH = tb.bottom - tb.top;
  1783. var bottomMm = paper.h - topMm - textH / PT_PER_MM - 2;
  1784. if (bottomMm < 5 || bottomMm > 50) bottomMm = (first.height - tb.bottom) / PT_PER_MM - 2;
  1785. if (tb.pages < 2 && bottomMm > topMm) bottomMm = topMm;
  1786. bottomMm = Math.max(5, Math.min(50, bottomMm));
  1787. var page = {
  1788. size: paper.size, orientation: paper.orientation,
  1789. margins: { top: r1(topMm), right: r1(rightMm), bottom: r1(bottomMm), left: r1(leftMm) },
  1790. columns: 1, colGap: 8, headerDist: 12.7, footerDist: 12.7
  1791. };
  1792. if (running.headerTop !== null) page.headerDist = r1(Math.max(3, Math.min(40, running.headerTop / PT_PER_MM)));
  1793. if (running.footerBottom !== null) page.footerDist = r1(Math.max(3, Math.min(40, running.footerBottom / PT_PER_MM)));
  1794. // fonts: a family per run, and its CSS stack
  1795. var stacks = {};
  1796. var sizeChars = {};
  1797. function prepRun(r) {
  1798. var fam = familyOf(r);
  1799. r.famKey = fam;
  1800. if (!stacks[fam]) stacks[fam] = stackOf(fam, r);
  1801. var k = sizeKey(r.size);
  1802. sizeChars[k] = (sizeChars[k] || 0) + r.text.length;
  1803. }
  1804. pages.forEach(function (pg) {
  1805. pg.regions.forEach(function (rg) {
  1806. rg.items.forEach(function (it) {
  1807. if (it.tokens) it.tokens.forEach(function (t) { if (t.run && t.run.text !== undefined && t.run.font) prepRun(t.run); });
  1808. });
  1809. });
  1810. pg.tables.forEach(function (t) {
  1811. t.cells.forEach(function (c) { c.runs.forEach(prepRun); });
  1812. });
  1813. });
  1814. var bodySize = 11;
  1815. var bestN = -1;
  1816. Object.keys(sizeChars).forEach(function (k) { if (sizeChars[k] > bestN) { bestN = sizeChars[k]; bodySize = parseFloat(k); } });
  1817. var famList = {};
  1818. Object.keys(stacks).forEach(function (f) { famList[stacks[f]] = f; });
  1819. return loadFonts(famList).then(function () {
  1820. return emit(pages, {
  1821. page: page, tb: tb, stacks: stacks, bodySize: bodySize, running: running,
  1822. sizeChars: sizeChars, totalChars: Object.keys(sizeChars).reduce(function (n, k) { return n + sizeChars[k]; }, 0),
  1823. paperW: paper.w * PT_PER_MM
  1824. });
  1825. });
  1826. }
  1827. function emit(pages, ctx) {
  1828. var root = document.createElement("div");
  1829. var E = new Emitter(ctx);
  1830. var tb = ctx.tb;
  1831. var docMults = [];
  1832. var all = []; // {P | block, page, colLeft, colRight, region}
  1833. pages.forEach(function (pg, pi) {
  1834. pg.regions.forEach(function (rg) {
  1835. var colL = rg.bounds.left !== null && rg.bounds.left !== undefined ? rg.bounds.left : tb.left;
  1836. var colR = rg.bounds.right !== null && rg.bounds.right !== undefined ? rg.bounds.right : tb.right;
  1837. if (colR - colL < 30) { colL = tb.left; colR = tb.right; }
  1838. paragraphsOf(rg, colL, colR).forEach(function (P) {
  1839. all.push({ P: P.block ? null : P, block: P.block || null, page: pi, colL: colL, colR: colR });
  1840. });
  1841. });
  1842. });
  1843. // superscripts and subscripts: a smaller run off the line's baseline
  1844. all.forEach(function (x) {
  1845. if (!x.P) return;
  1846. x.P.lines.forEach(function (L) {
  1847. L.tokens.forEach(function (t) {
  1848. var r = t.run;
  1849. if (!r || !r.size) return;
  1850. if (r.size < L.size * 0.85) {
  1851. if (r.base < L.base - L.size * 0.15) r.script = "sup";
  1852. else if (r.base > L.base + L.size * 0.08) r.script = "sub";
  1853. }
  1854. });
  1855. });
  1856. });
  1857. // heading levels: sizes clearly above the body text
  1858. var headSizes = {};
  1859. all.forEach(function (x) {
  1860. var P = x.P;
  1861. // a numbered heading ("2. Design goals") is a heading, a bulleted
  1862. // line is not
  1863. if (!P || (P.marker && P.marker.kind !== "number") || P.lines.length > 3 || P.chars > 200) return;
  1864. var s = sizeKey(P.size);
  1865. if (s >= ctx.bodySize * 1.18 || (P.bold && s >= ctx.bodySize * 1.08 && P.lines.length <= 2)) {
  1866. P.headCand = true;
  1867. headSizes[s] = (headSizes[s] || 0) + 1;
  1868. }
  1869. });
  1870. // headings are the rare sizes: a size that carries a good share of
  1871. // the text is body text of its own (a manual's main text above its
  1872. // small print), and only the three largest are levels
  1873. Object.keys(headSizes).forEach(function (s) {
  1874. if ((ctx.sizeChars[s] || 0) > ctx.totalChars * 0.12) delete headSizes[s];
  1875. });
  1876. var levels = Object.keys(headSizes).map(parseFloat).sort(function (a, b) { return b - a; }).slice(0, 3);
  1877. all.forEach(function (x) {
  1878. if (x.P && x.P.headCand && levels.indexOf(sizeKey(x.P.size)) < 0) x.P.headCand = false;
  1879. });
  1880. var firstPage = all.filter(function (x) { return x.page === 0 && x.P; });
  1881. var titleSize = levels.length && headSizes[levels[0]] === 1 && levels[0] >= ctx.bodySize * 1.6 ? levels[0] : null;
  1882. all.forEach(function (x) {
  1883. var P = x.P;
  1884. if (!P || !P.headCand) return;
  1885. var s = sizeKey(P.size);
  1886. if (titleSize !== null && s === titleSize && firstPage.indexOf(x) >= 0) {
  1887. P.heading = "h1";
  1888. P.title = true;
  1889. return;
  1890. }
  1891. var idx = levels.indexOf(s) - (titleSize !== null ? 1 : 0);
  1892. P.heading = "h" + Math.min(3, Math.max(1, idx + 1));
  1893. });
  1894. // line spacing: the document's own, and each paragraph's against it
  1895. all.forEach(function (x) {
  1896. var P = x.P;
  1897. if (!P || !P.pitch) return;
  1898. var base = dominant(paragraphTokens(P, false));
  1899. var rt = ratioOf(ctx.stacks[base.famKey] || "Arial");
  1900. var m = P.pitch / ((rt.asc + rt.desc) * base.size);
  1901. if (m > 0.6 && m < 4) { P.mult = m; docMults.push(r2(m)); }
  1902. });
  1903. var docLS = docMults.length ? r2(median(docMults)) : 1.15;
  1904. all.forEach(function (x) {
  1905. var P = x.P;
  1906. if (!P) return;
  1907. if (P.mult && Math.abs(P.mult - docLS) > 0.03) P.ls = r2(P.mult);
  1908. var lh = null;
  1909. // how tall the editor will make one of its lines, and where in
  1910. // that line the baseline sits (CSS centres the font's box in it)
  1911. P.lineH = function () {
  1912. if (lh) return lh;
  1913. var base = dominant(paragraphTokens(P, false));
  1914. var rt = ratioOf(ctx.stacks[base.famKey] || "Arial");
  1915. var m = P.ls || docLS;
  1916. lh = { h: (rt.asc + rt.desc) * base.size * m, asc: rt.asc * base.size, desc: rt.desc * base.size };
  1917. return lh;
  1918. };
  1919. });
  1920. // shading: a box behind every line of a paragraph colours the
  1921. // paragraph; behind a few words, those words
  1922. all.forEach(function (x) {
  1923. var P = x.P;
  1924. if (!P) return;
  1925. var bgs = {};
  1926. var total = 0, shaded = 0;
  1927. P.lines.forEach(function (L) {
  1928. L.tokens.forEach(function (t) {
  1929. if (!t.run || !t.run.text) return;
  1930. total += t.run.text.length;
  1931. if (t.run.bg) { shaded += t.run.text.length; bgs[hex(t.run.bg)] = t.run.bg; }
  1932. });
  1933. });
  1934. var keys = Object.keys(bgs);
  1935. if (keys.length === 1 && shaded >= total * 0.95) {
  1936. var box = null;
  1937. P.lines.forEach(function (L) { L.tokens.forEach(function (t) { if (t.run && t.run.bgBox) box = t.run.bgBox; }); });
  1938. if (box && box.x1 - box.x0 > (x.colR - x.colL) * 0.6) {
  1939. P.bg = bgs[keys[0]];
  1940. return;
  1941. }
  1942. }
  1943. P.lines.forEach(function (L) { L.tokens.forEach(function (t) { if (t.run && t.run.bg) t.run.bgSpan = true; }); });
  1944. });
  1945. // tab stops
  1946. all.forEach(function (x) {
  1947. var P = x.P;
  1948. if (!P || P.lines.length !== 1 || !P.lines[0].hasTab) return;
  1949. var L = P.lines[0];
  1950. var stops = [];
  1951. var segIdx = 0;
  1952. L.tokens.forEach(function (t, i) {
  1953. if (!t.tab) return;
  1954. segIdx++;
  1955. var sg = L.segs[segIdx];
  1956. if (!sg) return;
  1957. var lead = t.leader ? "dot" : "none";
  1958. var rightAligned = Math.abs(sg.x1 - x.colR) <= 3 && segIdx === L.segs.length - 1;
  1959. if (rightAligned) stops.push("right:" + r2(sg.x1 - x.colL) + ":" + lead);
  1960. else stops.push("left:" + r2(sg.x0 - x.colL) + ":" + lead);
  1961. });
  1962. P.tabs = stops.join(";");
  1963. P.align = "left";
  1964. P.marginLeft = Math.max(0, L.x0 - x.colL);
  1965. P.indent = 0;
  1966. });
  1967. // where a page of the PDF ends early, the next one starts a page
  1968. var pageLast = {};
  1969. all.forEach(function (x, i) { pageLast[x.page] = i; });
  1970. var pageFirst = {};
  1971. all.forEach(function (x, i) { if (pageFirst[x.page] === undefined) pageFirst[x.page] = i; });
  1972. var textBottom = tb.bottom;
  1973. Object.keys(pageFirst).forEach(function (p) {
  1974. p = parseInt(p, 10);
  1975. if (p === 0) return;
  1976. var prevIdx = pageLast[p - 1];
  1977. var prevPage = p - 1;
  1978. while (prevIdx === undefined && prevPage > 0) { prevPage--; prevIdx = pageLast[prevPage]; }
  1979. var cur = all[pageFirst[p]];
  1980. if (prevIdx === undefined) return;
  1981. var prev = all[prevIdx];
  1982. var prevBottom = prev.P ? prev.P.bottom : prev.block.y1;
  1983. var lineH = ctx.bodySize * 1.4;
  1984. if (textBottom - prevBottom > Math.max(lineH * 4, (textBottom - tb.top) * 0.18) || prevPage < p - 1) {
  1985. cur.pageBreak = true;
  1986. return;
  1987. }
  1988. // a paragraph carried over to the next page is one paragraph
  1989. var A = prev.P, B = cur.P;
  1990. if (!A || !B || A.marker || B.marker || A.heading || B.heading || A.align === "center") return;
  1991. var la = A.lines[A.lines.length - 1], lb = B.lines[0];
  1992. if (la.style !== lb.style || la.hasTab || lb.hasTab) return;
  1993. var full = prev.colR - la.x1 < firstWordWidth(lb) + la.size * 0.6;
  1994. var contX = A.lines.length > 1 ? A.lines[1].x0 : A.lines[0].x0;
  1995. var noIndent = Math.abs(lb.x0 - contX) <= Math.max(1.5, lb.size * 0.3);
  1996. var ends = ENDS_SENTENCE.test(la.text.trim());
  1997. if (full && noIndent && (!ends || /^[a-z]/.test(lb.text))) {
  1998. B.lines.forEach(function (L) { A.lines.push(L); });
  1999. A.lastBase = B.lastBase;
  2000. A.bottom = B.bottom;
  2001. if (!A.pitch && B.pitch) A.pitch = B.pitch;
  2002. cur.merged = true;
  2003. }
  2004. });
  2005. // lists: consecutive items, nested by where their markers stand
  2006. var listRun = null;
  2007. function closeList() { listRun = null; }
  2008. var prevEntry = null;
  2009. all.forEach(function (x) {
  2010. if (x.merged) return;
  2011. var spaceBefore = 0;
  2012. var startsPage = prevEntry === null || prevEntry.page !== x.page;
  2013. if (x.P) {
  2014. var lh = x.P.lineH();
  2015. var top = x.P.firstBase - (lh.h / 2 + (lh.asc - lh.desc) / 2);
  2016. if (startsPage) {
  2017. spaceBefore = prevEntry === null ? Math.max(0, top - tb.top) : 0;
  2018. } else if (prevEntry.P) {
  2019. var plh = prevEntry.P.lineH();
  2020. var pbottom = prevEntry.P.lastBase + plh.h / 2 - (plh.asc - plh.desc) / 2;
  2021. spaceBefore = top - pbottom;
  2022. } else {
  2023. spaceBefore = top - prevEntry.block.y1;
  2024. }
  2025. } else if (prevEntry && !startsPage) {
  2026. var pb = prevEntry.P ? prevEntry.P.bottom : prevEntry.block.y1;
  2027. spaceBefore = x.block.y0 - pb;
  2028. }
  2029. spaceBefore = Math.max(0, Math.min(200, spaceBefore));
  2030. if (spaceBefore < 0.75) spaceBefore = 0;
  2031. if (x.pageBreak) {
  2032. closeList();
  2033. root.appendChild(el("div", null, "doc-pagebreak"));
  2034. spaceBefore = 0;
  2035. }
  2036. if (x.P && x.P.marker && !x.P.heading) {
  2037. addListItem(x, spaceBefore);
  2038. } else {
  2039. closeList();
  2040. if (x.P) root.appendChild(E.paragraph(x.P, spaceBefore));
  2041. else {
  2042. var b = emitBlock(x, spaceBefore);
  2043. if (b) root.appendChild(b);
  2044. }
  2045. }
  2046. prevEntry = x;
  2047. });
  2048. function addListItem(x, spaceBefore) {
  2049. var P = x.P, m = P.marker;
  2050. var markerX = m.markerX - x.colL;
  2051. if (!listRun) listRun = { stack: [] };
  2052. var st = listRun.stack;
  2053. // close deeper levels
  2054. var textXr = m.textX - x.colL;
  2055. // a level is where its markers or its text line up ("9." and
  2056. // "10." right-aligned start apart, their text does not)
  2057. var level = function (e) { return Math.abs(markerX - e.markerX) <= 2 || Math.abs(textXr - e.textX) <= 2; };
  2058. while (st.length && !level(st[st.length - 1]) && markerX < st[st.length - 1].markerX - 2) st.pop();
  2059. var top = st.length ? st[st.length - 1] : null;
  2060. var ordered = m.kind === "number";
  2061. var sameLevel = top && level(top);
  2062. if (sameLevel && (top.ordered !== ordered || (ordered && top.fmt !== m.fmt) || (!ordered && top.marker !== m.marker))) {
  2063. st.pop();
  2064. top = st.length ? st[st.length - 1] : null;
  2065. sameLevel = false;
  2066. }
  2067. if (!sameLevel) {
  2068. var depth = st.length;
  2069. var parentText = top ? top.textX : 0;
  2070. var textX = m.textX - x.colL;
  2071. var list = el(ordered ? "ol" : "ul", "padding-left:" + pt(Math.max(0, textX - parentText)) +
  2072. ";--doc-hang:" + pt(Math.max(4, m.textX - m.markerX)) + ";", "doc-list");
  2073. if (ordered) {
  2074. list.setAttribute("data-fmt", m.fmt);
  2075. list.setAttribute("data-lvltext", m.prefix + "%" + (depth + 1) + m.suffix);
  2076. if (m.value !== 1 && m.value > 0) list.setAttribute("start", String(m.value));
  2077. } else {
  2078. list.setAttribute("data-fmt", "bullet");
  2079. list.setAttribute("data-lvltext", m.marker);
  2080. }
  2081. if (P.colSpan) list.classList.add("col-span-all");
  2082. (top ? top.el : root).appendChild(list);
  2083. st.push({ el: list, markerX: markerX, textX: textX, ordered: ordered, fmt: m.fmt, marker: m.marker });
  2084. top = st[st.length - 1];
  2085. }
  2086. top.el.appendChild(E.listItem(P, spaceBefore));
  2087. }
  2088. function emitBlock(x, spaceBefore) {
  2089. var b = x.block;
  2090. var colW = x.colR - x.colL;
  2091. if (b.kind === "hr") return el("hr");
  2092. if (b.kind === "image" || b.kind === "figure") {
  2093. var src = b.kind === "image" ? b.img.src : b.src;
  2094. if (!src) return null;
  2095. var w = b.x1 - b.x0, h = b.y1 - b.y0;
  2096. if (w > colW) { h = h * colW / w; w = colW; }
  2097. var cx = (b.x0 + b.x1) / 2;
  2098. var align = "left", ml = 0;
  2099. if (Math.abs(cx - (x.colL + x.colR) / 2) < colW * 0.06 && b.x0 > x.colL + 4) align = "center";
  2100. else if (Math.abs(b.x1 - x.colR) < colW * 0.06 && b.x0 > x.colL + colW * 0.3) align = "right";
  2101. else ml = Math.max(0, b.x0 - x.colL);
  2102. var css = "";
  2103. if (spaceBefore > 0.4) css += "padding-top:" + pt(spaceBefore) + ";";
  2104. if (align !== "left") css += "text-align:" + align + ";";
  2105. if (ml > 2) css += "margin-left:" + pt(Math.min(ml, colW - w)) + ";";
  2106. var p = el("p", css || null);
  2107. // a border is drawn outside the picture's box, as the PDF did
  2108. var bd = b.border ? Math.max(0.25, Math.min(6, b.border.w)) : 0;
  2109. var img = el("img", "width:" + pt(w - bd) + ";height:" + pt(h - bd) + ";" +
  2110. (bd ? "border:" + pt(bd) + " solid " + hex(b.border.color) + ";" : ""));
  2111. img.setAttribute("src", src);
  2112. p.appendChild(img);
  2113. return p;
  2114. }
  2115. if (b.kind === "table") return emitTable(b, x, spaceBefore);
  2116. return null;
  2117. }
  2118. function borderCss(l) {
  2119. if (!l) return "none";
  2120. return pt(Math.max(0.25, Math.min(6, l.w))) + " solid " + hex(l.color);
  2121. }
  2122. function emitTable(t, x, spaceBefore) {
  2123. var widths = [];
  2124. for (var c = 0; c < t.cols; c++) widths.push(t.xs[c + 1] - t.xs[c]);
  2125. var totalW = t.x1 - t.x0;
  2126. var css = "width:" + pt(totalW) + ";table-layout:fixed;";
  2127. var ml = t.x0 - x.colL;
  2128. if (ml > 1) css += "margin-left:" + pt(ml) + ";";
  2129. var table = el("table", css, "of-table");
  2130. table.setAttribute("data-docx", "1");
  2131. var cg = el("colgroup");
  2132. widths.forEach(function (w) { cg.appendChild(el("col", "width:" + pt(w) + ";")); });
  2133. table.appendChild(cg);
  2134. var tbody = el("tbody");
  2135. table.appendChild(tbody);
  2136. var byRow = {};
  2137. t.cells.forEach(function (cell) { (byRow[cell.r] = byRow[cell.r] || []).push(cell); });
  2138. for (var r = 0; r < t.rows; r++) {
  2139. var tr = el("tr", "height:" + pt(t.ys[r + 1] - t.ys[r]) + ";");
  2140. (byRow[r] || []).sort(function (a, b) { return a.c - b.c; }).forEach(function (cell) {
  2141. tr.appendChild(emitCell(cell, t));
  2142. });
  2143. tbody.appendChild(tr);
  2144. }
  2145. return table;
  2146. }
  2147. function emitCell(cell, t) {
  2148. var minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
  2149. cell.runs.forEach(function (r) {
  2150. minX = Math.min(minX, r.x0); maxX = Math.max(maxX, r.x1);
  2151. minY = Math.min(minY, r.top); maxY = Math.max(maxY, r.bottom);
  2152. });
  2153. cell.images.forEach(function (b) {
  2154. minX = Math.min(minX, b.x0); maxX = Math.max(maxX, b.x1);
  2155. minY = Math.min(minY, b.y0); maxY = Math.max(maxY, b.y1);
  2156. });
  2157. var padL = 2, padR = 2;
  2158. if (minX < Infinity) {
  2159. padL = Math.max(1, Math.min(10, minX - cell.x0 - 0.5));
  2160. padR = Math.max(1, Math.min(padL, cell.x1 - maxX));
  2161. }
  2162. var valign = "top";
  2163. if (minY < Infinity) {
  2164. var gt = minY - cell.y0, gb = cell.y1 - maxY;
  2165. if (gt > 4 && Math.abs(gt - gb) < Math.max(2.5, (gt + gb) * 0.2)) valign = "middle";
  2166. else if (gb < gt - 4 && gb < 5) valign = "bottom";
  2167. }
  2168. var css = "border-top:" + borderCss(cell.top) + ";border-right:" + borderCss(cell.right) +
  2169. ";border-bottom:" + borderCss(cell.bottom) + ";border-left:" + borderCss(cell.left) +
  2170. ";padding:1pt " + pt(padR) + " 1pt " + pt(padL) + ";vertical-align:" + valign + ";";
  2171. if (cell.bg && !isWhite(cell.bg)) css += "background-color:" + hex(cell.bg) + ";";
  2172. var td = el("td", css);
  2173. if (cell.cs > 1) td.setAttribute("colspan", String(cell.cs));
  2174. if (cell.rs > 1) td.setAttribute("rowspan", String(cell.rs));
  2175. // the cell's text, reflowed like a little page of its own
  2176. var atoms = cell.runs.map(function (r) {
  2177. r.kind = "run";
  2178. r.y0 = r.top;
  2179. r.y1 = r.bottom;
  2180. return r;
  2181. });
  2182. cell.images.forEach(function (b) { b.top = b.y0; b.bottom = b.y1; atoms.push(b); });
  2183. var region = { items: linesOf(atoms), bounds: {} };
  2184. var colL = cell.x0 + padL, colR = cell.x1 - padR;
  2185. var paras = paragraphsOf(region, colL, colR);
  2186. var prevP = null;
  2187. paras.forEach(function (P) {
  2188. if (P.block) {
  2189. var b = P.block;
  2190. if (b.kind === "image" && b.img.src) {
  2191. var p = el("p", "text-align:" + ((b.x0 + b.x1) / 2 > (colL + colR) / 2 + 4 ? "center" : "left") + ";");
  2192. var w = Math.min(b.x1 - b.x0, colR - colL), h = (b.y1 - b.y0) * w / Math.max(1, b.x1 - b.x0);
  2193. var img = el("img", "width:" + pt(w) + ";height:" + pt(h) + ";");
  2194. img.setAttribute("src", b.img.src);
  2195. p.appendChild(img);
  2196. td.appendChild(p);
  2197. }
  2198. return;
  2199. }
  2200. var sb = 0;
  2201. if (prevP) sb = Math.max(0, P.top - prevP.bottom - P.size * 0.3);
  2202. if (P.lines.length > 1 && P.pitch) {
  2203. var base = dominant(paragraphTokens(P, false));
  2204. var rt = ratioOf(ctx.stacks[base.famKey] || "Arial");
  2205. var m = P.pitch / ((rt.asc + rt.desc) * base.size);
  2206. if (m > 0.6 && m < 4 && Math.abs(m - docLS) > 0.03) P.ls = r2(m);
  2207. }
  2208. P.marginLeft = Math.max(0, P.marginLeft || 0);
  2209. if (P.marker) { P.marker = null; P.marginLeft = 0; P.indent = 0; }
  2210. td.appendChild(E.paragraph(P, sb));
  2211. prevP = P;
  2212. });
  2213. if (!td.firstChild) td.appendChild(el("p")).appendChild(document.createElement("br"));
  2214. return td;
  2215. }
  2216. var html = root.innerHTML || "<p><br></p>";
  2217. var running = ctx.running;
  2218. /* letterhead art goes into the header (footer) when it fits in the
  2219. band between the paper's edge and the text; the text of the
  2220. header follows it */
  2221. function bandHtml(pic, text, roomMm) {
  2222. var src = pic && (pic.kind === "image" ? pic.img.src : pic.src);
  2223. if (!src) return undefined;
  2224. var w = pic.x1 - pic.x0, h = pic.y1 - pic.y0;
  2225. var room = roomMm * PT_PER_MM;
  2226. if (room < 12) return undefined;
  2227. if (h > room) { w = w * room / h; h = room; }
  2228. var box = document.createElement("div");
  2229. var p = el("p", pic.x0 > ctx.paperW * 0.3 ? "text-align:" + (pic.x1 > ctx.paperW * 0.7 ? "right" : "center") + ";" : null);
  2230. var img = el("img", "width:" + pt(w) + ";height:" + pt(h) + ";");
  2231. img.setAttribute("src", src);
  2232. p.appendChild(img);
  2233. box.appendChild(p);
  2234. if (text) {
  2235. var tp = el("p");
  2236. tp.appendChild(document.createTextNode(text));
  2237. box.appendChild(tp);
  2238. }
  2239. return box.innerHTML;
  2240. }
  2241. var pg = ctx.page;
  2242. var headerHtml = bandHtml(running.headerPic, running.header, pg.margins.top - pg.headerDist - 2);
  2243. var footerHtml = bandHtml(running.footerPic, running.footer, pg.margins.bottom - pg.footerDist - 2);
  2244. return {
  2245. html: html,
  2246. page: ctx.page,
  2247. header: running.header || "",
  2248. footer: running.footer || "",
  2249. headerHtml: headerHtml,
  2250. footerHtml: footerHtml,
  2251. pageNumbers: !!running.pageNumbers,
  2252. lineSpacing: docLS,
  2253. hfMode: "all"
  2254. };
  2255. }
  2256. window.DocsPdfImport = {
  2257. convert: convert,
  2258. // exposed for tests
  2259. _listMarker: listMarker,
  2260. _pickPaper: pickPaper,
  2261. _analyzePage: analyzePage,
  2262. _paragraphsOf: paragraphsOf,
  2263. _textBounds: textBounds,
  2264. _stripRunning: stripRunning
  2265. };
  2266. })();