forked from bpampuch/pdfmake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSVGMeasure.js
79 lines (64 loc) · 1.64 KB
/
SVGMeasure.js
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
import xmldoc from 'xmldoc';
/**
* Strip unit postfix, parse number, but return undefined instead of NaN for bad input
*
* @param {string} textVal
* @returns {?number}
*/
const stripUnits = textVal => {
var n = parseFloat(textVal);
if (typeof n !== 'number' || isNaN(n)) {
return undefined;
}
return n;
};
/**
* Make sure it's valid XML and the root tage is <svg/>, returns xmldoc DOM
*
* @param {string} svgString
* @returns {object}
*/
const parseSVG = (svgString) => {
var doc;
try {
doc = new xmldoc.XmlDocument(svgString);
} catch (err) {
throw new Error('SVGMeasure: ' + err);
}
if (doc.name !== "svg") {
throw new Error('SVGMeasure: expected <svg> document');
}
return doc;
};
class SVGMeasure {
constructor() {
}
measureSVG(svgString) {
let doc = parseSVG(svgString);
let docWidth = stripUnits(doc.attr.width);
let docHeight = stripUnits(doc.attr.height);
if ((docWidth === undefined || docHeight === undefined) && typeof doc.attr.viewBox === 'string') {
let viewBoxParts = doc.attr.viewBox.split(/[,\s]+/);
if (viewBoxParts.length !== 4) {
throw new Error("Unexpected svg viewbox format, should have 4 entries but found: '" + doc.attr.viewBox + "'");
}
if (docWidth === undefined) {
docWidth = stripUnits(viewBoxParts[2]);
}
if (docHeight === undefined) {
docHeight = stripUnits(viewBoxParts[3]);
}
}
return {
width: docWidth,
height: docHeight
};
}
writeDimensions(svgString, dimensions) {
let doc = parseSVG(svgString);
doc.attr.width = "" + dimensions.width;
doc.attr.height = "" + dimensions.height;
return doc.toString();
}
}
export default SVGMeasure;