summaryrefslogtreecommitdiffstats
path: root/lib/output/modifiers/svgToImg.js
blob: d088e3e00c17b87d2b94f74e3c9ee38c2a4a6a9f (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
var path = require('path');
var domSerializer = require('dom-serializer');

var editHTMLElement = require('./editHTMLElement');
var fs = require('../../utils/fs');

/**
    Render a cheerio DOM as html

    @param {HTMLDom} $
    @param {HTMLElement} dom
    @param {Object}
    @return {String}
*/
function renderDOM($, dom, options) {
    if (!dom && $._root && $._root.children) {
        dom = $._root.children;
    }
    options = options|| dom.options || $._options;
    return domSerializer(dom, options);
}

/**
    Replace SVG tag by IMG

    @param {String} baseFolder
    @param {HTMLDom} $
*/
function svgToImg(baseFolder, $) {
    return editHTMLElement($, 'svg', function($svg) {
        var content = '<?xml version="1.0" encoding="UTF-8"?>' +
            renderDOM($, $svg);

        // Generate a filename
        return fs.uniqueFilename(baseFolder, 'image.svg')
        .then(function(fileName) {
            var filePath = path.join(baseFolder, fileName);

            // Write the svg to the file
            return fs.writeFile(filePath, content, 'utf8')

            // Return as image
            .then(function() {
                $svg.replaceWith('<img src="/' + fileName + '" />');
            });
        });
    });
}

module.exports = svgToImg;