forked from foliojs/pdfkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobject.coffee
70 lines (56 loc) · 2.16 KB
/
object.coffee
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
###
PDFObject - converts JavaScript types into their corrisponding PDF types.
By Devon Govett
###
class PDFObject
pad = (str, length) ->
(Array(length + 1).join('0') + str).slice(-length)
@convert: (object) ->
if Array.isArray object
items = (PDFObject.convert e for e in object).join(' ')
'[' + items + ']'
else if typeof object is 'string'
'/' + object
else if Buffer.isBuffer(object)
object.toString()
else if object instanceof PDFReference
object.toString()
else if object instanceof Date
'(D:' + pad(object.getUTCFullYear(), 4) +
pad(object.getUTCMonth(), 2) +
pad(object.getUTCDate(), 2) +
pad(object.getUTCHours(), 2) +
pad(object.getUTCMinutes(), 2) +
pad(object.getUTCSeconds(), 2) +
'Z)'
else if {}.toString.call(object) is '[object Object]'
out = ['<<']
for key, val of object
out.push '/' + key + ' ' + PDFObject.convert(val)
out.push '>>'
out.join '\n'
else
'' + object
# Convert Big-endian UCS-2 to Little-endian to support most PDFRreaders
swapBytes = (buff) ->
l = buff.length
if l & 0x01
throw new Error("Buffer length must be even")
else
for i in [0...l - 1] by 2
a = buff[i]
buff[i] = buff[i+1]
buff[i+1] = a
return buff
@s: (string, swap = false) ->
string = string.replace(/\\/g, '\\\\\\\\')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
if swap
string = swapBytes(new Buffer('\ufeff' + string, 'ucs-2')).toString('binary')
return new Buffer("("+string+")")
module.exports = PDFObject
PDFReference = require './reference'