blob: f31b06d1a416e1ce245e0de0191e2c3bfe0dd459 (
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
|
var path = require('path');
var crc = require('crc');
var domSerializer = require('dom-serializer');
var editHTMLElement = require('./editHTMLElement');
var fs = require('../../utils/fs');
var LocationUtils = require('../../utils/location');
/**
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, currentFile, $) {
var currentDirectory = path.dirname(currentFile);
return editHTMLElement($, 'svg', function($svg) {
var content = '<?xml version="1.0" encoding="UTF-8"?>' +
renderDOM($, $svg);
// We avoid generating twice the same PNG
var hash = crc.crc32(content).toString(16);
var fileName = hash + '.svg';
var filePath = path.join(baseFolder, fileName);
// Write the svg to the file
return fs.assertFile(filePath, function() {
return fs.writeFile(filePath, content, 'utf8');
})
// Return as image
.then(function() {
var src = LocationUtils.relative(currentDirectory, fileName);
$svg.replaceWith('<img src="' + src + '" />');
});
});
}
module.exports = svgToImg;
|