Last active
July 23, 2016 14:49
-
-
Save madnight/34342f4c657e1d2964b5e57e67e09153 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'json' | |
require 'base64' | |
require 'tempfile' | |
require 'sinatra' | |
require 'pdfkit' | |
# HTTP Status Codes | |
OK, BAD_REQUEST, UNAUTHORIZED, INTERNAL_SERVER_ERROR = 200, 400, 401, 500 | |
# service is up and running | |
get '/' do | |
status OK | |
end | |
# accpets json html and parameters, returns pdf | |
post '/' do | |
begin | |
# parse json contents into variables | |
body = JSON.parse(request.body.read) | |
html, footer, token, options = body['content'], body['footer'], body['token'], body['options'] | |
html = html.nil? ? raise(ArgumentError, 'content missing') : Base64.strict_decode64(html) | |
footer = footer.nil? ? false : Base64.strict_decode64(footer) | |
# authentication via token | |
unless token.nil? ? raise(ArgumentError, 'token missing') : token == ENV['TOKEN'] | |
halt UNAUTHORIZED, { error: "invalid token" }.to_json # answer client | |
end | |
# error handling and logging | |
rescue ArgumentError, JSON::ParserError => e # empty content, invalid json or base64 | |
puts e.inspect # log message | |
halt BAD_REQUEST, { error: "#{e.message}" }.to_json | |
rescue => e # something else happened | |
puts e.inspect, e.backtrace | |
halt INTERNAL_SERVER_ERROR | |
end | |
options = options.nil? ? {} : options | |
if footer # wktohtml accepts footer only as file | |
tmp = Tempfile.new(['footer', '.html']) | |
tmp << footer; tmp.rewind; tmp.close | |
options['footer-html'] = tmp.path | |
end | |
status OK | |
PDFKit.new(html, options).to_pdf | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment