Skip to content

Instantly share code, notes, and snippets.

@zachy
Forked from jzajpt/gist:1826036
Created February 14, 2012 12:29
Show Gist options
  • Save zachy/1826458 to your computer and use it in GitHub Desktop.
Save zachy/1826458 to your computer and use it in GitHub Desktop.
require 'mini_magick'
#class InvalidInputFileError < Exception; end
class Converter
def initialize(input, output = nil)
#FILE nebo string
if html_file?(input)
#resit file
@file_input = input
elsif html_text?(input)
@text_input = input
#resit string
else
raise "Wrong input, .html file path or .html text expected"
end
if png_file?(output)
@output = output
else
if @file_input
@output = output_filename_from @file_input
else
@output = "result.png"
end
end
end
def convert_file
if @file_input
system(Dir.pwd+"/wkhtmltopdf-amd64",@file_input, "temporary.pdf")
else
temp = File.new("temporary.html", "w")
temp.write(@text_input)
temp.close
system(Dir.pwd+"/wkhtmltopdf-amd64","temporary.html", "temporary.pdf")
end
image = MiniMagick::Image.open("temporary.pdf")
image.format "png"
image.write Dir.pwd+"/"+@output
File.delete("temporary.pdf")
File.delete("temporary.html") if temp
end
protected
def html_file?(filename)
filename.match(/^(\w|\d|[\-\_])+\.html$/)
end
def png_file?(filename)
if filename
if filename.match(/^(\w|\d|[\-\_])+\.png$/)
return true
end
raise "Wrong output file format, expecting .png file name."
end
end
def html_text?(str)
str.match(/^<!DOCTYPE (html)|(HTML)/)
end
def output_filename_from(filename)
File.basename(filename, File.extname(filename))
end
end
htmlstr = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
TODO write content
</body>
</html>
'
conv = Converter.new("faktura.html", "aA_.png")
conv.convert_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment