-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
reference.coffee
52 lines (43 loc) · 1.53 KB
/
reference.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
###
PDFReference - represents a reference to another object in the PDF object heirarchy
By Devon Govett
###
zlib = require 'flate'
class PDFReference
constructor: (@id, @data = {}) ->
@gen = 0
@stream = null
@finalizedStream = null
object: ->
@finalize() if not @finalizedStream
out = ["#{@id} #{@gen} obj"]
out.push PDFObject.convert(@data)
if @stream || @finalizedStream
out.push "stream"
out.push @finalizedStream
out.push "endstream"
out.push "endobj"
return out.join '\n'
add: (s) ->
@stream ?= []
@stream.push if Buffer.isBuffer(s) then s.toString('binary') else s
finalize: (compress = false) ->
# cache the finalized stream
if @stream
data = @stream.join '\n'
if compress
# create a byte array instead of passing a string to the Buffer
# fixes a weird unicode bug.
data = new Buffer(data.charCodeAt(i) for i in [0...data.length])
compressedData = zlib.deflate(data)
@finalizedStream = compressedData.toString 'binary'
@data.Filter = 'FlateDecode'
@data.Length ?= @finalizedStream.length
else
@finalizedStream = data
else
@finalizedStream = ''
toString: ->
"#{@id} #{@gen} R"
module.exports = PDFReference
PDFObject = require './object'