Skip to content

Instantly share code, notes, and snippets.

@pavelvlasov
Created January 20, 2018 23:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pavelvlasov/b140ab9ba5ad28941fb02a08a0535375 to your computer and use it in GitHub Desktop.
Save pavelvlasov/b140ab9ba5ad28941fb02a08a0535375 to your computer and use it in GitHub Desktop.
render html into png image with phantomjs
'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);
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