-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
88 lines (78 loc) · 2.35 KB
/
index.js
File metadata and controls
88 lines (78 loc) · 2.35 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var fs = require('fs')
var path = require('path')
var through = require('through2')
var streamft = require('stream-from-to')
var marked = require('marked')
var extend = require('extend')
var duplexer = require('duplexer')
var wkhtmltopdf = require('wkhtmltopdf')
marked.setOptions({
highlight: function (code) {
return require('highlight.js').highlightAuto(code).value
}
})
function mkpdf (opts) {
opts = opts || {}
opts.cssPath = opts.cssPath ? path.resolve(opts.cssPath) : path.join(__dirname, 'assets/pdf.css')
opts.highlightCssPath = opts.highlightCssPath ? path.resolve(opts.highlightCssPath) : path.join(__dirname, 'assets/github-gist.css')
opts.htmlPath = opts.htmlPath ? path.resolve(opts.htmlPath) : path.join(__dirname, 'assets/index.html')
opts.preProcessMd = opts.preProcessMd || function () { return through() }
opts.preProcessHtml = opts.preProcessHtml || function () { return through() }
opts.paperFormat = opts.paperFormat || 'A4'
opts.paperOrientation = opts.paperOrientation || 'portrait'
opts.paperBorder = opts.paperBorder || '2cm'
opts.disableToc = opts.disableToc || false
opts.tocTitle = opts.tocTitle || 'Table of Contents'
var md = ''
var mdToHtml = through(
function transform (chunk, enc, cb) {
md += chunk + '\n\n'
cb()
},
function flush (cb) {
this.push(marked(md))
this.push(null)
}
)
var htmlTemplate = fs.readFileSync(opts.htmlPath, 'utf8')
var wkopts = {
toc: !opts.disableToc,
outlineDepth: 2,
pageSize: opts.paperFormat,
orientation: opts.paperOrientation,
marginLeft: opts.paperBorder,
marginRight: opts.paperBorder,
marginTop: opts.paperBorder,
marginBottom: opts.paperBorder
}
if (!opts.disableToc) {
wkopts['tocHeaderText'] = opts.tocTitle
}
var html = ''
var htmlToPdf = through(
function transform (chunk, enc, cb) {
html += chunk
cb()
},
function flush (cb) {
var content = htmlTemplate.replace('{{content}}', html)
.replace('{{cssPath}}', opts.cssPath)
.replace('{{highlightCssPath}}', opts.highlightCssPath)
wkhtmltopdf(content, wkopts).pipe(outputStream)
}
)
var inputStream = through()
var outputStream = through()
inputStream
.pipe(opts.preProcessMd())
.pipe(mdToHtml)
.pipe(opts.preProcessHtml())
.pipe(htmlToPdf)
return extend(
duplexer(inputStream, outputStream),
streamft(function () {
return mkpdf(opts)
})
)
}
module.exports = mkpdf