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