forked from parallax/jsPDF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jspdf.js
2746 lines (2566 loc) · 99 KB
/
jspdf.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @preserve
* jsPDF - PDF Document creation from JavaScript
* Version ${versionID} Built on ${builtOn}
* CommitID ${commitID}
*
* Copyright (c) 2010-2016 James Hall <james@parall.ax>, https://github.com/MrRio/jsPDF
* 2010 Aaron Spike, https://github.com/acspike
* 2012 Willow Systems Corporation, willow-systems.com
* 2012 Pablo Hess, https://github.com/pablohess
* 2012 Florian Jenett, https://github.com/fjenett
* 2013 Warren Weckesser, https://github.com/warrenweckesser
* 2013 Youssef Beddad, https://github.com/lifof
* 2013 Lee Driscoll, https://github.com/lsdriscoll
* 2013 Stefan Slonevskiy, https://github.com/stefslon
* 2013 Jeremy Morel, https://github.com/jmorel
* 2013 Christoph Hartmann, https://github.com/chris-rock
* 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
* 2014 James Makes, https://github.com/dollaruw
* 2014 Diego Casorran, https://github.com/diegocr
* 2014 Steven Spungin, https://github.com/Flamenco
* 2014 Kenneth Glassey, https://github.com/Gavvers
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Contributor(s):
* siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
* kim3er, mfo, alnorth, Flamenco
*/
/**
* Creates new jsPDF document object instance.
* @name jsPDF
* @class
* @param orientation {String/Object} Orientation of the first page. Possible values are "portrait" or "landscape" (or shortcuts "p" (Default), "l") <br />
* Can also be an options object.
* @param unit {String} Measurement unit to be used when coordinates are specified.<br />
* Possible values are "pt" (points), "mm" (Default), "cm", "in" or "px".
* @param format {String/Array} The format of the first page. Can be <ul><li>a0 - a10</li><li>b0 - b10</li><li>c0 - c10</li><li>c0 - c10</li><li>dl</li><li>letter</li><li>government-letter</li><li>legal</li><li>junior-legal</li><li>ledger</li><li>tabloid</li><li>credit-card</li></ul><br />
* Default is "a4". If you want to use your own format just pass instead of one of the above predefined formats the size as an number-array , e.g. [595.28, 841.89]
* @returns {jsPDF}
* @description
* If the first parameter (orientation) is an object, it will be interpreted as an object of named parameters
* ```
* {
* orientation: 'p',
* unit: 'mm',
* format: 'a4',
* hotfixes: [] // an array of hotfix strings to enable
* }
* ```
*/
var jsPDF = (function (global) {
'use strict';
var pdfVersion = '1.3',
pageFormats = { // Size in pt of various paper formats
'a0': [2383.94, 3370.39],
'a1': [1683.78, 2383.94],
'a2': [1190.55, 1683.78],
'a3': [841.89, 1190.55],
'a4': [595.28, 841.89],
'a5': [419.53, 595.28],
'a6': [297.64, 419.53],
'a7': [209.76, 297.64],
'a8': [147.40, 209.76],
'a9': [104.88, 147.40],
'a10': [73.70, 104.88],
'b0': [2834.65, 4008.19],
'b1': [2004.09, 2834.65],
'b2': [1417.32, 2004.09],
'b3': [1000.63, 1417.32],
'b4': [708.66, 1000.63],
'b5': [498.90, 708.66],
'b6': [354.33, 498.90],
'b7': [249.45, 354.33],
'b8': [175.75, 249.45],
'b9': [124.72, 175.75],
'b10': [87.87, 124.72],
'c0': [2599.37, 3676.54],
'c1': [1836.85, 2599.37],
'c2': [1298.27, 1836.85],
'c3': [918.43, 1298.27],
'c4': [649.13, 918.43],
'c5': [459.21, 649.13],
'c6': [323.15, 459.21],
'c7': [229.61, 323.15],
'c8': [161.57, 229.61],
'c9': [113.39, 161.57],
'c10': [79.37, 113.39],
'dl': [311.81, 623.62],
'letter': [612, 792],
'government-letter': [576, 756],
'legal': [612, 1008],
'junior-legal': [576, 360],
'ledger': [1224, 792],
'tabloid': [792, 1224],
'credit-card': [153, 243]
};
/**
* jsPDF's Internal PubSub Implementation.
* See mrrio.github.io/jsPDF/doc/symbols/PubSub.html
* Backward compatible rewritten on 2014 by
* Diego Casorran, https://github.com/diegocr
*
* @class
* @name PubSub
* @ignore This should not be in the public docs.
*/
function PubSub(context) {
var topics = {};
this.subscribe = function (topic, callback, once) {
if (typeof callback !== 'function') {
return false;
}
if (!topics.hasOwnProperty(topic)) {
topics[topic] = {};
}
var id = Math.random().toString(35);
topics[topic][id] = [callback, !!once];
return id;
};
this.unsubscribe = function (token) {
for (var topic in topics) {
if (topics[topic][token]) {
delete topics[topic][token];
return true;
}
}
return false;
};
this.publish = function (topic) {
if (topics.hasOwnProperty(topic)) {
var args = Array.prototype.slice.call(arguments, 1),
idr = [];
for (var id in topics[topic]) {
var sub = topics[topic][id];
try {
sub[0].apply(context, args);
} catch (ex) {
if (global.console) {
console.error('jsPDF PubSub Error', ex.message, ex);
}
}
if (sub[1]) idr.push(id);
}
if (idr.length) idr.forEach(this.unsubscribe);
}
};
}
/**
* @constructor
* @private
*/
function jsPDF(orientation, unit, format, compressPdf) {
var options = {};
if (typeof orientation === 'object') {
options = orientation;
orientation = options.orientation;
unit = options.unit || unit;
format = options.format || format;
compressPdf = options.compress || options.compressPdf || compressPdf;
}
// Default options
unit = unit || 'mm';
format = format || 'a4';
orientation = ('' + (orientation || 'P')).toLowerCase();
var format_as_string = ('' + format).toLowerCase(),
compress = !!compressPdf && typeof Uint8Array === 'function',
textColor = options.textColor || '0 g',
drawColor = options.drawColor || '0 G',
activeFontSize = options.fontSize || 16,
activeCharSpace = options.charSpace || 0,
R2L = options.R2L || false,
lineHeightProportion = options.lineHeight || 1.15,
lineWidth = options.lineWidth || 0.200025, // 2mm
fileId = '00000000000000000000000000000000',
objectNumber = 2, // 'n' Current object number
outToPages = !1, // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
offsets = [], // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
fonts = {}, // collection of font objects, where key is fontKey - a dynamically created label for a given font.
fontmap = {}, // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
activeFontKey, // will be string representing the KEY of the font as combination of fontName + fontStyle
k, // Scale factor
tmp,
page = 0,
currentPage,
pages = [],
pagesContext = [], // same index as pages and pagedim
pagedim = [],
content = [],
additionalObjects = [],
lineCapID = 0,
lineJoinID = 0,
content_length = 0,
pageWidth,
pageHeight,
pageMode,
zoomMode,
layoutMode,
creationDate,
documentProperties = {
'title': '',
'subject': '',
'author': '',
'keywords': '',
'creator': ''
},
API = {},
events = new PubSub(API),
hotfixes = options.hotfixes || [],
/////////////////////
// Private functions
/////////////////////
generateColorString = function (options) {
var color;
var ch1 = options.ch1;
var ch2 = options.ch2;
var ch3 = options.ch3;
var ch4 = options.ch4;
var precision = options.precision;
var letterArray = (options.pdfColorType === "draw") ? ['G', 'RG', 'K'] : ['g', 'rg', 'k'];
if ((typeof ch1 === "string") && ch1.charAt(0) !== '#') {
var rgbColor = new RGBColor(ch1);
if (rgbColor.ok) {
ch1 = rgbColor.toHex();
}
}
//convert short rgb to long form
if ((typeof ch1 === "string") && (/^#[0-9A-Fa-f]{3}$/).test(ch1)) {
ch1 = '#' + ch1[1] + ch1[1] + ch1[2] + ch1[2] + ch1[3] + ch1[3];
}
if ((typeof ch1 === "string") && (/^#[0-9A-Fa-f]{6}$/).test(ch1)) {
var hex = parseInt(ch1.substr(1), 16);
ch1 = (hex >> 16) & 255;
ch2 = (hex >> 8) & 255;
ch3 = (hex & 255);
}
if ((typeof ch2 === "undefined") || (typeof ch4 === "undefined") && ((ch1 === ch2) && (ch2 === ch3))) {
// Gray color space.
if (typeof ch1 === "string") {
color = ch1 + " " + letterArray[0];
} else {
switch (options.precision) {
case 2:
color = f2(ch1 / 255) + " " + letterArray[0];
break;
case 3:
default:
color = f3(ch1 / 255) + " " + letterArray[0];
}
}
} else if (typeof ch4 === "undefined" || typeof ch4 === "object") {
// assume RGB
if (typeof ch1 === "string") {
color = [ch1, ch2, ch3, letterArray[1]].join(" ");
} else {
switch (options.precision) {
case 2:
color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), letterArray[1]].join(" ");
break;
default:
case 3:
color = [f3(ch1 / 255), f3(ch2 / 255), f3(ch3 / 255), letterArray[1]].join(" ");
}
}
// assume RGBA
if (ch4 && ch4.a === 0) {
//TODO Implement transparency.
//WORKAROUND use white for now
color = ['255', '255', '255', letterArray[1]].join(" ");
}
} else {
// assume CMYK
if (typeof ch1 === 'string') {
color = [ch1, ch2, ch3, ch4, letterArray[2]].join(" ");
} else {
switch (options.precision) {
case 2:
color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), letterArray[2]].join(" ");
break;
case 3:
default:
color = [f3(ch1), f3(ch2), f3(ch3), f3(ch4), letterArray[2]].join(" ");
}
}
}
return color;
},
convertDateToPDFDate = function (parmDate) {
var padd2 = function(number) {
return ('0' + parseInt(number)).slice(-2);
};
var result = '';
var tzoffset = parmDate.getTimezoneOffset(),
tzsign = tzoffset < 0 ? '+' : '-',
tzhour = Math.floor(Math.abs(tzoffset / 60)),
tzmin = Math.abs(tzoffset % 60),
timeZoneString = [tzsign, padd2(tzhour), "'", padd2(tzmin), "'"].join('');
result = ['D:',
parmDate.getFullYear(),
padd2(parmDate.getMonth() + 1),
padd2(parmDate.getDate()),
padd2(parmDate.getHours()),
padd2(parmDate.getMinutes()),
padd2(parmDate.getSeconds()),
timeZoneString
].join('');
return result;
},
convertPDFDateToDate = function (parmPDFDate) {
var year = parseInt(parmPDFDate.substr(2,4), 10);
var month = parseInt(parmPDFDate.substr(6,2), 10) - 1;
var date = parseInt(parmPDFDate.substr(8,2), 10);
var hour = parseInt(parmPDFDate.substr(10,2), 10);
var minutes = parseInt(parmPDFDate.substr(12,2), 10);
var seconds = parseInt(parmPDFDate.substr(14,2), 10);
var timeZoneHour = parseInt(parmPDFDate.substr(16,2), 10);
var timeZoneMinutes = parseInt(parmPDFDate.substr(20,2), 10);
var resultingDate = new Date(year, month, date, hour, minutes, seconds, 0);
return resultingDate;
},
setCreationDate = function (date) {
var tmpCreationDateString;
var regexPDFCreationDate = (/^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|\-0[0-9]|\-1[0-1])\'(0[0-9]|[1-5][0-9])\'?$/);
if (typeof (date) === undefined) {
date = new Date();
}
if (typeof date === "object" && Object.prototype.toString.call(date) === "[object Date]") {
tmpCreationDateString = convertDateToPDFDate(date)
} else if (regexPDFCreationDate.test(date)) {
tmpCreationDateString = date;
} else {
tmpCreationDateString = convertDateToPDFDate(new Date());
}
creationDate = tmpCreationDateString;
return creationDate;
},
getCreationDate = function(type) {
var result = creationDate;
if (type === "jsDate") {
result = convertPDFDateToDate(creationDate);
}
return result;
},
setFileId = function (value) {
value = value || ("12345678901234567890123456789012").split('').map(function () {return "ABCDEF0123456789".charAt(Math.floor(Math.random() * 16)); }).join('');
fileId = value;
return fileId;
},
getFileId = function() {
return fileId;
},
f2 = function(number) {
return number.toFixed(2); // Ie, %.2f
},
f3 = function (number) {
return number.toFixed(3); // Ie, %.3f
},
padd2 = function (number) {
return ('0' + parseInt(number)).slice(-2);
},
out = function(string) {
string = (typeof string === "string") ? string : string.toString();
if (outToPages) {
/* set by beginPage */
pages[currentPage].push(string);
} else {
// +1 for '\n' that will be used to join 'content'
content_length += string.length + 1;
content.push(string);
}
},
newObject = function () {
// Begin a new object
objectNumber++;
offsets[objectNumber] = content_length;
out(objectNumber + ' 0 obj');
return objectNumber;
},
// Does not output the object until after the pages have been output.
// Returns an object containing the objectId and content.
// All pages have been added so the object ID can be estimated to start right after.
// This does not modify the current objectNumber; It must be updated after the newObjects are output.
newAdditionalObject = function () {
var objId = pages.length * 2 + 1;
objId += additionalObjects.length;
var obj = {
objId: objId,
content: ''
};
additionalObjects.push(obj);
return obj;
},
// Does not output the object. The caller must call newObjectDeferredBegin(oid) before outputing any data
newObjectDeferred = function () {
objectNumber++;
offsets[objectNumber] = function () {
return content_length;
};
return objectNumber;
},
newObjectDeferredBegin = function (oid) {
offsets[oid] = content_length;
},
putStream = function (str) {
out('stream');
out(str);
out('endstream');
},
putPages = function () {
var n, p, arr, i, deflater, adler32, adler32cs, wPt, hPt,
pageObjectNumbers = [];
adler32cs = global.adler32cs || jsPDF.API.adler32cs;
if (compress && typeof adler32cs === 'undefined') {
compress = false;
}
// outToPages = false as set in endDocument(). out() writes to content.
for (n = 1; n <= page; n++) {
pageObjectNumbers.push(newObject());
wPt = (pageWidth = pagedim[n].width) * k;
hPt = (pageHeight = pagedim[n].height) * k;
out('<</Type /Page');
out('/Parent 1 0 R');
out('/Resources 2 0 R');
out('/MediaBox [0 0 ' + f2(wPt) + ' ' + f2(hPt) + ']');
// Added for annotation plugin
events.publish('putPage', {
pageNumber: n,
page: pages[n]
});
out('/Contents ' + (objectNumber + 1) + ' 0 R');
out('>>');
out('endobj');
// Page content
p = pages[n].join('\n');
newObject();
if (compress) {
arr = [];
i = p.length;
while (i--) {
arr[i] = p.charCodeAt(i);
}
adler32 = adler32cs.from(p);
deflater = new Deflater(6);
deflater.append(new Uint8Array(arr));
p = deflater.flush();
arr = new Uint8Array(p.length + 6);
arr.set(new Uint8Array([120, 156])),
arr.set(p, 2);
arr.set(new Uint8Array([adler32 & 0xFF, (adler32 >> 8) & 0xFF, (
adler32 >> 16) & 0xFF, (adler32 >> 24) & 0xFF]), p.length +
2);
p = String.fromCharCode.apply(null, arr);
out('<</Length ' + p.length + ' /Filter [/FlateDecode]>>');
} else {
out('<</Length ' + p.length + '>>');
}
putStream(p);
out('endobj');
}
offsets[1] = content_length;
out('1 0 obj');
out('<</Type /Pages');
var kids = '/Kids [';
for (i = 0; i < page; i++) {
kids += pageObjectNumbers[i] + ' 0 R ';
}
out(kids + ']');
out('/Count ' + page);
out('>>');
out('endobj');
events.publish('postPutPages');
},
putFont = function(font) {
events.publish('putFont', {
font: font,
out: out,
newObject: newObject
});
if (font.isAlreadyPutted !== true) {
font.objectNumber = newObject();
out('<<');
out('/Type /Font');
out('/BaseFont /' + font.postScriptName)
out('/Subtype /Type1');
if (typeof font.encoding === 'string') {
out('/Encoding /' + font.encoding);
}
out('/FirstChar 32');
out('/LastChar 255');
out('>>');
out('endobj');
}
},
putFonts = function () {
for (var fontKey in fonts) {
if (fonts.hasOwnProperty(fontKey)) {
putFont(fonts[fontKey]);
}
}
},
putXobjectDict = function () {
// Loop through images, or other data objects
events.publish('putXobjectDict');
},
putResourceDictionary = function () {
out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
out('/Font <<');
// Do this for each font, the '1' bit is the index of the font
for (var fontKey in fonts) {
if (fonts.hasOwnProperty(fontKey)) {
out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
}
}
out('>>');
out('/XObject <<');
putXobjectDict();
out('>>');
},
putResources = function () {
putFonts();
events.publish('putResources');
// Resource dictionary
offsets[2] = content_length;
out('2 0 obj');
out('<<');
putResourceDictionary();
out('>>');
out('endobj');
events.publish('postPutResources');
},
putAdditionalObjects = function () {
events.publish('putAdditionalObjects');
for (var i = 0; i < additionalObjects.length; i++) {
var obj = additionalObjects[i];
offsets[obj.objId] = content_length;
out(obj.objId + ' 0 obj');
out(obj.content);;
out('endobj');
}
objectNumber += additionalObjects.length;
events.publish('postPutAdditionalObjects');
},
addToFontDictionary = function (fontKey, fontName, fontStyle) {
// this is mapping structure for quick font key lookup.
// returns the KEY of the font (ex: "F1") for a given
// pair of font name and type (ex: "Arial". "Italic")
if (!fontmap.hasOwnProperty(fontName)) {
fontmap[fontName] = {};
}
fontmap[fontName][fontStyle] = fontKey;
},
/**
* FontObject describes a particular font as member of an instnace of jsPDF
*
* It's a collection of properties like 'id' (to be used in PDF stream),
* 'fontName' (font's family name), 'fontStyle' (font's style variant label)
*
* @class
* @public
* @property id {String} PDF-document-instance-specific label assinged to the font.
* @property postScriptName {String} PDF specification full name for the font
* @property encoding {Object} Encoding_name-to-Font_metrics_object mapping.
* @name FontObject
* @ignore This should not be in the public docs.
*/
addFont = function(postScriptName, fontName, fontStyle, encoding) {
var fontKey = 'F' + (Object.keys(fonts).length + 1).toString(10),
// This is FontObject
font = fonts[fontKey] = {
'id': fontKey,
'postScriptName': postScriptName,
'fontName': fontName,
'fontStyle': fontStyle,
'encoding': encoding,
'metadata': {}
};
addToFontDictionary(fontKey, fontName, fontStyle);
events.publish('addFont', font);
return fontKey;
},
addFonts = function () {
var HELVETICA = "helvetica",
TIMES = "times",
COURIER = "courier",
NORMAL = "normal",
BOLD = "bold",
ITALIC = "italic",
BOLD_ITALIC = "bolditalic",
encoding = 'StandardEncoding',
ZAPF = "zapfdingbats",
SYMBOL = "symbol",
standardFonts = [
['Helvetica', HELVETICA, NORMAL, 'WinAnsiEncoding'],
['Helvetica-Bold', HELVETICA, BOLD, 'WinAnsiEncoding'],
['Helvetica-Oblique', HELVETICA, ITALIC, 'WinAnsiEncoding'],
['Helvetica-BoldOblique', HELVETICA, BOLD_ITALIC, 'WinAnsiEncoding'],
['Courier', COURIER, NORMAL, 'WinAnsiEncoding'],
['Courier-Bold', COURIER, BOLD, 'WinAnsiEncoding'],
['Courier-Oblique', COURIER, ITALIC, 'WinAnsiEncoding'],
['Courier-BoldOblique', COURIER, BOLD_ITALIC, 'WinAnsiEncoding'],
['Times-Roman', TIMES, NORMAL, 'WinAnsiEncoding'],
['Times-Bold', TIMES, BOLD, 'WinAnsiEncoding'],
['Times-Italic', TIMES, ITALIC, 'WinAnsiEncoding'],
['Times-BoldItalic', TIMES, BOLD_ITALIC, 'WinAnsiEncoding'],
['ZapfDingbats', ZAPF, NORMAL, null],
['Symbol', SYMBOL, NORMAL, null]
];
for (var i = 0, l = standardFonts.length; i < l; i++) {
var fontKey = addFont(
standardFonts[i][0],
standardFonts[i][1],
standardFonts[i][2],
standardFonts[i][3]);
// adding aliases for standard fonts, this time matching the capitalization
var parts = standardFonts[i][0].split('-');
addToFontDictionary(fontKey, parts[0], parts[1] || '');
}
events.publish('addFonts', {
fonts: fonts,
dictionary: fontmap
});
},
SAFE = function __safeCall(fn) {
fn.foo = function __safeCallWrapper() {
try {
return fn.apply(this, arguments);
} catch (e) {
var stack = e.stack || '';
if (~stack.indexOf(' at ')) stack = stack.split(" at ")[1];
var m = "Error in function " + stack.split("\n")[0].split('<')[
0] + ": " + e.message;
if (global.console) {
global.console.error(m, e);
if (global.alert) alert(m);
} else {
throw new Error(m);
}
}
};
fn.foo.bar = fn;
return fn.foo;
},
to8bitStream = function (text, flags) {
/**
* PDF 1.3 spec:
* "For text strings encoded in Unicode, the first two bytes must be 254 followed by
* 255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
* with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
* to be a meaningful beginning of a word or phrase.) The remainder of the
* string consists of Unicode character codes, according to the UTF-16 encoding
* specified in the Unicode standard, version 2.0. Commonly used Unicode values
* are represented as 2 bytes per character, with the high-order byte appearing first
* in the string."
*
* In other words, if there are chars in a string with char code above 255, we
* recode the string to UCS2 BE - string doubles in length and BOM is prepended.
*
* HOWEVER!
* Actual *content* (body) text (as opposed to strings used in document properties etc)
* does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
*
* Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
* a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
* fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
* code page. There, however, all characters in the stream are treated as GIDs,
* including BOM, which is the reason we need to skip BOM in content text (i.e. that
* that is tied to a font).
*
* To signal this "special" PDFEscape / to8bitStream handling mode,
* API.text() function sets (unless you overwrite it with manual values
* given to API.text(.., flags) )
* flags.autoencode = true
* flags.noBOM = true
*
* ===================================================================================
* `flags` properties relied upon:
* .sourceEncoding = string with encoding label.
* "Unicode" by default. = encoding of the incoming text.
* pass some non-existing encoding name
* (ex: 'Do not touch my strings! I know what I am doing.')
* to make encoding code skip the encoding step.
* .outputEncoding = Either valid PDF encoding name
* (must be supported by jsPDF font metrics, otherwise no encoding)
* or a JS object, where key = sourceCharCode, value = outputCharCode
* missing keys will be treated as: sourceCharCode === outputCharCode
* .noBOM
* See comment higher above for explanation for why this is important
* .autoencode
* See comment higher above for explanation for why this is important
*/
var i, l, sourceEncoding, encodingBlock, outputEncoding, newtext,
isUnicode, ch, bch;
flags = flags || {};
sourceEncoding = flags.sourceEncoding || 'Unicode';
outputEncoding = flags.outputEncoding;
// This 'encoding' section relies on font metrics format
// attached to font objects by, among others,
// "Willow Systems' standard_font_metrics plugin"
// see jspdf.plugin.standard_font_metrics.js for format
// of the font.metadata.encoding Object.
// It should be something like
// .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
// .widths = {0:width, code:width, ..., 'fof':divisor}
// .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
if ((flags.autoencode || outputEncoding) &&
fonts[activeFontKey].metadata &&
fonts[activeFontKey].metadata[sourceEncoding] &&
fonts[activeFontKey].metadata[sourceEncoding].encoding) {
encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding;
// each font has default encoding. Some have it clearly defined.
if (!outputEncoding && fonts[activeFontKey].encoding) {
outputEncoding = fonts[activeFontKey].encoding;
}
// Hmmm, the above did not work? Let's try again, in different place.
if (!outputEncoding && encodingBlock.codePages) {
outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
}
if (typeof outputEncoding === 'string') {
outputEncoding = encodingBlock[outputEncoding];
}
// we want output encoding to be a JS Object, where
// key = sourceEncoding's character code and
// value = outputEncoding's character code.
if (outputEncoding) {
isUnicode = false;
newtext = [];
for (i = 0, l = text.length; i < l; i++) {
ch = outputEncoding[text.charCodeAt(i)];
if (ch) {
newtext.push(
String.fromCharCode(ch));
} else {
newtext.push(
text[i]);
}
// since we are looping over chars anyway, might as well
// check for residual unicodeness
if (newtext[i].charCodeAt(0) >> 8) {
/* more than 255 */
isUnicode = true;
}
}
text = newtext.join('');
}
}
i = text.length;
// isUnicode may be set to false above. Hence the triple-equal to undefined
while (isUnicode === undefined && i !== 0) {
if (text.charCodeAt(i - 1) >> 8) {
/* more than 255 */
isUnicode = true;
}
i--;
}
if (!isUnicode) {
return text;
}
newtext = flags.noBOM ? [] : [254, 255];
for (i = 0, l = text.length; i < l; i++) {
ch = text.charCodeAt(i);
bch = ch >> 8; // divide by 256
if (bch >> 8) {
/* something left after dividing by 256 second time */
throw new Error("Character at position " + i + " of string '" +
text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
}
newtext.push(bch);
newtext.push(ch - (bch << 8));
}
return String.fromCharCode.apply(undefined, newtext);
},
pdfEscape = function (text, flags) {
/**
* Replace '/', '(', and ')' with pdf-safe versions
*
* Doing to8bitStream does NOT make this PDF display unicode text. For that
* we also need to reference a unicode font and embed it - royal pain in the rear.
*
* There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
* which JavaScript Strings are happy to provide. So, while we still cannot display
* 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
* 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
* is still parseable.
* This will allow immediate support for unicode in document properties strings.
*/
return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(
/\(/g, '\\(').replace(/\)/g, '\\)');
},
putInfo = function () {
out('/Producer (jsPDF ' + jsPDF.version + ')');
for (var key in documentProperties) {
if (documentProperties.hasOwnProperty(key) && documentProperties[
key]) {
out('/' + key.substr(0, 1).toUpperCase() + key.substr(1) + ' (' +
pdfEscape(documentProperties[key]) + ')');
}
}
out('/CreationDate (' + creationDate + ')');
},
putCatalog = function () {
out('/Type /Catalog');
out('/Pages 1 0 R');
// PDF13ref Section 7.2.1
if (!zoomMode) zoomMode = 'fullwidth';
switch (zoomMode) {
case 'fullwidth':
out('/OpenAction [3 0 R /FitH null]');
break;
case 'fullheight':
out('/OpenAction [3 0 R /FitV null]');
break;
case 'fullpage':
out('/OpenAction [3 0 R /Fit]');
break;
case 'original':
out('/OpenAction [3 0 R /XYZ null null 1]');
break;
default:
var pcn = '' + zoomMode;
if (pcn.substr(pcn.length - 1) === '%')
zoomMode = parseInt(zoomMode) / 100;
if (typeof zoomMode === 'number') {
out('/OpenAction [3 0 R /XYZ null null ' + f2(zoomMode) + ']');
}
}
if (!layoutMode) layoutMode = 'continuous';
switch (layoutMode) {
case 'continuous':
out('/PageLayout /OneColumn');
break;
case 'single':
out('/PageLayout /SinglePage');
break;
case 'two':
case 'twoleft':
out('/PageLayout /TwoColumnLeft');
break;
case 'tworight':
out('/PageLayout /TwoColumnRight');
break;
}
if (pageMode) {
/**
* A name object specifying how the document should be displayed when opened:
* UseNone : Neither document outline nor thumbnail images visible -- DEFAULT
* UseOutlines : Document outline visible
* UseThumbs : Thumbnail images visible
* FullScreen : Full-screen mode, with no menu bar, window controls, or any other window visible
*/
out('/PageMode /' + pageMode);
}
events.publish('putCatalog');
},
putTrailer = function () {
out('/Size ' + (objectNumber + 1));
out('/Root ' + objectNumber + ' 0 R');
out('/Info ' + (objectNumber - 1) + ' 0 R');
out("/ID [ <" + fileId + "> <" + fileId + "> ]");
},
beginPage = function (width, height) {
// Dimensions are stored as user units and converted to points on output
var orientation = typeof height === 'string' && height.toLowerCase();
if (typeof width === 'string') {
var format = width.toLowerCase();
if (pageFormats.hasOwnProperty(format)) {
width = pageFormats[format][0] / k;
height = pageFormats[format][1] / k;
}
}
if (Array.isArray(width)) {
height = width[1];
width = width[0];
}
if (orientation) {
switch (orientation.substr(0, 1)) {
case 'l':
if (height > width) orientation = 's';
break;
case 'p':
if (width > height) orientation = 's';
break;
}
if (orientation === 's') {
tmp = width;
width = height;
height = tmp;
}
}
outToPages = true;
pages[++page] = [];
pagedim[page] = {
width: Number(width) || pageWidth,
height: Number(height) || pageHeight
};
pagesContext[page] = {};
_setPage(page);
},
_addPage = function () {
beginPage.apply(this, arguments);
// Set line width
out(f2(lineWidth * k) + ' w');
// Set draw color
out(drawColor);
// resurrecting non-default line caps, joins
if (lineCapID !== 0) {
out(lineCapID + ' J');
}
if (lineJoinID !== 0) {
out(lineJoinID + ' j');
}
events.publish('addPage', {
pageNumber: page
});
},
_deletePage = function (n) {
if (n > 0 && n <= page) {
pages.splice(n, 1);
pagedim.splice(n, 1);
page--;
if (currentPage > page) {
currentPage = page;
}
this.setPage(currentPage);
}
},
_setPage = function (n) {
if (n > 0 && n <= page) {
currentPage = n;
pageWidth = pagedim[n].width;
pageHeight = pagedim[n].height;
}
},
/**
* Returns a document-specific font key - a label assigned to a
* font name + font type combination at the time the font was added
* to the font inventory.
*
* Font key is used as label for the desired font for a block of text
* to be added to the PDF document stream.
* @private
* @function