/jspdf.plugin.from_html.js

https://github.com/HangYang/jsPDF · JavaScript · 536 lines · 490 code · 1 blank · 45 comment · 108 complexity · 4db4ace45ad9002b99c02f9989fc35db MD5 · raw file

  1. /** @preserve
  2. * jsPDF fromHTML plugin. BETA stage. API subject to change. Needs browser
  3. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  4. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  5. * 2014 Diego Casorran, https://github.com/diegocr
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining
  8. * a copy of this software and associated documentation files (the
  9. * "Software"), to deal in the Software without restriction, including
  10. * without limitation the rights to use, copy, modify, merge, publish,
  11. * distribute, sublicense, and/or sell copies of the Software, and to
  12. * permit persons to whom the Software is furnished to do so, subject to
  13. * the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be
  16. * included in all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  19. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. * ====================================================================
  26. */
  27. (function(jsPDFAPI) {
  28. var DrillForContent, FontNameDB, FontStyleMap, FontWeightMap, GetCSS, PurgeWhiteSpace, Renderer, ResolveFont, ResolveUnitedNumber, UnitedNumberMap, elementHandledElsewhere, images, loadImgs, process, tableToJson;
  29. PurgeWhiteSpace = function(array) {
  30. var fragment, i, l, lTrimmed, r, rTrimmed, trailingSpace;
  31. i = 0;
  32. l = array.length;
  33. fragment = void 0;
  34. lTrimmed = false;
  35. rTrimmed = false;
  36. while (!lTrimmed && i !== l) {
  37. fragment = array[i] = array[i].trimLeft();
  38. if (fragment) {
  39. lTrimmed = true;
  40. }
  41. i++;
  42. }
  43. i = l - 1;
  44. while (l && !rTrimmed && i !== -1) {
  45. fragment = array[i] = array[i].trimRight();
  46. if (fragment) {
  47. rTrimmed = true;
  48. }
  49. i--;
  50. }
  51. r = /\s+$/g;
  52. trailingSpace = true;
  53. i = 0;
  54. while (i !== l) {
  55. fragment = array[i].replace(/\s+/g, " ");
  56. if (trailingSpace) {
  57. fragment = fragment.trimLeft();
  58. }
  59. if (fragment) {
  60. trailingSpace = r.test(fragment);
  61. }
  62. array[i] = fragment;
  63. i++;
  64. }
  65. return array;
  66. };
  67. Renderer = function(pdf, x, y, settings) {
  68. this.pdf = pdf;
  69. this.x = x;
  70. this.y = y;
  71. this.settings = settings;
  72. this.init();
  73. return this;
  74. };
  75. ResolveFont = function(css_font_family_string) {
  76. var name, part, parts;
  77. name = void 0;
  78. parts = css_font_family_string.split(",");
  79. part = parts.shift();
  80. while (!name && part) {
  81. name = FontNameDB[part.trim().toLowerCase()];
  82. part = parts.shift();
  83. }
  84. return name;
  85. };
  86. ResolveUnitedNumber = function(css_line_height_string) {
  87. var normal, undef, value;
  88. undef = void 0;
  89. normal = 16.00;
  90. value = UnitedNumberMap[css_line_height_string];
  91. if (value) {
  92. return value;
  93. }
  94. value = {
  95. "xx-small": 9,
  96. "x-small": 11,
  97. small: 13,
  98. medium: 16,
  99. large: 19,
  100. "x-large": 23,
  101. "xx-large": 28,
  102. auto: 0
  103. }[{
  104. css_line_height_string: css_line_height_string
  105. }];
  106. if (value !== undef) {
  107. return UnitedNumberMap[css_line_height_string] = value / normal;
  108. }
  109. if (value = parseFloat(css_line_height_string)) {
  110. return UnitedNumberMap[css_line_height_string] = value / normal;
  111. }
  112. value = css_line_height_string.match(/([\d\.]+)(px)/);
  113. if (value.length === 3) {
  114. return UnitedNumberMap[css_line_height_string] = parseFloat(value[1]) / normal;
  115. }
  116. return UnitedNumberMap[css_line_height_string] = 1;
  117. };
  118. GetCSS = function(element) {
  119. var css, tmp, computedCSSElement;
  120. computedCSSElement = (function(el) {
  121. var compCSS;
  122. compCSS = (function(el) {
  123. if ( document.defaultView && document.defaultView.getComputedStyle ) {
  124. return document.defaultView.getComputedStyle(el, null);
  125. } else if ( el.currentStyle ) {
  126. return el.currentStyle;
  127. } else {
  128. return el.style;
  129. }
  130. })(el);
  131. return function(prop) {
  132. prop = prop.replace(/-\D/g, function(match){
  133. return match.charAt(1).toUpperCase();
  134. })
  135. return compCSS[prop];
  136. }
  137. })(element);
  138. css = {};
  139. tmp = void 0;
  140. css["font-family"] = ResolveFont(computedCSSElement("font-family")) || "times";
  141. css["font-style"] = FontStyleMap[computedCSSElement("font-style")] || "normal";
  142. tmp = FontWeightMap[computedCSSElement("font-weight")] || "normal";
  143. if (tmp === "bold") {
  144. if (css["font-style"] === "normal") {
  145. css["font-style"] = tmp;
  146. } else {
  147. css["font-style"] = tmp + css["font-style"];
  148. }
  149. }
  150. css["font-size"] = ResolveUnitedNumber(computedCSSElement("font-size")) || 1;
  151. css["line-height"] = ResolveUnitedNumber(computedCSSElement("line-height")) || 1;
  152. css["display"] = (computedCSSElement("display") === "inline" ? "inline" : "block");
  153. if (css["display"] === "block") {
  154. css["margin-top"] = ResolveUnitedNumber(computedCSSElement("margin-top")) || 0;
  155. css["margin-bottom"] = ResolveUnitedNumber(computedCSSElement("margin-bottom")) || 0;
  156. css["padding-top"] = ResolveUnitedNumber(computedCSSElement("padding-top")) || 0;
  157. css["padding-bottom"] = ResolveUnitedNumber(computedCSSElement("padding-bottom")) || 0;
  158. css["margin-left"] = ResolveUnitedNumber(computedCSSElement("margin-left")) || 0;
  159. css["margin-right"] = ResolveUnitedNumber(computedCSSElement("margin-right")) || 0;
  160. css["padding-left"] = ResolveUnitedNumber(computedCSSElement("padding-left")) || 0;
  161. css["padding-right"] = ResolveUnitedNumber(computedCSSElement("padding-right")) || 0;
  162. }
  163. return css;
  164. };
  165. elementHandledElsewhere = function(element, renderer, elementHandlers) {
  166. var handlers, i, isHandledElsewhere, l, t;
  167. isHandledElsewhere = false;
  168. i = void 0;
  169. l = void 0;
  170. t = void 0;
  171. handlers = elementHandlers["#" + element.id];
  172. if (handlers) {
  173. if (typeof handlers === "function") {
  174. isHandledElsewhere = handlers(element, renderer);
  175. } else {
  176. i = 0;
  177. l = handlers.length;
  178. while (!isHandledElsewhere && i !== l) {
  179. isHandledElsewhere = handlers[i](element, renderer);
  180. i++;
  181. }
  182. }
  183. }
  184. handlers = elementHandlers[element.nodeName];
  185. if (!isHandledElsewhere && handlers) {
  186. if (typeof handlers === "function") {
  187. isHandledElsewhere = handlers(element, renderer);
  188. } else {
  189. i = 0;
  190. l = handlers.length;
  191. while (!isHandledElsewhere && i !== l) {
  192. isHandledElsewhere = handlers[i](element, renderer);
  193. i++;
  194. }
  195. }
  196. }
  197. return isHandledElsewhere;
  198. };
  199. tableToJson = function(table, renderer) {
  200. var data, headers, i, j, rowData, tableRow, table_obj, table_with, cell, l;
  201. data = [];
  202. headers = [];
  203. i = 0;
  204. l = table.rows[0].cells.length;
  205. table_with = table.clientWidth;
  206. while (i < l) {
  207. cell = table.rows[0].cells[i];
  208. headers[i] = {
  209. name: cell.textContent.toLowerCase().replace(/\s+/g,''),
  210. prompt: cell.textContent.replace(/\r?\n/g,''),
  211. width: (cell.clientWidth / table_with) * renderer.pdf.internal.pageSize.width
  212. };
  213. i++;
  214. }
  215. i = 1;
  216. while (i < table.rows.length) {
  217. tableRow = table.rows[i];
  218. rowData = {};
  219. j = 0;
  220. while (j < tableRow.cells.length) {
  221. rowData[headers[j].name] = tableRow.cells[j].textContent.replace(/\r?\n/g,'');
  222. j++;
  223. }
  224. data.push(rowData);
  225. i++;
  226. }
  227. return table_obj = {
  228. rows: data,
  229. headers: headers
  230. };
  231. };
  232. var SkipNode = {
  233. SCRIPT : 1,
  234. STYLE : 1,
  235. NOSCRIPT : 1,
  236. OBJECT : 1,
  237. EMBED : 1
  238. };
  239. DrillForContent = function(element, renderer, elementHandlers) {
  240. var cn, cns, fragmentCSS, i, isBlock, l, px2pt, table2json;
  241. cns = element.childNodes;
  242. cn = void 0;
  243. fragmentCSS = GetCSS(element);
  244. isBlock = fragmentCSS.display === "block";
  245. if (isBlock) {
  246. renderer.setBlockBoundary();
  247. renderer.setBlockStyle(fragmentCSS);
  248. }
  249. px2pt = 0.264583 * 72 / 25.4;
  250. i = 0;
  251. l = cns.length;
  252. while (i < l) {
  253. cn = cns[i];
  254. if (typeof cn === "object") {
  255. if (cn.nodeType === 8 && cn.nodeName === "#comment") {
  256. if (cn.textContent.match("ADD_PAGE")) {
  257. renderer.pdf.addPage();
  258. renderer.y = renderer.pdf.margins_doc.top;
  259. }
  260. } else if (cn.nodeType === 1 && !SkipNode[cn.nodeName]) {
  261. if (cn.nodeName === "IMG" && images[cn.getAttribute("src")]) {
  262. if ((renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom < renderer.y + cn.height) && (renderer.y > renderer.pdf.margins_doc.top)) {
  263. renderer.pdf.addPage();
  264. renderer.y = renderer.pdf.margins_doc.top;
  265. }
  266. renderer.pdf.addImage(images[cn.getAttribute("src")], renderer.x, renderer.y, cn.width, cn.height);
  267. renderer.y += cn.height;
  268. } else if (cn.nodeName === "TABLE") {
  269. table2json = tableToJson(cn, renderer);
  270. renderer.y += 10;
  271. renderer.pdf.table(renderer.x, renderer.y, table2json.rows, table2json.headers, {
  272. autoSize: false,
  273. printHeaders: true,
  274. margins: renderer.pdf.margins_doc
  275. });
  276. renderer.y = renderer.pdf.lastCellPos.y + renderer.pdf.lastCellPos.h + 20;
  277. } else {
  278. if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
  279. DrillForContent(cn, renderer, elementHandlers);
  280. }
  281. }
  282. } else if (cn.nodeType === 3) {
  283. renderer.addText(cn.nodeValue, fragmentCSS);
  284. } else if (typeof cn === "string") {
  285. renderer.addText(cn, fragmentCSS);
  286. }
  287. }
  288. i++;
  289. }
  290. if (isBlock) {
  291. return renderer.setBlockBoundary();
  292. }
  293. };
  294. images = {};
  295. loadImgs = function(element, renderer, elementHandlers, cb) {
  296. var imgs = element.getElementsByTagName('img'), l = imgs.length, x = 0;
  297. function done() {
  298. DrillForContent(element, renderer, elementHandlers);
  299. cb(renderer.dispose());
  300. }
  301. function loadImage(url) {
  302. if(!url) return;
  303. var img = new Image();
  304. ++x;img.crossOrigin='';
  305. img.onerror = img.onload = function() {
  306. if(img.complete && img.width + img.height)
  307. images[url] = images[url] || img;
  308. if(!--x) done();
  309. };
  310. img.src = url;
  311. }
  312. while(l--)
  313. loadImage(imgs[l].getAttribute("src"));
  314. cb = cb || function() {};
  315. return x || done();
  316. };
  317. process = function(pdf, element, x, y, settings, callback) {
  318. if (!element) return false;
  319. if (!element.parentNode) element = '' + element.innerHTML;
  320. if (typeof element === "string") {
  321. element = (function(element) {
  322. var $frame, $hiddendiv, framename, visuallyhidden;
  323. framename = "jsPDFhtmlText" + Date.now().toString() + (Math.random() * 1000).toFixed(0);
  324. visuallyhidden = "position: absolute !important;" + "clip: rect(1px 1px 1px 1px); /* IE6, IE7 */" + "clip: rect(1px, 1px, 1px, 1px);" + "padding:0 !important;" + "border:0 !important;" + "height: 1px !important;" + "width: 1px !important; " + "top:auto;" + "left:-100px;" + "overflow: hidden;";
  325. $hiddendiv = document.createElement('div');
  326. $hiddendiv.style.cssText = visuallyhidden;
  327. $hiddendiv.innerHTML = "<iframe style=\"height:1px;width:1px\" name=\"" + framename + "\" />";
  328. document.body.appendChild($hiddendiv);
  329. $frame = window.frames[framename];
  330. $frame.document.body.innerHTML = element;
  331. return $frame.document.body;
  332. })(element.replace(/<\/?script[^>]*?>/gi,''));
  333. }
  334. var r = new Renderer(pdf, x, y, settings);
  335. loadImgs.call(this, element, r, settings.elementHandlers, callback);
  336. return r.dispose();
  337. };
  338. Renderer.prototype.init = function() {
  339. this.paragraph = {
  340. text: [],
  341. style: []
  342. };
  343. return this.pdf.internal.write("q");
  344. };
  345. Renderer.prototype.dispose = function() {
  346. this.pdf.internal.write("Q");
  347. return {
  348. x: this.x,
  349. y: this.y
  350. };
  351. };
  352. Renderer.prototype.splitFragmentsIntoLines = function(fragments, styles) {
  353. var currentLineLength, defaultFontSize, ff, fontMetrics, fontMetricsCache, fragment, fragmentChopped, fragmentLength, fragmentSpecificMetrics, fs, k, line, lines, maxLineLength, style;
  354. defaultFontSize = 12;
  355. k = this.pdf.internal.scaleFactor;
  356. fontMetricsCache = {};
  357. ff = void 0;
  358. fs = void 0;
  359. fontMetrics = void 0;
  360. fragment = void 0;
  361. style = void 0;
  362. fragmentSpecificMetrics = void 0;
  363. fragmentLength = void 0;
  364. fragmentChopped = void 0;
  365. line = [];
  366. lines = [line];
  367. currentLineLength = 0;
  368. maxLineLength = this.settings.width;
  369. while (fragments.length) {
  370. fragment = fragments.shift();
  371. style = styles.shift();
  372. if (fragment) {
  373. ff = style["font-family"];
  374. fs = style["font-style"];
  375. fontMetrics = fontMetricsCache[ff + fs];
  376. if (!fontMetrics) {
  377. fontMetrics = this.pdf.internal.getFont(ff, fs).metadata.Unicode;
  378. fontMetricsCache[ff + fs] = fontMetrics;
  379. }
  380. fragmentSpecificMetrics = {
  381. widths: fontMetrics.widths,
  382. kerning: fontMetrics.kerning,
  383. fontSize: style["font-size"] * defaultFontSize,
  384. textIndent: currentLineLength
  385. };
  386. fragmentLength = this.pdf.getStringUnitWidth(fragment, fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  387. if (currentLineLength + fragmentLength > maxLineLength) {
  388. fragmentChopped = this.pdf.splitTextToSize(fragment, maxLineLength, fragmentSpecificMetrics);
  389. line.push([fragmentChopped.shift(), style]);
  390. while (fragmentChopped.length) {
  391. line = [[fragmentChopped.shift(), style]];
  392. lines.push(line);
  393. }
  394. currentLineLength = this.pdf.getStringUnitWidth(line[0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
  395. } else {
  396. line.push([fragment, style]);
  397. currentLineLength += fragmentLength;
  398. }
  399. }
  400. }
  401. return lines;
  402. };
  403. Renderer.prototype.RenderTextFragment = function(text, style) {
  404. var defaultFontSize, font;
  405. if (this.pdf.internal.pageSize.height - this.pdf.margins_doc.bottom < this.y + this.pdf.internal.getFontSize()) {
  406. this.pdf.internal.write("ET", "Q");
  407. this.pdf.addPage();
  408. this.y = this.pdf.margins_doc.top;
  409. this.pdf.internal.write("q", "BT", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  410. }
  411. defaultFontSize = 12;
  412. font = this.pdf.internal.getFont(style["font-family"], style["font-style"]);
  413. return this.pdf.internal.write("/" + font.id, (defaultFontSize * style["font-size"]).toFixed(2), "Tf", "(" + this.pdf.internal.pdfEscape(text) + ") Tj");
  414. };
  415. Renderer.prototype.renderParagraph = function() {
  416. var blockstyle, defaultFontSize, fontToUnitRatio, fragments, i, l, line, lines, maxLineHeight, out, paragraphspacing_after, paragraphspacing_before, priorblockstype, styles;
  417. fragments = PurgeWhiteSpace(this.paragraph.text);
  418. styles = this.paragraph.style;
  419. blockstyle = this.paragraph.blockstyle;
  420. priorblockstype = this.paragraph.blockstyle || {};
  421. this.paragraph = {
  422. text: [],
  423. style: [],
  424. blockstyle: {},
  425. priorblockstyle: blockstyle
  426. };
  427. if (!fragments.join("").trim()) {
  428. return;
  429. }
  430. lines = this.splitFragmentsIntoLines(fragments, styles);
  431. line = void 0;
  432. maxLineHeight = void 0;
  433. defaultFontSize = 12;
  434. fontToUnitRatio = defaultFontSize / this.pdf.internal.scaleFactor;
  435. paragraphspacing_before = (Math.max((blockstyle["margin-top"] || 0) - (priorblockstype["margin-bottom"] || 0), 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
  436. paragraphspacing_after = ((blockstyle["margin-bottom"] || 0) + (blockstyle["padding-bottom"] || 0)) * fontToUnitRatio;
  437. out = this.pdf.internal.write;
  438. i = void 0;
  439. l = void 0;
  440. this.y += paragraphspacing_before;
  441. out("q", "BT", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
  442. while (lines.length) {
  443. line = lines.shift();
  444. maxLineHeight = 0;
  445. i = 0;
  446. l = line.length;
  447. while (i !== l) {
  448. if (line[i][0].trim()) {
  449. maxLineHeight = Math.max(maxLineHeight, line[i][1]["line-height"], line[i][1]["font-size"]);
  450. }
  451. i++;
  452. }
  453. out(0, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
  454. i = 0;
  455. l = line.length;
  456. while (i !== l) {
  457. if (line[i][0]) {
  458. this.RenderTextFragment(line[i][0], line[i][1]);
  459. }
  460. i++;
  461. }
  462. this.y += maxLineHeight * fontToUnitRatio;
  463. }
  464. out("ET", "Q");
  465. return this.y += paragraphspacing_after;
  466. };
  467. Renderer.prototype.setBlockBoundary = function() {
  468. return this.renderParagraph();
  469. };
  470. Renderer.prototype.setBlockStyle = function(css) {
  471. return this.paragraph.blockstyle = css;
  472. };
  473. Renderer.prototype.addText = function(text, css) {
  474. this.paragraph.text.push(text);
  475. return this.paragraph.style.push(css);
  476. };
  477. FontNameDB = {
  478. helvetica: "helvetica",
  479. "sans-serif": "helvetica",
  480. serif: "times",
  481. times: "times",
  482. "times new roman": "times",
  483. monospace: "courier",
  484. courier: "courier"
  485. };
  486. FontWeightMap = {
  487. 100: "normal",
  488. 200: "normal",
  489. 300: "normal",
  490. 400: "normal",
  491. 500: "bold",
  492. 600: "bold",
  493. 700: "bold",
  494. 800: "bold",
  495. 900: "bold",
  496. normal: "normal",
  497. bold: "bold",
  498. bolder: "bold",
  499. lighter: "normal"
  500. };
  501. FontStyleMap = {
  502. normal: "normal",
  503. italic: "italic",
  504. oblique: "italic"
  505. };
  506. UnitedNumberMap = {
  507. normal: 1
  508. /*
  509. Converts HTML-formatted text into formatted PDF text.
  510. Notes:
  511. 2012-07-18
  512. Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed.
  513. Plugin relies on jQuery for CSS extraction.
  514. Targeting HTML output from Markdown templating, which is a very simple
  515. markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.)
  516. Images, tables are NOT supported.
  517. @public
  518. @function
  519. @param HTML {String or DOM Element} HTML-formatted text, or pointer to DOM element that is to be rendered into PDF.
  520. @param x {Number} starting X coordinate in jsPDF instance's declared units.
  521. @param y {Number} starting Y coordinate in jsPDF instance's declared units.
  522. @param settings {Object} Additional / optional variables controlling parsing, rendering.
  523. @returns {Object} jsPDF instance
  524. */
  525. };
  526. return jsPDFAPI.fromHTML = function(HTML, x, y, settings, callback, margins) {
  527. "use strict";
  528. this.margins_doc = margins || {top:0,bottom:0};
  529. if(!settings) settings = {};
  530. if(!settings.elementHandlers) settings.elementHandlers = {};
  531. return process(this, HTML, x || 4, y || 4, settings, callback);
  532. };
  533. })(jsPDF.API);