UNPKG

3.19 kBJavaScriptView Raw
1
2/*
3PDFObject - converts JavaScript types into their corrisponding PDF types.
4By Devon Govett
5 */
6
7(function() {
8 var PDFObject, PDFReference;
9
10 PDFObject = (function() {
11 var escapable, escapableRe, pad, swapBytes;
12
13 function PDFObject() {}
14
15 pad = function(str, length) {
16 return (Array(length + 1).join('0') + str).slice(-length);
17 };
18
19 escapableRe = /[\n\r\t\b\f\(\)\\]/g;
20
21 escapable = {
22 '\n': '\\n',
23 '\r': '\\r',
24 '\t': '\\t',
25 '\b': '\\b',
26 '\f': '\\f',
27 '\\': '\\\\',
28 '(': '\\(',
29 ')': '\\)'
30 };
31
32 swapBytes = function(buff) {
33 var a, i, j, l, ref;
34 l = buff.length;
35 if (l & 0x01) {
36 throw new Error("Buffer length must be even");
37 } else {
38 for (i = j = 0, ref = l - 1; j < ref; i = j += 2) {
39 a = buff[i];
40 buff[i] = buff[i + 1];
41 buff[i + 1] = a;
42 }
43 }
44 return buff;
45 };
46
47 PDFObject.convert = function(object) {
48 var e, i, isUnicode, items, j, key, out, ref, string, val;
49 if (typeof object === 'string') {
50 return '/' + object;
51 } else if (object instanceof String) {
52 string = object;
53 isUnicode = false;
54 for (i = j = 0, ref = string.length; j < ref; i = j += 1) {
55 if (string.charCodeAt(i) > 0x7f) {
56 isUnicode = true;
57 break;
58 }
59 }
60 if (isUnicode) {
61 string = swapBytes(new Buffer('\ufeff' + string, 'utf16le')).toString('binary');
62 }
63 string = string.replace(escapableRe, function(c) {
64 return escapable[c];
65 });
66 return '(' + string + ')';
67 } else if (Buffer.isBuffer(object)) {
68 return '<' + object.toString('hex') + '>';
69 } else if (object instanceof PDFReference) {
70 return object.toString();
71 } else if (object instanceof Date) {
72 return '(D:' + pad(object.getUTCFullYear(), 4) + pad(object.getUTCMonth() + 1, 2) + pad(object.getUTCDate(), 2) + pad(object.getUTCHours(), 2) + pad(object.getUTCMinutes(), 2) + pad(object.getUTCSeconds(), 2) + 'Z)';
73 } else if (Array.isArray(object)) {
74 items = ((function() {
75 var k, len, results;
76 results = [];
77 for (k = 0, len = object.length; k < len; k++) {
78 e = object[k];
79 results.push(PDFObject.convert(e));
80 }
81 return results;
82 })()).join(' ');
83 return '[' + items + ']';
84 } else if ({}.toString.call(object) === '[object Object]') {
85 out = ['<<'];
86 for (key in object) {
87 val = object[key];
88 out.push('/' + key + ' ' + PDFObject.convert(val));
89 }
90 out.push('>>');
91 return out.join('\n');
92 } else if (typeof object === 'number') {
93 return PDFObject.number(object);
94 } else {
95 return '' + object;
96 }
97 };
98
99 PDFObject.number = function(n) {
100 if (n > -1e21 && n < 1e21) {
101 return Math.round(n * 1e6) / 1e6;
102 }
103 throw new Error("unsupported number: " + n);
104 };
105
106 return PDFObject;
107
108 })();
109
110 module.exports = PDFObject;
111
112 PDFReference = require('./reference');
113
114}).call(this);