-
-
Save seco/38c69227f62bf55c04540795232d482e to your computer and use it in GitHub Desktop.
render html into png image with phantomjs
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
'use strict'; | |
var system = require('system'); | |
var html = system.args[1]; | |
var width = system.args[2]; | |
var height = system.args[3]; | |
var page = require('webpage').create(); | |
page.viewportSize = { width: Number(width), height: Number(height) }; | |
page.clipRect = { width: Number(width), height: Number(height) }; | |
page.onLoadFinished = function (status) { | |
try { | |
if (status !== 'success') { | |
return phantom.exit(1) | |
} | |
system.stdout.write('data:image/png;base64,' + page.renderBase64('PNG')); | |
phantom.exit(); | |
} catch(err) { | |
console.error(err) | |
phantom.exit(1); | |
} | |
} | |
page.setContent('<!DOCTYPE html>' + decodeURI(html), 'http://example.com'); | |
setTimeout(function () { | |
phantom.exit(1) | |
}, 500); |
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
import {exec} from "child_process" | |
import * as path from "path" | |
const isOsx = Boolean(process.env.OSX as string); | |
const phantomJsPath = path.resolve(__dirname, "./phantomjs") | |
const PREFIX = "data:image/png;base64," | |
export default ( | |
htmlString: string, | |
width: number, | |
height: number, | |
): Promise<Buffer> => { | |
return new Promise((resolve, reject) => { | |
try { | |
const cmd = [ | |
`${path.join(phantomJsPath, isOsx ? "phantomjs_osx" : "phantomjs_linux-x86_64")}`, | |
"--debug=yes --ignore-ssl-errors=true", | |
`${path.join(phantomJsPath, "./screenshot.js")}`, | |
`"${encodeURI(htmlString)}" ${width} ${height}` | |
].join(" ") | |
exec(cmd, (err, stdout, stderr) => { | |
if (err) { | |
return reject(err); | |
} | |
if (stdout.startsWith(PREFIX)) { | |
resolve(new Buffer(stdout.substring(PREFIX.length), "base64")) | |
} else { | |
reject(new Error("Unknown error")) | |
} | |
}) | |
} catch (err) { | |
reject(err) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment