|
| 1 | +"use strict"; |
| 2 | +/*global phantom: false*/ |
| 3 | + |
| 4 | +var webpage = require("webpage"); |
| 5 | + |
| 6 | +if (phantom.args.length !== 3) { |
| 7 | + console.error("Usage: converter.js source dest scale"); |
| 8 | + phantom.exit(); |
| 9 | +} else { |
| 10 | + convert(phantom.args[0], phantom.args[1], Number(phantom.args[2])); |
| 11 | +} |
| 12 | + |
| 13 | +function convert(source, dest, scale) { |
| 14 | + var page = webpage.create(); |
| 15 | + |
| 16 | + page.open(source, function (status) { |
| 17 | + if (status !== "success") { |
| 18 | + console.error("Unable to load the source file."); |
| 19 | + phantom.exit(); |
| 20 | + return; |
| 21 | + } |
| 22 | + |
| 23 | + var dimensions = getSvgDimensions(page); |
| 24 | + page.viewportSize = { |
| 25 | + width: Math.round(dimensions.width * scale), |
| 26 | + height: Math.round(dimensions.height * scale) |
| 27 | + }; |
| 28 | + if (!dimensions.usesViewBox) { |
| 29 | + page.zoomFactor = scale; |
| 30 | + } |
| 31 | + |
| 32 | + // This delay is I guess necessary for the resizing to happen? |
| 33 | + setTimeout(function () { |
| 34 | + page.render(dest); |
| 35 | + phantom.exit(); |
| 36 | + }, 0); |
| 37 | + }); |
| 38 | +} |
| 39 | + |
| 40 | +function getSvgDimensions(page) { |
| 41 | + return page.evaluate(function () { |
| 42 | + /*global document: false*/ |
| 43 | + |
| 44 | + var el = document.documentElement; |
| 45 | + var bbox = el.getBBox(); |
| 46 | + |
| 47 | + var width = parseFloat(el.getAttribute("width")); |
| 48 | + var height = parseFloat(el.getAttribute("height")); |
| 49 | + var viewBoxWidth = el.viewBox.animVal.width; |
| 50 | + var viewBoxHeight = el.viewBox.animVal.height; |
| 51 | + var usesViewBox = viewBoxWidth && viewBoxHeight; |
| 52 | + |
| 53 | + if (usesViewBox) { |
| 54 | + if (width && !height) { |
| 55 | + height = width * viewBoxHeight / viewBoxWidth; |
| 56 | + } |
| 57 | + if (height && !width) { |
| 58 | + width = height * viewBoxWidth / viewBoxHeight; |
| 59 | + } |
| 60 | + if (!width && !height) { |
| 61 | + width = viewBoxWidth; |
| 62 | + height = viewBoxHeight; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + if (!width) { |
| 67 | + width = bbox.width + bbox.x; |
| 68 | + } |
| 69 | + if (!height) { |
| 70 | + height = bbox.height + bbox.y; |
| 71 | + } |
| 72 | + |
| 73 | + return { width: width, height: height, usesViewBox: usesViewBox }; |
| 74 | + }); |
| 75 | +} |
0 commit comments