Last active
January 14, 2018 23:33
-
-
Save gunzip/0ef59bab2d304dc597513413f2bd9305 to your computer and use it in GitHub Desktop.
HTML to SVG screenshots with phantomjs (html to pdf) and inkscape (pdf to svg)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Requires `inkscape` and `phantomjs` installed globally | |
* Handles @media print and @media all | |
*/ | |
/* global phantom */ | |
/* global jQuery */ | |
const TIMEOUT_MS = 1000 | |
const page = require('webpage').create() | |
const system = require('system') | |
const address = system.args[1] | |
const output = system.args[2] | |
const pageWidth = parseInt(system.args[3], 10) | |
const pageHeight = parseInt(system.args[4], 10) | |
const spawn = require('child_process').spawn | |
function convertToSvg(path, cb) { | |
const dst = path.replace(/pdf$/, 'svg') | |
const cmd = spawn('inkscape', ['--without-gui', '--export-plain-svg=' + dst, path]) | |
cmd.on('close', cb) | |
cmd.on('exit', cb) | |
} | |
page.viewportSize = { | |
width: pageWidth, | |
height: pageHeight | |
} | |
page.open(address, function(status) { | |
if (status !== 'success') { | |
console.error('err', address) | |
phantom.exit(1) | |
} else { | |
page.evaluate(function() { | |
function activateAllStylesheets(document) { | |
for (var k in document.styleSheets) { | |
const styleSheet = document.styleSheets[k] | |
if (typeof styleSheet === 'object' && 'rules' in styleSheet && styleSheet.rules !== null) { | |
const rules = styleSheet.rules | |
Object.keys(rules) | |
.forEach(function(r) { | |
if (typeof rules[r].media !== 'undefined') { | |
rules[r].media.mediaText = rules[r].media.mediaText.replace('screen', 'all') | |
console.log(rules[r].media.mediaText) | |
} | |
}) | |
} | |
} | |
} | |
jQuery('[media]').attr('media', 'all') | |
setTimeout(function() { | |
activateAllStylesheets(document) | |
}, 200) | |
}) | |
window.setTimeout(function() { | |
page.render(output) | |
convertToSvg(output, phantom.exit) | |
}, TIMEOUT_MS) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment