1 | _ = require 'lodash'
|
2 | express = require 'express'
|
3 | enableDestroy = require 'server-destroy'
|
4 | Nightmare = require 'nightmare'
|
5 | debug = require('debug')('html5-to-pdf:nightmare')
|
6 |
|
7 | class Generator
|
8 | constructor: (@options) ->
|
9 | @nightmare = new Nightmare {}
|
10 |
|
11 | build: (callback) =>
|
12 | @startServer (error, url) =>
|
13 | return callback error, null if error?
|
14 | @nightmare.goto url
|
15 | @includeAssets()
|
16 | @nightmare.evaluate @addBody, @options.get('inputBody')?.toString()
|
17 | @nightmare.wait @options.get('renderDelay')
|
18 | outputPath = @options.get('outputPath')
|
19 | options = @options.get('options')
|
20 | debug {outputPath, options}
|
21 | @nightmare.pdf options unless outputPath?
|
22 | @nightmare.pdf outputPath, options if outputPath?
|
23 | @nightmare.end()
|
24 | .then @doneSuccess(callback)
|
25 | .catch @doneError(callback)
|
26 |
|
27 | doneSuccess: (callback) =>
|
28 | return (buf) =>
|
29 | @_server?.destroy?()
|
30 | callback null, buf
|
31 |
|
32 | doneError: (callback) =>
|
33 | return (error) =>
|
34 | @_server?.destroy?()
|
35 | callback error, null
|
36 |
|
37 | includeAssets: =>
|
38 | _.each @options.get('include'), ({ type, filePath }={}) =>
|
39 | @nightmare.inject type, filePath
|
40 | return
|
41 |
|
42 | addBody: (html) ->
|
43 | try
|
44 | body = document.querySelector "body"
|
45 | body.removeChild document.querySelector "p"
|
46 | container = document.createElement "div"
|
47 | container.innerHTML = html
|
48 | body.appendChild container
|
49 | return document
|
50 |
|
51 | startServer: (callback) =>
|
52 | return callback null, @options.get('templateUrl') if @options.get('templateUrl')?
|
53 | app = express()
|
54 | app.use express.static(@options.get('templatePath'))
|
55 | options = @options.get('options')
|
56 | @_server = app.listen options.port, (error) =>
|
57 | return callback error, null if error?
|
58 | enableDestroy @_server
|
59 | callback null, "http://#{options.host}:#{@_server.address().port}"
|
60 |
|
61 | module.exports = Generator
|