jspdf.js 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943
  1. /** @preserve jsPDF 0.9.0rc2 ( ${buildDate} ${commitID} )
  2. Copyright (c) 2010-2012 James Hall, james@snapshotmedia.co.uk, https://github.com/MrRio/jsPDF
  3. Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  4. MIT license.
  5. */
  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. /**
  28. Creates new jsPDF document object instance
  29. @class
  30. @param orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
  31. @param unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"
  32. @param format One of 'a0', 'a1', 'a2', 'a3', 'a4' (Default) etc to 'a10', 'b0' to 'b10', 'c0' to 'c10', 'letter', 'government-letter', 'legal', 'junior-legal', 'ledger' or 'tabloid'
  33. @returns {jsPDF}
  34. @name jsPDF
  35. */
  36. var jsPDF = (function () {
  37. 'use strict';
  38. /*jslint browser:true, plusplus: true, bitwise: true, nomen: true */
  39. /*global document: false, btoa, atob, zpipe, Uint8Array, ArrayBuffer, Blob, saveAs, adler32cs, Deflater */
  40. // this will run on <=IE9, possibly some niche browsers
  41. // new webkit-based, FireFox, IE10 already have native version of this.
  42. if (typeof btoa === 'undefined') {
  43. window.btoa = function (data) {
  44. // DO NOT ADD UTF8 ENCODING CODE HERE!!!!
  45. // UTF8 encoding encodes bytes over char code 128
  46. // and, essentially, turns an 8-bit binary streams
  47. // (that base64 can deal with) into 7-bit binary streams.
  48. // (by default server does not know that and does not recode the data back to 8bit)
  49. // You destroy your data.
  50. // binary streams like jpeg image data etc, while stored in JavaScript strings,
  51. // (which are 16bit arrays) are in 8bit format already.
  52. // You do NOT need to char-encode that before base64 encoding.
  53. // if you, by act of fate
  54. // have string which has individual characters with code
  55. // above 255 (pure unicode chars), encode that BEFORE you base64 here.
  56. // you can use absolutely any approch there, as long as in the end,
  57. // base64 gets an 8bit (char codes 0 - 255) stream.
  58. // when you get it on the server after un-base64, you must
  59. // UNencode it too, to get back to 16, 32bit or whatever original bin stream.
  60. // Note, Yes, JavaScript strings are, in most cases UCS-2 -
  61. // 16-bit character arrays. This does not mean, however,
  62. // that you always have to UTF8 it before base64.
  63. // it means that if you have actual characters anywhere in
  64. // that string that have char code above 255, you need to
  65. // recode *entire* string from 16-bit (or 32bit) to 8-bit array.
  66. // You can do binary split to UTF16 (BE or LE)
  67. // you can do utf8, you can split the thing by hand and prepend BOM to it,
  68. // but whatever you do, make sure you mirror the opposite on
  69. // the server. If server does not expect to post-process un-base64
  70. // 8-bit binary stream, think very very hard about messing around with encoding.
  71. // so, long story short:
  72. // DO NOT ADD UTF8 ENCODING CODE HERE!!!!
  73. /* @preserve
  74. ====================================================================
  75. base64 encoder
  76. MIT, GPL
  77. version: 1109.2015
  78. discuss at: http://phpjs.org/functions/base64_encode
  79. + original by: Tyler Akins (http://rumkin.com)
  80. + improved by: Bayron Guevara
  81. + improved by: Thunder.m
  82. + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  83. + bugfixed by: Pellentesque Malesuada
  84. + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  85. + improved by: Rafal Kukawski (http://kukawski.pl)
  86. + Daniel Dotsenko, Willow Systems Corp, willow-systems.com
  87. ====================================================================
  88. */
  89. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  90. b64a = b64.split(''),
  91. o1,
  92. o2,
  93. o3,
  94. h1,
  95. h2,
  96. h3,
  97. h4,
  98. bits,
  99. i = 0,
  100. ac = 0,
  101. enc = "",
  102. tmp_arr = [],
  103. r;
  104. do { // pack three octets into four hexets
  105. o1 = data.charCodeAt(i++);
  106. o2 = data.charCodeAt(i++);
  107. o3 = data.charCodeAt(i++);
  108. bits = o1 << 16 | o2 << 8 | o3;
  109. h1 = bits >> 18 & 0x3f;
  110. h2 = bits >> 12 & 0x3f;
  111. h3 = bits >> 6 & 0x3f;
  112. h4 = bits & 0x3f;
  113. // use hexets to index into b64, and append result to encoded string
  114. tmp_arr[ac++] = b64a[h1] + b64a[h2] + b64a[h3] + b64a[h4];
  115. } while (i < data.length);
  116. enc = tmp_arr.join('');
  117. r = data.length % 3;
  118. return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
  119. // end of base64 encoder MIT, GPL
  120. };
  121. }
  122. if (typeof atob === 'undefined') {
  123. window.atob = function (data) {
  124. // http://kevin.vanzonneveld.net
  125. // + original by: Tyler Akins (http://rumkin.com)
  126. // + improved by: Thunder.m
  127. // + input by: Aman Gupta
  128. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  129. // + bugfixed by: Onno Marsman
  130. // + bugfixed by: Pellentesque Malesuada
  131. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  132. // + input by: Brett Zamir (http://brett-zamir.me)
  133. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  134. // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  135. // * returns 1: 'Kevin van Zonneveld'
  136. // mozilla has this native
  137. // - but breaks in 2.0.0.12!
  138. //if (typeof this.window['atob'] == 'function') {
  139. // return atob(data);
  140. //}
  141. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  142. o1,
  143. o2,
  144. o3,
  145. h1,
  146. h2,
  147. h3,
  148. h4,
  149. bits,
  150. i = 0,
  151. ac = 0,
  152. dec = "",
  153. tmp_arr = [];
  154. if (!data) {
  155. return data;
  156. }
  157. data += '';
  158. do { // unpack four hexets into three octets using index points in b64
  159. h1 = b64.indexOf(data.charAt(i++));
  160. h2 = b64.indexOf(data.charAt(i++));
  161. h3 = b64.indexOf(data.charAt(i++));
  162. h4 = b64.indexOf(data.charAt(i++));
  163. bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
  164. o1 = bits >> 16 & 0xff;
  165. o2 = bits >> 8 & 0xff;
  166. o3 = bits & 0xff;
  167. if (h3 === 64) {
  168. tmp_arr[ac++] = String.fromCharCode(o1);
  169. } else if (h4 === 64) {
  170. tmp_arr[ac++] = String.fromCharCode(o1, o2);
  171. } else {
  172. tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
  173. }
  174. } while (i < data.length);
  175. dec = tmp_arr.join('');
  176. return dec;
  177. };
  178. }
  179. var getObjectLength = typeof Object.keys === 'function' ?
  180. function (object) {
  181. return Object.keys(object).length;
  182. } :
  183. function (object) {
  184. var i = 0, e;
  185. for (e in object) {
  186. if (object.hasOwnProperty(e)) {
  187. i++;
  188. }
  189. }
  190. return i;
  191. },
  192. /**
  193. PubSub implementation
  194. @class
  195. @name PubSub
  196. */
  197. PubSub = function (context) {
  198. /** @preserve
  199. -----------------------------------------------------------------------------------------------
  200. JavaScript PubSub library
  201. 2012 (c) ddotsenko@willowsystems.com
  202. based on Peter Higgins (dante@dojotoolkit.org)
  203. Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
  204. Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
  205. http://dojofoundation.org/license for more information.
  206. -----------------------------------------------------------------------------------------------
  207. */
  208. /**
  209. @private
  210. @fieldOf PubSub
  211. */
  212. this.topics = {};
  213. /**
  214. Stores what will be `this` within the callback functions.
  215. @private
  216. @fieldOf PubSub#
  217. */
  218. this.context = context;
  219. /**
  220. Allows caller to emit an event and pass arguments to event listeners.
  221. @public
  222. @function
  223. @param topic {String} Name of the channel on which to voice this event
  224. @param args Any number of arguments you want to pass to the listeners of this event.
  225. @methodOf PubSub#
  226. @name publish
  227. */
  228. this.publish = function (topic, args) {
  229. if (this.topics[topic]) {
  230. var currentTopic = this.topics[topic],
  231. toremove = [],
  232. fn,
  233. i,
  234. l,
  235. pair,
  236. emptyFunc = function () {};
  237. args = Array.prototype.slice.call(arguments, 1);
  238. for (i = 0, l = currentTopic.length; i < l; i++) {
  239. pair = currentTopic[i]; // this is a [function, once_flag] array
  240. fn = pair[0];
  241. if (pair[1]) { /* 'run once' flag set */
  242. pair[0] = emptyFunc;
  243. toremove.push(i);
  244. }
  245. fn.apply(this.context, args);
  246. }
  247. for (i = 0, l = toremove.length; i < l; i++) {
  248. currentTopic.splice(toremove[i], 1);
  249. }
  250. }
  251. };
  252. /**
  253. Allows listener code to subscribe to channel and be called when data is available
  254. @public
  255. @function
  256. @param topic {String} Name of the channel on which to voice this event
  257. @param callback {Function} Executable (function pointer) that will be ran when event is voiced on this channel.
  258. @param once {Boolean} (optional. False by default) Flag indicating if the function is to be triggered only once.
  259. @returns {Object} A token object that cen be used for unsubscribing.
  260. @methodOf PubSub#
  261. @name subscribe
  262. */
  263. this.subscribe = function (topic, callback, once) {
  264. if (!this.topics[topic]) {
  265. this.topics[topic] = [[callback, once]];
  266. } else {
  267. this.topics[topic].push([callback, once]);
  268. }
  269. return {
  270. "topic": topic,
  271. "callback": callback
  272. };
  273. };
  274. /**
  275. Allows listener code to unsubscribe from a channel
  276. @public
  277. @function
  278. @param token {Object} A token object that was returned by `subscribe` method
  279. @methodOf PubSub#
  280. @name unsubscribe
  281. */
  282. this.unsubscribe = function (token) {
  283. if (this.topics[token.topic]) {
  284. var currentTopic = this.topics[token.topic], i, l;
  285. for (i = 0, l = currentTopic.length; i < l; i++) {
  286. if (currentTopic[i][0] === token.callback) {
  287. currentTopic.splice(i, 1);
  288. }
  289. }
  290. }
  291. };
  292. };
  293. /**
  294. @constructor
  295. @private
  296. */
  297. function jsPDF(orientation, unit, format, compressPdf) { /** String orientation, String unit, String format, Boolean compressed */
  298. // Default parameter values
  299. if (typeof orientation === 'undefined') {
  300. orientation = 'p';
  301. } else {
  302. orientation = orientation.toString().toLowerCase();
  303. }
  304. if (typeof unit === 'undefined') { unit = 'mm'; }
  305. if (typeof format === 'undefined') { format = 'a4'; }
  306. if (typeof compressPdf === 'undefined' && typeof zpipe === 'undefined') { compressPdf = false; }
  307. var format_as_string = format.toString().toLowerCase(),
  308. version = '0.9.0rc2',
  309. content = [],
  310. content_length = 0,
  311. compress = compressPdf,
  312. pdfVersion = '1.3', // PDF Version
  313. pageFormats = { // Size in pt of various paper formats
  314. 'a0': [2383.94, 3370.39],
  315. 'a1': [1683.78, 2383.94],
  316. 'a2': [1190.55, 1683.78],
  317. 'a3': [841.89, 1190.55],
  318. 'a4': [595.28, 841.89],
  319. 'a5': [419.53, 595.28],
  320. 'a6': [297.64, 419.53],
  321. 'a7': [209.76, 297.64],
  322. 'a8': [147.4 , 209.76],
  323. 'a9': [104.88, 147.4],
  324. 'a10': [73.7, 104.88],
  325. 'b0': [2834.65, 4008.19],
  326. 'b1': [2004.09, 2834.65],
  327. 'b2': [1417.32, 2004.09],
  328. 'b3': [1000.63, 1417.32],
  329. 'b4': [708.66, 1000.63],
  330. 'b5': [498.9, 708.66],
  331. 'b6': [354.33, 498.9],
  332. 'b7': [249.45, 354.33],
  333. 'b8': [175.75, 249.45],
  334. 'b9': [124.72, 175.75],
  335. 'b10': [87.87, 124.72],
  336. 'c0': [2599.37, 3676.54],
  337. 'c1': [1836.85, 2599.37],
  338. 'c2': [1298.27, 1836.85],
  339. 'c3': [918.43, 1298.27],
  340. 'c4': [649.13, 918.43],
  341. 'c5': [459.21, 649.13],
  342. 'c6': [323.15, 459.21],
  343. 'c7': [229.61, 323.15],
  344. 'c8': [161.57, 229.61],
  345. 'c9': [113.39, 161.57],
  346. 'c10': [79.37, 113.39],
  347. 'letter': [612, 792],
  348. 'government-letter': [576, 756],
  349. 'legal': [612, 1008],
  350. 'junior-legal': [576, 360],
  351. 'ledger': [1224, 792],
  352. 'tabloid': [792, 1224]
  353. },
  354. textColor = '0 g',
  355. drawColor = '0 G',
  356. page = 0,
  357. pages = [],
  358. objectNumber = 2, // 'n' Current object number
  359. outToPages = false, // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
  360. offsets = [], // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
  361. fonts = {}, // collection of font objects, where key is fontKey - a dynamically created label for a given font.
  362. fontmap = {}, // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
  363. activeFontSize = 16,
  364. activeFontKey, // will be string representing the KEY of the font as combination of fontName + fontStyle
  365. lineWidth = 0.200025, // 2mm
  366. lineHeightProportion = 1.15,
  367. pageHeight,
  368. pageWidth,
  369. k, // Scale factor
  370. documentProperties = {'title': '', 'subject': '', 'author': '', 'keywords': '', 'creator': ''},
  371. lineCapID = 0,
  372. lineJoinID = 0,
  373. API = {},
  374. events = new PubSub(API),
  375. tmp,
  376. plugin,
  377. /////////////////////
  378. // Private functions
  379. /////////////////////
  380. // simplified (speedier) replacement for sprintf's %.2f conversion
  381. f2 = function (number) {
  382. return number.toFixed(2);
  383. },
  384. // simplified (speedier) replacement for sprintf's %.3f conversion
  385. f3 = function (number) {
  386. return number.toFixed(3);
  387. },
  388. // simplified (speedier) replacement for sprintf's %02d
  389. padd2 = function (number) {
  390. var n = (number).toFixed(0);
  391. if (number < 10) {
  392. return '0' + n;
  393. } else {
  394. return n;
  395. }
  396. },
  397. // simplified (speedier) replacement for sprintf's %02d
  398. padd10 = function (number) {
  399. var n = (number).toFixed(0);
  400. if (n.length < 10) {
  401. return new Array( 11 - n.length ).join('0') + n;
  402. } else {
  403. return n;
  404. }
  405. },
  406. out = function (string) {
  407. if (outToPages) { /* set by beginPage */
  408. pages[page].push(string);
  409. } else {
  410. content.push(string);
  411. content_length += string.length + 1; // +1 is for '\n' that will be used to join contents of content
  412. }
  413. },
  414. newObject = function () {
  415. // Begin a new object
  416. objectNumber++;
  417. offsets[objectNumber] = content_length;
  418. out(objectNumber + ' 0 obj');
  419. return objectNumber;
  420. },
  421. putStream = function (str) {
  422. out('stream');
  423. out(str);
  424. out('endstream');
  425. },
  426. wPt,
  427. hPt,
  428. kids,
  429. i,
  430. putPages = function () {
  431. wPt = pageWidth * k;
  432. hPt = pageHeight * k;
  433. // outToPages = false as set in endDocument(). out() writes to content.
  434. var n, p, arr, uint, i, deflater, adler32;
  435. for (n = 1; n <= page; n++) {
  436. newObject();
  437. out('<</Type /Page');
  438. out('/Parent 1 0 R');
  439. out('/Resources 2 0 R');
  440. out('/Contents ' + (objectNumber + 1) + ' 0 R>>');
  441. out('endobj');
  442. // Page content
  443. p = pages[n].join('\n');
  444. newObject();
  445. if (compress) {
  446. arr = [];
  447. for (i = 0; i < p.length; ++i) {
  448. arr[i] = p.charCodeAt(i);
  449. }
  450. adler32 = adler32cs.from(p);
  451. deflater = new Deflater(6);
  452. deflater.append(new Uint8Array(arr));
  453. p = deflater.flush();
  454. arr = [new Uint8Array([120, 156]), new Uint8Array(p),
  455. new Uint8Array([adler32 & 0xFF, (adler32 >> 8) & 0xFF, (adler32 >> 16) & 0xFF, (adler32 >> 24) & 0xFF])];
  456. p = '';
  457. for (i in arr) {
  458. if (arr.hasOwnProperty(i)) {
  459. p += String.fromCharCode.apply(null, arr[i]);
  460. }
  461. }
  462. out('<</Length ' + p.length + ' /Filter [/FlateDecode]>>');
  463. } else {
  464. out('<</Length ' + p.length + '>>');
  465. }
  466. putStream(p);
  467. out('endobj');
  468. }
  469. offsets[1] = content_length;
  470. out('1 0 obj');
  471. out('<</Type /Pages');
  472. kids = '/Kids [';
  473. for (i = 0; i < page; i++) {
  474. kids += (3 + 2 * i) + ' 0 R ';
  475. }
  476. out(kids + ']');
  477. out('/Count ' + page);
  478. out('/MediaBox [0 0 ' + f2(wPt) + ' ' + f2(hPt) + ']');
  479. out('>>');
  480. out('endobj');
  481. },
  482. putFont = function (font) {
  483. font.objectNumber = newObject();
  484. out('<</BaseFont/' + font.PostScriptName + '/Type/Font');
  485. if (typeof font.encoding === 'string') {
  486. out('/Encoding/' + font.encoding);
  487. }
  488. out('/Subtype/Type1>>');
  489. out('endobj');
  490. },
  491. putFonts = function () {
  492. var fontKey;
  493. for (fontKey in fonts) {
  494. if (fonts.hasOwnProperty(fontKey)) {
  495. putFont(fonts[fontKey]);
  496. }
  497. }
  498. },
  499. putXobjectDict = function () {
  500. // Loop through images, or other data objects
  501. events.publish('putXobjectDict');
  502. },
  503. putResourceDictionary = function () {
  504. out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
  505. out('/Font <<');
  506. // Do this for each font, the '1' bit is the index of the font
  507. var fontKey;
  508. for (fontKey in fonts) {
  509. if (fonts.hasOwnProperty(fontKey)) {
  510. out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
  511. }
  512. }
  513. out('>>');
  514. out('/XObject <<');
  515. putXobjectDict();
  516. out('>>');
  517. },
  518. putResources = function () {
  519. putFonts();
  520. events.publish('putResources');
  521. // Resource dictionary
  522. offsets[2] = content_length;
  523. out('2 0 obj');
  524. out('<<');
  525. putResourceDictionary();
  526. out('>>');
  527. out('endobj');
  528. events.publish('postPutResources');
  529. },
  530. addToFontDictionary = function (fontKey, fontName, fontStyle) {
  531. // this is mapping structure for quick font key lookup.
  532. // returns the KEY of the font (ex: "F1") for a given pair of font name and type (ex: "Arial". "Italic")
  533. var undef;
  534. if (fontmap[fontName] === undef) {
  535. fontmap[fontName] = {}; // fontStyle is a var interpreted and converted to appropriate string. don't wrap in quotes.
  536. }
  537. fontmap[fontName][fontStyle] = fontKey;
  538. },
  539. /**
  540. FontObject describes a particular font as member of an instnace of jsPDF
  541. It's a collection of properties like 'id' (to be used in PDF stream),
  542. 'fontName' (font's family name), 'fontStyle' (font's style variant label)
  543. @class
  544. @public
  545. @property id {String} PDF-document-instance-specific label assinged to the font.
  546. @property PostScriptName {String} PDF specification full name for the font
  547. @property encoding {Object} Encoding_name-to-Font_metrics_object mapping.
  548. @name FontObject
  549. */
  550. FontObject = {},
  551. addFont = function (PostScriptName, fontName, fontStyle, encoding) {
  552. var fontKey = 'F' + (getObjectLength(fonts) + 1).toString(10),
  553. // This is FontObject
  554. font = fonts[fontKey] = {
  555. 'id': fontKey,
  556. // , 'objectNumber': will be set by putFont()
  557. 'PostScriptName': PostScriptName,
  558. 'fontName': fontName,
  559. 'fontStyle': fontStyle,
  560. 'encoding': encoding,
  561. 'metadata': {}
  562. };
  563. addToFontDictionary(fontKey, fontName, fontStyle);
  564. events.publish('addFont', font);
  565. return fontKey;
  566. },
  567. addFonts = function () {
  568. var HELVETICA = "helvetica",
  569. TIMES = "times",
  570. COURIER = "courier",
  571. NORMAL = "normal",
  572. BOLD = "bold",
  573. ITALIC = "italic",
  574. BOLD_ITALIC = "bolditalic",
  575. encoding = 'StandardEncoding',
  576. standardFonts = [
  577. ['Helvetica', HELVETICA, NORMAL],
  578. ['Helvetica-Bold', HELVETICA, BOLD],
  579. ['Helvetica-Oblique', HELVETICA, ITALIC],
  580. ['Helvetica-BoldOblique', HELVETICA, BOLD_ITALIC],
  581. ['Courier', COURIER, NORMAL],
  582. ['Courier-Bold', COURIER, BOLD],
  583. ['Courier-Oblique', COURIER, ITALIC],
  584. ['Courier-BoldOblique', COURIER, BOLD_ITALIC],
  585. ['Times-Roman', TIMES, NORMAL],
  586. ['Times-Bold', TIMES, BOLD],
  587. ['Times-Italic', TIMES, ITALIC],
  588. ['Times-BoldItalic', TIMES, BOLD_ITALIC]
  589. ],
  590. i,
  591. l,
  592. fontKey,
  593. parts;
  594. for (i = 0, l = standardFonts.length; i < l; i++) {
  595. fontKey = addFont(
  596. standardFonts[i][0],
  597. standardFonts[i][1],
  598. standardFonts[i][2],
  599. encoding
  600. );
  601. // adding aliases for standard fonts, this time matching the capitalization
  602. parts = standardFonts[i][0].split('-');
  603. addToFontDictionary(fontKey, parts[0], parts[1] || '');
  604. }
  605. events.publish('addFonts', {'fonts': fonts, 'dictionary': fontmap});
  606. },
  607. /**
  608. @public
  609. @function
  610. @param text {String}
  611. @param flags {Object} Encoding flags.
  612. @returns {String} Encoded string
  613. */
  614. to8bitStream = function (text, flags) {
  615. /* PDF 1.3 spec:
  616. "For text strings encoded in Unicode, the first two bytes must be 254 followed by
  617. 255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
  618. with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
  619. to be a meaningful beginning of a word or phrase.) The remainder of the
  620. string consists of Unicode character codes, according to the UTF-16 encoding
  621. specified in the Unicode standard, version 2.0. Commonly used Unicode values
  622. are represented as 2 bytes per character, with the high-order byte appearing first
  623. in the string."
  624. In other words, if there are chars in a string with char code above 255, we
  625. recode the string to UCS2 BE - string doubles in length and BOM is prepended.
  626. HOWEVER!
  627. Actual *content* (body) text (as opposed to strings used in document properties etc)
  628. does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
  629. Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
  630. a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
  631. fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
  632. code page. There, however, all characters in the stream are treated as GIDs,
  633. including BOM, which is the reason we need to skip BOM in content text (i.e. that
  634. that is tied to a font).
  635. To signal this "special" PDFEscape / to8bitStream handling mode,
  636. API.text() function sets (unless you overwrite it with manual values
  637. given to API.text(.., flags) )
  638. flags.autoencode = true
  639. flags.noBOM = true
  640. */
  641. /*
  642. `flags` properties relied upon:
  643. .sourceEncoding = string with encoding label.
  644. "Unicode" by default. = encoding of the incoming text.
  645. pass some non-existing encoding name
  646. (ex: 'Do not touch my strings! I know what I am doing.')
  647. to make encoding code skip the encoding step.
  648. .outputEncoding = Either valid PDF encoding name
  649. (must be supported by jsPDF font metrics, otherwise no encoding)
  650. or a JS object, where key = sourceCharCode, value = outputCharCode
  651. missing keys will be treated as: sourceCharCode === outputCharCode
  652. .noBOM
  653. See comment higher above for explanation for why this is important
  654. .autoencode
  655. See comment higher above for explanation for why this is important
  656. */
  657. var i, l, undef, sourceEncoding, encodingBlock, outputEncoding, newtext, isUnicode, ch, bch;
  658. if (flags === undef) {
  659. flags = {};
  660. }
  661. sourceEncoding = flags.sourceEncoding ? sourceEncoding : 'Unicode';
  662. outputEncoding = flags.outputEncoding;
  663. // This 'encoding' section relies on font metrics format
  664. // attached to font objects by, among others,
  665. // "Willow Systems' standard_font_metrics plugin"
  666. // see jspdf.plugin.standard_font_metrics.js for format
  667. // of the font.metadata.encoding Object.
  668. // It should be something like
  669. // .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
  670. // .widths = {0:width, code:width, ..., 'fof':divisor}
  671. // .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
  672. if ((flags.autoencode || outputEncoding) &&
  673. fonts[activeFontKey].metadata &&
  674. fonts[activeFontKey].metadata[sourceEncoding] &&
  675. fonts[activeFontKey].metadata[sourceEncoding].encoding
  676. ) {
  677. encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding;
  678. // each font has default encoding. Some have it clearly defined.
  679. if (!outputEncoding && fonts[activeFontKey].encoding) {
  680. outputEncoding = fonts[activeFontKey].encoding;
  681. }
  682. // Hmmm, the above did not work? Let's try again, in different place.
  683. if (!outputEncoding && encodingBlock.codePages) {
  684. outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
  685. }
  686. if (typeof outputEncoding === 'string') {
  687. outputEncoding = encodingBlock[outputEncoding];
  688. }
  689. // we want output encoding to be a JS Object, where
  690. // key = sourceEncoding's character code and
  691. // value = outputEncoding's character code.
  692. if (outputEncoding) {
  693. isUnicode = false;
  694. newtext = [];
  695. for (i = 0, l = text.length; i < l; i++) {
  696. ch = outputEncoding[text.charCodeAt(i)];
  697. if (ch) {
  698. newtext.push(
  699. String.fromCharCode(ch)
  700. );
  701. } else {
  702. newtext.push(
  703. text[i]
  704. );
  705. }
  706. // since we are looping over chars anyway, might as well
  707. // check for residual unicodeness
  708. if (newtext[i].charCodeAt(0) >> 8) { /* more than 255 */
  709. isUnicode = true;
  710. }
  711. }
  712. text = newtext.join('');
  713. }
  714. }
  715. i = text.length;
  716. // isUnicode may be set to false above. Hence the triple-equal to undefined
  717. while (isUnicode === undef && i !== 0) {
  718. if (text.charCodeAt(i - 1) >> 8) { /* more than 255 */
  719. isUnicode = true;
  720. }
  721. i--;
  722. }
  723. if (!isUnicode) {
  724. return text;
  725. } else {
  726. newtext = flags.noBOM ? [] : [254, 255];
  727. for (i = 0, l = text.length; i < l; i++) {
  728. ch = text.charCodeAt(i);
  729. bch = ch >> 8; // divide by 256
  730. if (bch >> 8) { /* something left after dividing by 256 second time */
  731. throw new Error("Character at position " + i.toString(10) + " of string '" + text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
  732. }
  733. newtext.push(bch);
  734. newtext.push(ch - (bch << 8));
  735. }
  736. return String.fromCharCode.apply(undef, newtext);
  737. }
  738. },
  739. // Replace '/', '(', and ')' with pdf-safe versions
  740. pdfEscape = function (text, flags) {
  741. // doing to8bitStream does NOT make this PDF display unicode text. For that
  742. // we also need to reference a unicode font and embed it - royal pain in the rear.
  743. // There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
  744. // which JavaScript Strings are happy to provide. So, while we still cannot display
  745. // 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
  746. // 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
  747. // is still parseable.
  748. // This will allow immediate support for unicode in document properties strings.
  749. return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
  750. },
  751. putInfo = function () {
  752. out('/Producer (jsPDF ' + version + ')');
  753. if (documentProperties.title) {
  754. out('/Title (' + pdfEscape(documentProperties.title) + ')');
  755. }
  756. if (documentProperties.subject) {
  757. out('/Subject (' + pdfEscape(documentProperties.subject) + ')');
  758. }
  759. if (documentProperties.author) {
  760. out('/Author (' + pdfEscape(documentProperties.author) + ')');
  761. }
  762. if (documentProperties.keywords) {
  763. out('/Keywords (' + pdfEscape(documentProperties.keywords) + ')');
  764. }
  765. if (documentProperties.creator) {
  766. out('/Creator (' + pdfEscape(documentProperties.creator) + ')');
  767. }
  768. var created = new Date();
  769. out('/CreationDate (D:' +
  770. [
  771. created.getFullYear(),
  772. padd2(created.getMonth() + 1),
  773. padd2(created.getDate()),
  774. padd2(created.getHours()),
  775. padd2(created.getMinutes()),
  776. padd2(created.getSeconds())
  777. ].join('') +
  778. ')'
  779. );
  780. },
  781. putCatalog = function () {
  782. out('/Type /Catalog');
  783. out('/Pages 1 0 R');
  784. // @TODO: Add zoom and layout modes
  785. out('/OpenAction [3 0 R /FitH null]');
  786. out('/PageLayout /OneColumn');
  787. events.publish('putCatalog');
  788. },
  789. putTrailer = function () {
  790. out('/Size ' + (objectNumber + 1));
  791. out('/Root ' + objectNumber + ' 0 R');
  792. out('/Info ' + (objectNumber - 1) + ' 0 R');
  793. },
  794. beginPage = function () {
  795. page++;
  796. // Do dimension stuff
  797. outToPages = true;
  798. pages[page] = [];
  799. },
  800. _addPage = function () {
  801. beginPage();
  802. // Set line width
  803. out(f2(lineWidth * k) + ' w');
  804. // Set draw color
  805. out(drawColor);
  806. // resurrecting non-default line caps, joins
  807. if (lineCapID !== 0) {
  808. out(lineCapID.toString(10) + ' J');
  809. }
  810. if (lineJoinID !== 0) {
  811. out(lineJoinID.toString(10) + ' j');
  812. }
  813. events.publish('addPage', {'pageNumber': page});
  814. },
  815. /**
  816. Returns a document-specific font key - a label assigned to a
  817. font name + font type combination at the time the font was added
  818. to the font inventory.
  819. Font key is used as label for the desired font for a block of text
  820. to be added to the PDF document stream.
  821. @private
  822. @function
  823. @param fontName {String} can be undefined on "falthy" to indicate "use current"
  824. @param fontStyle {String} can be undefined on "falthy" to indicate "use current"
  825. @returns {String} Font key.
  826. */
  827. getFont = function (fontName, fontStyle) {
  828. var key, undef;
  829. if (fontName === undef) {
  830. fontName = fonts[activeFontKey].fontName;
  831. }
  832. if (fontStyle === undef) {
  833. fontStyle = fonts[activeFontKey].fontStyle;
  834. }
  835. try {
  836. key = fontmap[fontName][fontStyle]; // returns a string like 'F3' - the KEY corresponding tot he font + type combination.
  837. } catch (e) {
  838. key = undef;
  839. }
  840. if (!key) {
  841. throw new Error("Unable to look up font label for font '" + fontName + "', '" + fontStyle + "'. Refer to getFontList() for available fonts.");
  842. }
  843. return key;
  844. },
  845. buildDocument = function () {
  846. outToPages = false; // switches out() to content
  847. content = [];
  848. offsets = [];
  849. // putHeader()
  850. out('%PDF-' + pdfVersion);
  851. putPages();
  852. putResources();
  853. // Info
  854. newObject();
  855. out('<<');
  856. putInfo();
  857. out('>>');
  858. out('endobj');
  859. // Catalog
  860. newObject();
  861. out('<<');
  862. putCatalog();
  863. out('>>');
  864. out('endobj');
  865. // Cross-ref
  866. var o = content_length, i;
  867. out('xref');
  868. out('0 ' + (objectNumber + 1));
  869. out('0000000000 65535 f ');
  870. for (i = 1; i <= objectNumber; i++) {
  871. out(padd10(offsets[i]) + ' 00000 n ');
  872. }
  873. // Trailer
  874. out('trailer');
  875. out('<<');
  876. putTrailer();
  877. out('>>');
  878. out('startxref');
  879. out(o);
  880. out('%%EOF');
  881. outToPages = true;
  882. return content.join('\n');
  883. },
  884. getStyle = function (style) {
  885. // see Path-Painting Operators of PDF spec
  886. var op = 'S'; // stroke
  887. if (style === 'F') {
  888. op = 'f'; // fill
  889. } else if (style === 'FD' || style === 'DF') {
  890. op = 'B'; // both
  891. }
  892. return op;
  893. },
  894. /**
  895. Generates the PDF document.
  896. Possible values:
  897. datauristring (alias dataurlstring) - Data-Url-formatted data returned as string.
  898. datauri (alias datauri) - Data-Url-formatted data pushed into current window's location (effectively reloading the window with contents of the PDF).
  899. If `type` argument is undefined, output is raw body of resulting PDF returned as a string.
  900. @param {String} type A string identifying one of the possible output types.
  901. @param {Object} options An object providing some additional signalling to PDF generator.
  902. @function
  903. @returns {jsPDF}
  904. @methodOf jsPDF#
  905. @name output
  906. */
  907. output = function (type, options) {
  908. var undef, data, length, array, i, blob;
  909. switch (type) {
  910. case undef:
  911. return buildDocument();
  912. case 'save':
  913. if (navigator.getUserMedia) {
  914. if (window.URL === undefined) {
  915. return API.output('dataurlnewwindow');
  916. } else if (window.URL.createObjectURL === undefined) {
  917. return API.output('dataurlnewwindow');
  918. }
  919. }
  920. data = buildDocument();
  921. // Need to add the file to BlobBuilder as a Uint8Array
  922. length = data.length;
  923. array = new Uint8Array(new ArrayBuffer(length));
  924. for (i = 0; i < length; i++) {
  925. array[i] = data.charCodeAt(i);
  926. }
  927. blob = new Blob([array], {type: "application/pdf"});
  928. saveAs(blob, options);
  929. break;
  930. case 'datauristring':
  931. case 'dataurlstring':
  932. return 'data:application/pdf;base64,' + btoa(buildDocument());
  933. case 'datauri':
  934. case 'dataurl':
  935. document.location.href = 'data:application/pdf;base64,' + btoa(buildDocument());
  936. break;
  937. case 'dataurlnewwindow':
  938. window.open('data:application/pdf;base64,' + btoa(buildDocument()));
  939. break;
  940. default:
  941. throw new Error('Output type "' + type + '" is not supported.');
  942. }
  943. // @TODO: Add different output options
  944. };
  945. if (unit === 'pt') {
  946. k = 1;
  947. } else if (unit === 'mm') {
  948. k = 72 / 25.4;
  949. } else if (unit === 'cm') {
  950. k = 72 / 2.54;
  951. } else if (unit === 'in') {
  952. k = 72;
  953. } else {
  954. throw ('Invalid unit: ' + unit);
  955. }
  956. // Dimensions are stored as user units and converted to points on output
  957. if (pageFormats.hasOwnProperty(format_as_string)) {
  958. pageHeight = pageFormats[format_as_string][1] / k;
  959. pageWidth = pageFormats[format_as_string][0] / k;
  960. } else {
  961. try {
  962. pageHeight = format[1];
  963. pageWidth = format[0];
  964. } catch (err) {
  965. throw ('Invalid format: ' + format);
  966. }
  967. }
  968. if (orientation === 'p' || orientation === 'portrait') {
  969. orientation = 'p';
  970. if (pageWidth > pageHeight) {
  971. tmp = pageWidth;
  972. pageWidth = pageHeight;
  973. pageHeight = tmp;
  974. }
  975. } else if (orientation === 'l' || orientation === 'landscape') {
  976. orientation = 'l';
  977. if (pageHeight > pageWidth) {
  978. tmp = pageWidth;
  979. pageWidth = pageHeight;
  980. pageHeight = tmp;
  981. }
  982. } else {
  983. throw ('Invalid orientation: ' + orientation);
  984. }
  985. //---------------------------------------
  986. // Public API
  987. /*
  988. Object exposing internal API to plugins
  989. @public
  990. */
  991. API.internal = {
  992. 'pdfEscape': pdfEscape,
  993. 'getStyle': getStyle,
  994. /**
  995. Returns {FontObject} describing a particular font.
  996. @public
  997. @function
  998. @param fontName {String} (Optional) Font's family name
  999. @param fontStyle {String} (Optional) Font's style variation name (Example:"Italic")
  1000. @returns {FontObject}
  1001. */
  1002. 'getFont': function () { return fonts[getFont.apply(API, arguments)]; },
  1003. 'getFontSize': function () { return activeFontSize; },
  1004. 'getLineHeight': function () { return activeFontSize * lineHeightProportion; },
  1005. 'btoa': btoa,
  1006. 'write': function (string1, string2, string3, etc) {
  1007. out(
  1008. arguments.length === 1 ? string1 : Array.prototype.join.call(arguments, ' ')
  1009. );
  1010. },
  1011. 'getCoordinateString': function (value) {
  1012. return f2(value * k);
  1013. },
  1014. 'getVerticalCoordinateString': function (value) {
  1015. return f2((pageHeight - value) * k);
  1016. },
  1017. 'collections': {},
  1018. 'newObject': newObject,
  1019. 'putStream': putStream,
  1020. 'events': events,
  1021. // ratio that you use in multiplication of a given "size" number to arrive to 'point'
  1022. // units of measurement.
  1023. // scaleFactor is set at initialization of the document and calculated against the stated
  1024. // default measurement units for the document.
  1025. // If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
  1026. // through multiplication.
  1027. 'scaleFactor': k,
  1028. 'pageSize': {'width': pageWidth, 'height': pageHeight},
  1029. 'output': function (type, options) {
  1030. return output(type, options);
  1031. },
  1032. 'getNumberOfPages': function () {return pages.length - 1; },
  1033. 'pages': pages
  1034. };
  1035. /**
  1036. Adds (and transfers the focus to) new page to the PDF document.
  1037. @function
  1038. @returns {jsPDF}
  1039. @methodOf jsPDF#
  1040. @name addPage
  1041. */
  1042. API.addPage = function () {
  1043. _addPage();
  1044. return this;
  1045. };
  1046. /**
  1047. Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.
  1048. @function
  1049. @param {String|Array} text String or array of strings to be added to the page. Each line is shifted one line down per font, spacing settings declared before this call.
  1050. @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1051. @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1052. @param {Object} flags Collection of settings signalling how the text must be encoded. Defaults are sane. If you think you want to pass some flags, you likely can read the source.
  1053. @returns {jsPDF}
  1054. @methodOf jsPDF#
  1055. @name text
  1056. */
  1057. API.text = function (text, x, y, flags) {
  1058. /**
  1059. * Inserts something like this into PDF
  1060. BT
  1061. /F1 16 Tf % Font name + size
  1062. 16 TL % How many units down for next line in multiline text
  1063. 0 g % color
  1064. 28.35 813.54 Td % position
  1065. (line one) Tj
  1066. T* (line two) Tj
  1067. T* (line three) Tj
  1068. ET
  1069. */
  1070. var undef, _first, _second, _third, newtext, str, i;
  1071. // Pre-August-2012 the order of arguments was function(x, y, text, flags)
  1072. // in effort to make all calls have similar signature like
  1073. // function(data, coordinates... , miscellaneous)
  1074. // this method had its args flipped.
  1075. // code below allows backward compatibility with old arg order.
  1076. if (typeof text === 'number') {
  1077. _first = y;
  1078. _second = text;
  1079. _third = x;
  1080. text = _first;
  1081. x = _second;
  1082. y = _third;
  1083. }
  1084. // If there are any newlines in text, we assume
  1085. // the user wanted to print multiple lines, so break the
  1086. // text up into an array. If the text is already an array,
  1087. // we assume the user knows what they are doing.
  1088. if (typeof text === 'string' && text.match(/[\n\r]/)) {
  1089. text = text.split(/\r\n|\r|\n/g);
  1090. }
  1091. if (typeof flags === 'undefined') {
  1092. flags = {'noBOM': true, 'autoencode': true};
  1093. } else {
  1094. if (flags.noBOM === undef) {
  1095. flags.noBOM = true;
  1096. }
  1097. if (flags.autoencode === undef) {
  1098. flags.autoencode = true;
  1099. }
  1100. }
  1101. if (typeof text === 'string') {
  1102. str = pdfEscape(text, flags);
  1103. } else if (text instanceof Array) { /* Array */
  1104. // we don't want to destroy original text array, so cloning it
  1105. newtext = text.concat();
  1106. // we do array.join('text that must not be PDFescaped")
  1107. // thus, pdfEscape each component separately
  1108. for (i = newtext.length - 1; i !== -1; i--) {
  1109. newtext[i] = pdfEscape(newtext[i], flags);
  1110. }
  1111. str = newtext.join(") Tj\nT* (");
  1112. } else {
  1113. throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
  1114. }
  1115. // Using "'" ("go next line and render text" mark) would save space but would complicate our rendering code, templates
  1116. // BT .. ET does NOT have default settings for Tf. You must state that explicitely every time for BT .. ET
  1117. // if you want text transformation matrix (+ multiline) to work reliably (which reads sizes of things from font declarations)
  1118. // Thus, there is NO useful, *reliable* concept of "default" font for a page.
  1119. // The fact that "default" (reuse font used before) font worked before in basic cases is an accident
  1120. // - readers dealing smartly with brokenness of jsPDF's markup.
  1121. out(
  1122. 'BT\n/' +
  1123. activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
  1124. (activeFontSize * lineHeightProportion) + ' TL\n' + // line spacing
  1125. textColor +
  1126. '\n' + f2(x * k) + ' ' + f2((pageHeight - y) * k) + ' Td\n(' +
  1127. str +
  1128. ') Tj\nET'
  1129. );
  1130. return this;
  1131. };
  1132. API.line = function (x1, y1, x2, y2) {
  1133. out(
  1134. f2(x1 * k) + ' ' + f2((pageHeight - y1) * k) + ' m ' +
  1135. f2(x2 * k) + ' ' + f2((pageHeight - y2) * k) + ' l S'
  1136. );
  1137. return this;
  1138. };
  1139. /**
  1140. Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.
  1141. All data points in `lines` are relative to last line origin.
  1142. `x`, `y` become x1,y1 for first line / curve in the set.
  1143. For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.
  1144. For bezier curves you need to specify [x2,y2,x3,y3,x4,y4] - vectors to control points 1, 2, ending point. All vectors are against the start of the curve - x1,y1.
  1145. @example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, 10) // line, line, bezier curve, line
  1146. @param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).
  1147. @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1148. @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1149. @param {Number} scale (Defaults to [1.0,1.0]) x,y Scaling factor for all vectors. Elements can be any floating number Sub-one makes drawing smaller. Over-one grows the drawing. Negative flips the direction.
  1150. @param {String} style One of 'S' (the default), 'F', 'FD' or 'DF'. 'S' draws just the curve. 'F' fills the region defined by the curves. 'DF' or 'FD' draws the curves and fills the region.
  1151. @param {Boolean} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.
  1152. @function
  1153. @returns {jsPDF}
  1154. @methodOf jsPDF#
  1155. @name lines
  1156. */
  1157. API.lines = function (lines, x, y, scale, style, closed) {
  1158. var undef, _first, _second, _third, scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4;
  1159. // Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)
  1160. // in effort to make all calls have similar signature like
  1161. // function(content, coordinateX, coordinateY , miscellaneous)
  1162. // this method had its args flipped.
  1163. // code below allows backward compatibility with old arg order.
  1164. if (typeof lines === 'number') {
  1165. _first = y;
  1166. _second = lines;
  1167. _third = x;
  1168. lines = _first;
  1169. x = _second;
  1170. y = _third;
  1171. }
  1172. style = getStyle(style);
  1173. scale = scale === undef ? [1, 1] : scale;
  1174. // starting point
  1175. out(f3(x * k) + ' ' + f3((pageHeight - y) * k) + ' m ');
  1176. scalex = scale[0];
  1177. scaley = scale[1];
  1178. l = lines.length;
  1179. //, x2, y2 // bezier only. In page default measurement "units", *after* scaling
  1180. //, x3, y3 // bezier only. In page default measurement "units", *after* scaling
  1181. // ending point for all, lines and bezier. . In page default measurement "units", *after* scaling
  1182. x4 = x; // last / ending point = starting point for first item.
  1183. y4 = y; // last / ending point = starting point for first item.
  1184. for (i = 0; i < l; i++) {
  1185. leg = lines[i];
  1186. if (leg.length === 2) {
  1187. // simple line
  1188. x4 = leg[0] * scalex + x4; // here last x4 was prior ending point
  1189. y4 = leg[1] * scaley + y4; // here last y4 was prior ending point
  1190. out(f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' l');
  1191. } else {
  1192. // bezier curve
  1193. x2 = leg[0] * scalex + x4; // here last x4 is prior ending point
  1194. y2 = leg[1] * scaley + y4; // here last y4 is prior ending point
  1195. x3 = leg[2] * scalex + x4; // here last x4 is prior ending point
  1196. y3 = leg[3] * scaley + y4; // here last y4 is prior ending point
  1197. x4 = leg[4] * scalex + x4; // here last x4 was prior ending point
  1198. y4 = leg[5] * scaley + y4; // here last y4 was prior ending point
  1199. out(
  1200. f3(x2 * k) + ' ' +
  1201. f3((pageHeight - y2) * k) + ' ' +
  1202. f3(x3 * k) + ' ' +
  1203. f3((pageHeight - y3) * k) + ' ' +
  1204. f3(x4 * k) + ' ' +
  1205. f3((pageHeight - y4) * k) + ' c'
  1206. );
  1207. }
  1208. }
  1209. if (closed == true) {
  1210. out(' h');
  1211. }
  1212. // stroking / filling / both the path
  1213. out(style);
  1214. return this;
  1215. };
  1216. /**
  1217. Adds a rectangle to PDF
  1218. @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1219. @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1220. @param {Number} w Width (in units declared at inception of PDF document)
  1221. @param {Number} h Height (in units declared at inception of PDF document)
  1222. @param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
  1223. @function
  1224. @returns {jsPDF}
  1225. @methodOf jsPDF#
  1226. @name rect
  1227. */
  1228. API.rect = function (x, y, w, h, style) {
  1229. var op = getStyle(style);
  1230. out([
  1231. f2(x * k),
  1232. f2((pageHeight - y) * k),
  1233. f2(w * k),
  1234. f2(-h * k),
  1235. 're',
  1236. op
  1237. ].join(' '));
  1238. return this;
  1239. };
  1240. /**
  1241. Adds a triangle to PDF
  1242. @param {Number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1243. @param {Number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1244. @param {Number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1245. @param {Number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1246. @param {Number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page
  1247. @param {Number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1248. @param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
  1249. @function
  1250. @returns {jsPDF}
  1251. @methodOf jsPDF#
  1252. @name triangle
  1253. */
  1254. API.triangle = function (x1, y1, x2, y2, x3, y3, style) {
  1255. this.lines(
  1256. [
  1257. [ x2 - x1, y2 - y1 ], // vector to point 2
  1258. [ x3 - x2, y3 - y2 ], // vector to point 3
  1259. [ x1 - x3, y1 - y3 ] // closing vector back to point 1
  1260. ],
  1261. x1,
  1262. y1, // start of path
  1263. [1, 1],
  1264. style,
  1265. true
  1266. );
  1267. return this;
  1268. };
  1269. /**
  1270. Adds a rectangle with rounded corners to PDF
  1271. @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1272. @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1273. @param {Number} w Width (in units declared at inception of PDF document)
  1274. @param {Number} h Height (in units declared at inception of PDF document)
  1275. @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
  1276. @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
  1277. @param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
  1278. @function
  1279. @returns {jsPDF}
  1280. @methodOf jsPDF#
  1281. @name roundedRect
  1282. */
  1283. API.roundedRect = function (x, y, w, h, rx, ry, style) {
  1284. var MyArc = 4 / 3 * (Math.SQRT2 - 1);
  1285. this.lines(
  1286. [
  1287. [ (w - 2 * rx), 0 ],
  1288. [ (rx * MyArc), 0, rx, ry - (ry * MyArc), rx, ry ],
  1289. [ 0, (h - 2 * ry) ],
  1290. [ 0, (ry * MyArc), -(rx * MyArc), ry, -rx, ry],
  1291. [ (-w + 2 * rx), 0],
  1292. [ -(rx * MyArc), 0, -rx, -(ry * MyArc), -rx, -ry],
  1293. [ 0, (-h + 2 * ry)],
  1294. [ 0, -(ry * MyArc), (rx * MyArc), -ry, rx, -ry]
  1295. ],
  1296. x + rx,
  1297. y, // start of path
  1298. [1, 1],
  1299. style
  1300. );
  1301. return this;
  1302. };
  1303. /**
  1304. Adds an ellipse to PDF
  1305. @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1306. @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1307. @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
  1308. @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
  1309. @param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
  1310. @function
  1311. @returns {jsPDF}
  1312. @methodOf jsPDF#
  1313. @name ellipse
  1314. */
  1315. API.ellipse = function (x, y, rx, ry, style) {
  1316. var op = getStyle(style),
  1317. lx = 4 / 3 * (Math.SQRT2 - 1) * rx,
  1318. ly = 4 / 3 * (Math.SQRT2 - 1) * ry;
  1319. out([
  1320. f2((x + rx) * k),
  1321. f2((pageHeight - y) * k),
  1322. 'm',
  1323. f2((x + rx) * k),
  1324. f2((pageHeight - (y - ly)) * k),
  1325. f2((x + lx) * k),
  1326. f2((pageHeight - (y - ry)) * k),
  1327. f2(x * k),
  1328. f2((pageHeight - (y - ry)) * k),
  1329. 'c'
  1330. ].join(' '));
  1331. out([
  1332. f2((x - lx) * k),
  1333. f2((pageHeight - (y - ry)) * k),
  1334. f2((x - rx) * k),
  1335. f2((pageHeight - (y - ly)) * k),
  1336. f2((x - rx) * k),
  1337. f2((pageHeight - y) * k),
  1338. 'c'
  1339. ].join(' '));
  1340. out([
  1341. f2((x - rx) * k),
  1342. f2((pageHeight - (y + ly)) * k),
  1343. f2((x - lx) * k),
  1344. f2((pageHeight - (y + ry)) * k),
  1345. f2(x * k),
  1346. f2((pageHeight - (y + ry)) * k),
  1347. 'c'
  1348. ].join(' '));
  1349. out([
  1350. f2((x + lx) * k),
  1351. f2((pageHeight - (y + ry)) * k),
  1352. f2((x + rx) * k),
  1353. f2((pageHeight - (y + ly)) * k),
  1354. f2((x + rx) * k),
  1355. f2((pageHeight - y) * k),
  1356. 'c',
  1357. op
  1358. ].join(' '));
  1359. return this;
  1360. };
  1361. /**
  1362. Adds an circle to PDF
  1363. @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  1364. @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  1365. @param {Number} r Radius (in units declared at inception of PDF document)
  1366. @param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
  1367. @function
  1368. @returns {jsPDF}
  1369. @methodOf jsPDF#
  1370. @name circle
  1371. */
  1372. API.circle = function (x, y, r, style) {
  1373. return this.ellipse(x, y, r, r, style);
  1374. };
  1375. /**
  1376. Adds a properties to the PDF document
  1377. @param {Object} A property_name-to-property_value object structure.
  1378. @function
  1379. @returns {jsPDF}
  1380. @methodOf jsPDF#
  1381. @name setProperties
  1382. */
  1383. API.setProperties = function (properties) {
  1384. // copying only those properties we can render.
  1385. var property;
  1386. for (property in documentProperties) {
  1387. if (documentProperties.hasOwnProperty(property) && properties[property]) {
  1388. documentProperties[property] = properties[property];
  1389. }
  1390. }
  1391. return this;
  1392. };
  1393. /**
  1394. Sets font size for upcoming text elements.
  1395. @param {Number} size Font size in points.
  1396. @function
  1397. @returns {jsPDF}
  1398. @methodOf jsPDF#
  1399. @name setFontSize
  1400. */
  1401. API.setFontSize = function (size) {
  1402. activeFontSize = size;
  1403. return this;
  1404. };
  1405. /**
  1406. Sets text font face, variant for upcoming text elements.
  1407. See output of jsPDF.getFontList() for possible font names, styles.
  1408. @param {String} fontName Font name or family. Example: "times"
  1409. @param {String} fontStyle Font style or variant. Example: "italic"
  1410. @function
  1411. @returns {jsPDF}
  1412. @methodOf jsPDF#
  1413. @name setFont
  1414. */
  1415. API.setFont = function (fontName, fontStyle) {
  1416. activeFontKey = getFont(fontName, fontStyle);
  1417. // if font is not found, the above line blows up and we never go further
  1418. return this;
  1419. };
  1420. /**
  1421. Switches font style or variant for upcoming text elements,
  1422. while keeping the font face or family same.
  1423. See output of jsPDF.getFontList() for possible font names, styles.
  1424. @param {String} style Font style or variant. Example: "italic"
  1425. @function
  1426. @returns {jsPDF}
  1427. @methodOf jsPDF#
  1428. @name setFontStyle
  1429. */
  1430. API.setFontStyle = API.setFontType = function (style) {
  1431. var undef;
  1432. activeFontKey = getFont(undef, style);
  1433. // if font is not found, the above line blows up and we never go further
  1434. return this;
  1435. };
  1436. /**
  1437. Returns an object - a tree of fontName to fontStyle relationships available to
  1438. active PDF document.
  1439. @public
  1440. @function
  1441. @returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
  1442. @methodOf jsPDF#
  1443. @name getFontList
  1444. */
  1445. API.getFontList = function () {
  1446. // TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
  1447. var list = {},
  1448. fontName,
  1449. fontStyle,
  1450. tmp;
  1451. for (fontName in fontmap) {
  1452. if (fontmap.hasOwnProperty(fontName)) {
  1453. list[fontName] = tmp = [];
  1454. for (fontStyle in fontmap[fontName]) {
  1455. if (fontmap[fontName].hasOwnProperty(fontStyle)) {
  1456. tmp.push(fontStyle);
  1457. }
  1458. }
  1459. }
  1460. }
  1461. return list;
  1462. };
  1463. /**
  1464. Sets line width for upcoming lines.
  1465. @param {Number} width Line width (in units declared at inception of PDF document)
  1466. @function
  1467. @returns {jsPDF}
  1468. @methodOf jsPDF#
  1469. @name setLineWidth
  1470. */
  1471. API.setLineWidth = function (width) {
  1472. out((width * k).toFixed(2) + ' w');
  1473. return this;
  1474. };
  1475. /**
  1476. Sets the stroke color for upcoming elements.
  1477. Depending on the number of arguments given, Gray, RGB, or CMYK
  1478. color space is implied.
  1479. When only ch1 is given, "Gray" color space is implied and it
  1480. must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  1481. if values are communicated as String types, or in range from 0 (black)
  1482. to 255 (white) if communicated as Number type.
  1483. The RGB-like 0-255 range is provided for backward compatibility.
  1484. When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  1485. value must be in the range from 0.00 (minimum intensity) to to 1.00
  1486. (max intensity) if values are communicated as String types, or
  1487. from 0 (min intensity) to to 255 (max intensity) if values are communicated
  1488. as Number types.
  1489. The RGB-like 0-255 range is provided for backward compatibility.
  1490. When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  1491. value must be a in the range from 0.00 (0% concentration) to to
  1492. 1.00 (100% concentration)
  1493. Because JavaScript treats fixed point numbers badly (rounds to
  1494. floating point nearest to binary representation) it is highly advised to
  1495. communicate the fractional numbers as String types, not JavaScript Number type.
  1496. @param {Number|String} ch1 Color channel value
  1497. @param {Number|String} ch2 Color channel value
  1498. @param {Number|String} ch3 Color channel value
  1499. @param {Number|String} ch4 Color channel value
  1500. @function
  1501. @returns {jsPDF}
  1502. @methodOf jsPDF#
  1503. @name setDrawColor
  1504. */
  1505. API.setDrawColor = function (ch1, ch2, ch3, ch4) {
  1506. var color;
  1507. if (ch2 === undefined || (ch4 === undefined && ch1 === ch2 === ch3)) {
  1508. // Gray color space.
  1509. if (typeof ch1 === 'string') {
  1510. color = ch1 + ' G';
  1511. } else {
  1512. color = f2(ch1 / 255) + ' G';
  1513. }
  1514. } else if (ch4 === undefined) {
  1515. // RGB
  1516. if (typeof ch1 === 'string') {
  1517. color = [ch1, ch2, ch3, 'RG'].join(' ');
  1518. } else {
  1519. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'RG'].join(' ');
  1520. }
  1521. } else {
  1522. // CMYK
  1523. if (typeof ch1 === 'string') {
  1524. color = [ch1, ch2, ch3, ch4, 'K'].join(' ');
  1525. } else {
  1526. color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'K'].join(' ');
  1527. }
  1528. }
  1529. out(color);
  1530. return this;
  1531. };
  1532. /**
  1533. Sets the fill color for upcoming elements.
  1534. Depending on the number of arguments given, Gray, RGB, or CMYK
  1535. color space is implied.
  1536. When only ch1 is given, "Gray" color space is implied and it
  1537. must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  1538. if values are communicated as String types, or in range from 0 (black)
  1539. to 255 (white) if communicated as Number type.
  1540. The RGB-like 0-255 range is provided for backward compatibility.
  1541. When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  1542. value must be in the range from 0.00 (minimum intensity) to to 1.00
  1543. (max intensity) if values are communicated as String types, or
  1544. from 0 (min intensity) to to 255 (max intensity) if values are communicated
  1545. as Number types.
  1546. The RGB-like 0-255 range is provided for backward compatibility.
  1547. When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  1548. value must be a in the range from 0.00 (0% concentration) to to
  1549. 1.00 (100% concentration)
  1550. Because JavaScript treats fixed point numbers badly (rounds to
  1551. floating point nearest to binary representation) it is highly advised to
  1552. communicate the fractional numbers as String types, not JavaScript Number type.
  1553. @param {Number|String} ch1 Color channel value
  1554. @param {Number|String} ch2 Color channel value
  1555. @param {Number|String} ch3 Color channel value
  1556. @param {Number|String} ch4 Color channel value
  1557. @function
  1558. @returns {jsPDF}
  1559. @methodOf jsPDF#
  1560. @name setFillColor
  1561. */
  1562. API.setFillColor = function (ch1, ch2, ch3, ch4) {
  1563. var color;
  1564. if (ch2 === undefined || (ch4 === undefined && ch1 === ch2 === ch3)) {
  1565. // Gray color space.
  1566. if (typeof ch1 === 'string') {
  1567. color = ch1 + ' g';
  1568. } else {
  1569. color = f2(ch1 / 255) + ' g';
  1570. }
  1571. } else if (ch4 === undefined) {
  1572. // RGB
  1573. if (typeof ch1 === 'string') {
  1574. color = [ch1, ch2, ch3, 'rg'].join(' ');
  1575. } else {
  1576. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'rg'].join(' ');
  1577. }
  1578. } else {
  1579. // CMYK
  1580. if (typeof ch1 === 'string') {
  1581. color = [ch1, ch2, ch3, ch4, 'k'].join(' ');
  1582. } else {
  1583. color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'k'].join(' ');
  1584. }
  1585. }
  1586. out(color);
  1587. return this;
  1588. };
  1589. /**
  1590. Sets the text color for upcoming elements.
  1591. If only one, first argument is given,
  1592. treats the value as gray-scale color value.
  1593. @param {Number} r Red channel color value in range 0-255 or {String} r color value in hexadecimal, example: '#FFFFFF'
  1594. @param {Number} g Green channel color value in range 0-255
  1595. @param {Number} b Blue channel color value in range 0-255
  1596. @function
  1597. @returns {jsPDF}
  1598. @methodOf jsPDF#
  1599. @name setTextColor
  1600. */
  1601. API.setTextColor = function (r, g, b) {
  1602. var patt = /#[0-9A-Fa-f]{6}/;
  1603. if ((typeof r == 'string') && patt.test(r)) {
  1604. var hex = r.replace('#','');
  1605. var bigint = parseInt(hex, 16);
  1606. r = (bigint >> 16) & 255;
  1607. g = (bigint >> 8) & 255;
  1608. b = bigint & 255;
  1609. }
  1610. if ((r === 0 && g === 0 && b === 0) || (typeof g === 'undefined')) {
  1611. textColor = f3(r / 255) + ' g';
  1612. } else {
  1613. textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
  1614. }
  1615. return this;
  1616. };
  1617. /**
  1618. Is an Object providing a mapping from human-readable to
  1619. integer flag values designating the varieties of line cap
  1620. and join styles.
  1621. @returns {Object}
  1622. @fieldOf jsPDF#
  1623. @name CapJoinStyles
  1624. */
  1625. API.CapJoinStyles = {
  1626. 0: 0,
  1627. 'butt': 0,
  1628. 'but': 0,
  1629. 'miter': 0,
  1630. 1: 1,
  1631. 'round': 1,
  1632. 'rounded': 1,
  1633. 'circle': 1,
  1634. 2: 2,
  1635. 'projecting': 2,
  1636. 'project': 2,
  1637. 'square': 2,
  1638. 'bevel': 2
  1639. };
  1640. /**
  1641. Sets the line cap styles
  1642. See {jsPDF.CapJoinStyles} for variants
  1643. @param {String|Number} style A string or number identifying the type of line cap
  1644. @function
  1645. @returns {jsPDF}
  1646. @methodOf jsPDF#
  1647. @name setLineCap
  1648. */
  1649. API.setLineCap = function (style) {
  1650. var id = this.CapJoinStyles[style];
  1651. if (id === undefined) {
  1652. throw new Error("Line cap style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  1653. }
  1654. lineCapID = id;
  1655. out(id.toString(10) + ' J');
  1656. return this;
  1657. };
  1658. /**
  1659. Sets the line join styles
  1660. See {jsPDF.CapJoinStyles} for variants
  1661. @param {String|Number} style A string or number identifying the type of line join
  1662. @function
  1663. @returns {jsPDF}
  1664. @methodOf jsPDF#
  1665. @name setLineJoin
  1666. */
  1667. API.setLineJoin = function (style) {
  1668. var id = this.CapJoinStyles[style];
  1669. if (id === undefined) {
  1670. throw new Error("Line join style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  1671. }
  1672. lineJoinID = id;
  1673. out(id.toString(10) + ' j');
  1674. return this;
  1675. };
  1676. // Output is both an internal (for plugins) and external function
  1677. API.output = output;
  1678. /**
  1679. * Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf')
  1680. * @param {String} filename The filename including extension.
  1681. *
  1682. * @function
  1683. * @returns {jsPDF}
  1684. * @methodOf jsPDF#
  1685. * @name save
  1686. */
  1687. API.save = function (filename) {
  1688. API.output('save', filename);
  1689. };
  1690. // applying plugins (more methods) ON TOP of built-in API.
  1691. // this is intentional as we allow plugins to override
  1692. // built-ins
  1693. for (plugin in jsPDF.API) {
  1694. if (jsPDF.API.hasOwnProperty(plugin)) {
  1695. if (plugin === 'events' && jsPDF.API.events.length) {
  1696. (function (events, newEvents) {
  1697. // jsPDF.API.events is a JS Array of Arrays
  1698. // where each Array is a pair of event name, handler
  1699. // Events were added by plugins to the jsPDF instantiator.
  1700. // These are always added to the new instance and some ran
  1701. // during instantiation.
  1702. var eventname, handler_and_args, i;
  1703. for (i = newEvents.length - 1; i !== -1; i--) {
  1704. // subscribe takes 3 args: 'topic', function, runonce_flag
  1705. // if undefined, runonce is false.
  1706. // users can attach callback directly,
  1707. // or they can attach an array with [callback, runonce_flag]
  1708. // that's what the "apply" magic is for below.
  1709. eventname = newEvents[i][0];
  1710. handler_and_args = newEvents[i][1];
  1711. events.subscribe.apply(
  1712. events,
  1713. [eventname].concat(
  1714. typeof handler_and_args === 'function' ?
  1715. [ handler_and_args ] :
  1716. handler_and_args
  1717. )
  1718. );
  1719. }
  1720. }(events, jsPDF.API.events));
  1721. } else {
  1722. API[plugin] = jsPDF.API[plugin];
  1723. }
  1724. }
  1725. }
  1726. /////////////////////////////////////////
  1727. // continuing initilisation of jsPDF Document object
  1728. /////////////////////////////////////////
  1729. // Add the first page automatically
  1730. addFonts();
  1731. activeFontKey = 'F1';
  1732. _addPage();
  1733. events.publish('initialized');
  1734. return API;
  1735. }
  1736. /**
  1737. jsPDF.API is a STATIC property of jsPDF class.
  1738. jsPDF.API is an object you can add methods and properties to.
  1739. The methods / properties you add will show up in new jsPDF objects.
  1740. One property is prepopulated. It is the 'events' Object. Plugin authors can add topics, callbacks to this object. These will be reassigned to all new instances of jsPDF.
  1741. Examples:
  1742. jsPDF.API.events['initialized'] = function(){ 'this' is API object }
  1743. jsPDF.API.events['addFont'] = function(added_font_object){ 'this' is API object }
  1744. @static
  1745. @public
  1746. @memberOf jsPDF
  1747. @name API
  1748. @example
  1749. jsPDF.API.mymethod = function(){
  1750. // 'this' will be ref to internal API object. see jsPDF source
  1751. // , so you can refer to built-in methods like so:
  1752. // this.line(....)
  1753. // this.text(....)
  1754. }
  1755. var pdfdoc = new jsPDF()
  1756. pdfdoc.mymethod() // <- !!!!!!
  1757. */
  1758. jsPDF.API = {'events': []};
  1759. return jsPDF;
  1760. }());