aboutsummaryrefslogtreecommitdiff
path: root/lib/index.js
blob: a7afed7e21e1bee4d651f8f55976014deb444670 (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
var docxReader = require("./docx/docx-reader");
var DocumentConverter = require("./document-to-html").DocumentConverter;
var readStyle = require("./style-reader").readStyle;
var readOptions = require("./options-reader").readOptions;

exports.convertToHtml = convertToHtml;
exports.convertToMarkdown = convertToMarkdown;
exports.convert = convert;
exports.extractRawText = extractRawText;
exports.images = require("./images");
exports.transforms = require("./transforms");
exports.underline = require("./underline");
var docxStyleMap = require("./docx/style-map");
exports.writeStyleMapToDocx = docxStyleMap.writeStyleMap;

function convertToHtml(input, options) {
    return convert(input, options);
}

function convertToMarkdown(input, options) {
    var markdownOptions = Object.create(options || {});
    markdownOptions.outputFormat = "markdown";
    return convert(input, markdownOptions);
}

function convert(input, options) {
    options = options || {};
    return docxStyleMap.readStyleMap(input)
        .then(function(styleMap) {
            if (!options.styleMap && styleMap) {
                options.styleMap = styleMap;
            }
        })
        .then(function() {
            var fullOptions = readOptions(options);
            return docxReader.read(input)
                .then(function(documentResult) {
                    return documentResult.map(fullOptions.transformDocument);
                })
                .then(function(documentResult) {
                    return convertDocumentToHtml(documentResult, fullOptions);
                });
        });
}

function convertDocumentToHtml(documentResult, options) {
    var parsedOptions = Object.create(options);
    parsedOptions.styleMap = (options.styleMap || []).map(readStyle);
    var documentConverter = new DocumentConverter(parsedOptions);
    return documentResult.flatMapThen(function(document) {
        return documentConverter.convertToHtml(document);
    });
}


function extractRawText(input) {
    return docxReader.read(input)
        .then(function(documentResult) {
            return documentResult.map(convertElementToRawText);
        });
}

function convertElementToRawText(element) {
    if (element.type === "text") {
        return element.value;
    } else {
        var tail = element.type === "paragraph" ? "\n\n" : "";
        return (element.children || []).map(convertElementToRawText).join("") + tail;
    }
}

exports.styleMapping = function() {
    throw new Error('Use a raw string instead of mammoth.styleMapping e.g. "p[style-name=\'Title\'] => h1" instead of mammoth.styleMapping("p[style-name=\'Title\'] => h1")');
};