summaryrefslogtreecommitdiffstats
path: root/lib/output/ebook.js
blob: 0cd18074191271917dbb63bb9aa8e868c5d78866 (plain)
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
var _ = require('lodash');
var util = require('util');
var juice = require('juice');

var command = require('../utils/command');
var fs = require('../utils/fs');
var Promise = require('../utils/promise');
var WebsiteOutput = require('./website');
var assetsInliner = require('./assets-inliner');

function _EbookOutput() {
    WebsiteOutput.apply(this, arguments);

    // ebook-convert does not support link like "./"
    this.opts.directoryIndex = false;
}
util.inherits(_EbookOutput, WebsiteOutput);

var EbookOutput = assetsInliner(_EbookOutput);

EbookOutput.prototype.name = 'ebook';

// Finish generation, create ebook using ebook-convert
EbookOutput.prototype.finish = function() {
    var that = this;
    if (that.book.isMultilingual()) {
        return EbookOutput.super_.prototype.finish.apply(that);
    }

    return Promise()
    .then(function() {
        return EbookOutput.super_.prototype.finish.apply(that);
    })

    // Generate SUMMARY.html
    .then(function() {
        return that.render('summary', that.getContext())
        .then(function(html) {
            return that.writeFile(
                'SUMMARY.html',
                html
            );
        });
    })

    // Start ebook-convert
    .then(function() {
        return that.ebookConvertOption();
    })

    .then(function(options) {
        if (!that.opts.format) return;

        var cmd = [
            'ebook-convert',
            that.resolve('SUMMARY.html'),
            that.resolve('index.'+that.opts.format),
            command.optionsToShellArgs(options)
        ].join(' ');

        return command.exec(cmd)
        .fail(function(err) {
            if (err.code == 127) {
                err = new Error('Need to install ebook-convert from Calibre');
            }

            throw err;
        });
    });
};

// Generate header/footer for PDF
EbookOutput.prototype.getPDFTemplate = function(tpl) {
    var that = this;
    var context = _.extend(
        {
            // Nunjucks context mapping to ebook-convert templating
            page: {
                num: '_PAGENUM_',
                title: '_TITLE_',
                section: '_SECTION_'
            }
        },
        this.getContext()
    );

    return this.render('pdf_'+tpl, context)

    // Inline css, include css relative to the output folder
    .then(function(output) {
        return Promise.nfcall(juice.juiceResources, output, {
            webResources: {
                relativeTo: that.root()
            }
        });
    });
};

// Locate the cover file to use
// Use configuration or search a "cover.jpg" file
// For multi-lingual book, it can use the one from the main book
EbookOutput.prototype.locateCover = function() {
    var cover = this.book.config.get('cover', 'cover.jpg');

    // Resolve to absolute
    cover = this.resolve(cover);

    // Cover doesn't exist and multilingual?
    if (!fs.existsSync(cover) && this.parent) {
        return this.parent.locateCover();
    }

    return cover;
};

// Generate options for ebook-convert
EbookOutput.prototype.ebookConvertOption = function() {
    var that = this;

    var options = {
        '--cover': this.locateCover(),
        '--title': that.book.config.get('title'),
        '--comments': that.book.config.get('description'),
        '--isbn': that.book.config.get('isbn'),
        '--authors': that.book.config.get('author'),
        '--language': that.book.config.get('language'),
        '--book-producer': 'GitBook',
        '--publisher': 'GitBook',
        '--chapter': 'descendant-or-self::*[contains(concat(\' \', normalize-space(@class), \' \'), \' book-chapter \')]',
        '--level1-toc': 'descendant-or-self::*[contains(concat(\' \', normalize-space(@class), \' \'), \' book-chapter-1 \')]',
        '--level2-toc': 'descendant-or-self::*[contains(concat(\' \', normalize-space(@class), \' \'), \' book-chapter-2 \')]',
        '--level3-toc': 'descendant-or-self::*[contains(concat(\' \', normalize-space(@class), \' \'), \' book-chapter-3 \')]',
        '--no-chapters-in-toc': true,
        '--max-levels': '1',
        '--breadth-first': true
    };

    if (that.opts.format == 'epub') {
        options = _.extend(options, {
            '--dont-split-on-page-breaks': true
        });
    }

    if (that.opts.format != 'pdf') return Promise(options);

    var pdfOptions = that.book.config.get('pdf');

    options = _.extend(options, {
        '--chapter-mark': String(pdfOptions.chapterMark),
        '--page-breaks-before': String(pdfOptions.pageBreaksBefore),
        '--margin-left': String(pdfOptions.margin.left),
        '--margin-right': String(pdfOptions.margin.right),
        '--margin-top': String(pdfOptions.margin.top),
        '--margin-bottom': String(pdfOptions.margin.bottom),
        '--pdf-default-font-size': String(pdfOptions.fontSize),
        '--pdf-mono-font-size': String(pdfOptions.fontSize),
        '--paper-size': String(pdfOptions.paperSize),
        '--pdf-page-numbers': Boolean(pdfOptions.pageNumbers),
        '--pdf-header-template': that.getPDFTemplate('header'),
        '--pdf-footer-template': that.getPDFTemplate('footer'),
        '--pdf-sans-family': String(pdfOptions.fontFamily)
    });

    return that.getPDFTemplate('header')
    .then(function(tpl) {
        options['--pdf-header-template'] = tpl;

        return that.getPDFTemplate('footer');
    })
    .then(function(tpl) {
        options['--pdf-footer-template'] = tpl;

        return options;
    });
};

// Don't write multi-lingual index for wbook
EbookOutput.prototype.outputMultilingualIndex = function() {

};

module.exports = EbookOutput;