pdf.js
Version:
A PDF generation library for Node.js
153 lines (118 loc) • 3.82 kB
text/coffeescript
###
PDFDocument - represents an entire PDF document
By Devon Govett
###
fs = require 'fs'
PDFObjectStore = require './store'
PDFObject = require './object'
PDFReference = require './reference'
PDFPage = require './page'
class PDFDocument
constructor: ( = {}) ->
# PDF version
= 1.3
# Whether streams should be compressed
= true
# The PDF object store
= new PDFObjectStore
# A list of pages in this document
= []
# The current page
= null
# Initialize mixins
# Create the metadata
=
Producer: 'PDFKit'
Creator: 'PDFKit'
CreationDate: new Date()
= .data
if .info
[key] = val for key, val of .info
delete .info
# Add the first page
mixin = (name) =>
methods = require './mixins/' + name
for name, method of methods
this::[name] = method
# Load mixins
mixin 'color'
mixin 'vector'
mixin 'fonts'
mixin 'text'
mixin 'images'
mixin 'annotations'
addPage: (options = ) ->
# create a page object
= new PDFPage(this, options)
# add the page to the object store
.addPage
.push
# reset x and y coordinates
= .margins.left
= .margins.top
return this
ref: (data) ->
.ref(data)
addContent: (str) ->
.content.add str
return this # make chaining possible
write: (filename, callback) ->
fs.writeFile filename, , 'binary', callback
output: ->
out = []
out
out
out
out
return out.join('\n')
finalize: ->
# convert strings in the info dictionary to literals
for key, val of when typeof val is 'string'
[key] = PDFObject.s val
# embed the subsetted fonts
for family, font of
font.embed()
# finalize each page
for page in
page.finalize()
generateHeader: (out) ->
# PDF version
out.push "%PDF-#{@version}"
# 4 binary chars, as recommended by the spec
out.push "%\xFF\xFF\xFF\xFF\n"
return out
generateBody: (out) ->
offset = out.join('\n').length
for id, ref of .objects
object = ref.object()
ref.offset = offset
out.push object
offset += object.length + 1
= offset
generateXRef: (out) ->
len = .length + 1
out.push "xref"
out.push "0 #{len}"
out.push "0000000000 65535 f "
for id, ref of .objects
offset = ('0000000000' + ref.offset).slice(-10)
out.push offset + ' 00000 n '
generateTrailer: (out) ->
trailer = PDFObject.convert
Size: .length
Root: .root
Info:
out.push 'trailer'
out.push trailer
out.push 'startxref'
out.push
out.push '%%EOF'
toString: ->
"[object PDFDocument]"
module.exports = PDFDocument