Last active
August 29, 2015 14:05
-
-
Save rangermeier/03dd9a495968e7ad9659 to your computer and use it in GitHub Desktop.
PDF converter server running in 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
/** | |
* Runs a server inside PhantomJS that converts HTML pages to PDF documents | |
* | |
* Usage: | |
* | |
* 1) start application with `phantomjs pdfserver.js <port>` | |
* <port> defaults to 8080 | |
* | |
* 2) Send HTTP Post request to localhost:8080 | |
* Pass parameters as JSON object | |
* Parameters: | |
* - input: Path to input file, either relative or with 'file://...' | |
* - output: Path for output file, relative or absolute path | |
* - format: page format for document, default "A4" | |
* - orientation: page orientation, default: "portrait" | |
*/ | |
var server = require('webserver').create(), | |
page = require('webpage').create(), | |
system = require('system'), | |
fs = require('fs'); | |
var port = system.args[1] || 8080; | |
var error = function(response, status, msg) { | |
response.statusCode = status; | |
response.write(msg); | |
response.close(); | |
} | |
console.log("starting PDF server on port "+ port) | |
var service = server.listen('127.0.0.1:'+port, function(request, response) { | |
var args, input, output, format, orientation; | |
try { | |
args = JSON.parse(request.post); | |
} catch (e) { | |
error(response, 400, "Bad parameters, error parsing JSON") | |
return; | |
} | |
input = args.input; | |
output = args.output; | |
if(!input || !output) { | |
error(response, 400, "<em>input</em> and <em>output</em> have to be specified"); | |
return; | |
} | |
format = args.format || 'A4'; | |
orientation = args.orientation || 'portrait'; | |
page.viewportSize = { width: 600, height: 600 }; | |
page.paperSize = { format: format, orientation: orientation, margin: '1cm' }; | |
if (args.zoom) { | |
page.zoomFactor = system.zoom; | |
} | |
page.open(input, function (status) { | |
if (status !== 'success') { | |
error(response, 404, "Can't open file"); | |
} else { | |
window.setTimeout(function () { | |
page.render(output); | |
response.statusCode = 200; | |
response.write(output); | |
response.close(); | |
}, 200); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment