[Awesome Ruby Gem] Use imgkit gem to generate images on the backend which renders HTML using Webkit
IMGKit
Create JPGs using plain old HTML+CSS. Uses wkhtmltoimage - http://github.com/antialize/wkhtmltopdf on the backend which renders HTML using Webkit.
Heavily based on PDFKit - https://github.com/jdpace/pdfkit/.
Installation
imkit
You can install it as a gem:
1 | gem install imgkit |
or add it into a Gemfile (Bundler):
1 | # Gemfile |
Then, run bundle install
.
1 | bundle install |
wkhtmltoimage
You can install it as a gem:
1 | gem install wkhtmltoimage-binary |
or add it into a Gemfile (Bundler):
1 | # Gemfile |
Then, run bundle install
.
1 | bundle install |
Install by hand: wkhtmltopdf - http://wkhtmltopdf.org/downloads.html
Use installer:
1 | sudo imgkit --install-wkhtmltoimage install latest version into /usr/local/bin |
Usages
1 | # IMGKit.new takes the HTML and any options for wkhtmltoimage |
Note: Ruby’s buffered I/O means that if you want to write the string data to a file or tempfile make sure to call #flush
to ensure the contents don’t get stuck in the buffer.
Configuration
wkhtmltoimage
binary location
If you’re on Windows or you installed wkhtmltoimage by hand to a location other than /usr/local/bin
you will need to tell IMGKit where the binary is. You can configure IMGKit like so:
1 | # config/initializers/imgkit.rb |
Default image format
May be set to one of IMGKit::KNOWN_FORMATS = [:jpg, :jpeg, :png]
1 | config.default_format = :png |
Prefix for tag options (see Usage) :
May be changed from its default (imgkit-):
1 | config.meta_tag_prefix = 'imgkit-option' |
Additional default options
Any flag accepted by wkhtmltoimage may be set thus:
1 | config.default_options = { |
For a flag which takes no parameters, use true for the value:
1 | 'no-images' => true |
For flags with multiple parameters, use an array:
1 | :cookie => ['my_session', '123BADBEEF456'] |
Overriding options
When initializing an IMGKit options may be may be set for the life time of the IMGKit object:
1 | IMGKit.new('http://example.com/form', :post => ['my_field', 'my_unique_value']) |
Rails
Mime Types
register a .jpg
mime type in:
1 | #config/initializers/mime_type.rb |
register a .png
mime type in:
1 | #config/initializers/mime_type.rb |
Controller Actions
You can respond in a controller with:
1 | @kit = IMGKit.new(render_to_string) |
- or -
1 | format.png do |
- or -
1 | respond_to do |format| |
This allows you to take advantage of rails page caching so you only generate the image when you need to.
–user-style-sheet workaround
To overcome the lack of support for --user-style-sheet
option by wkhtmltoimage 0.10.0 rc2 as reported
1 | require 'imgkit' |
CarrierWave Workaround
Contributed by @ticktricktrack
1 | class MyClass < ActiveRecord::Base |
References
[2] imgkit | RubyGems.org | your community gem host - https://rubygems.org/gems/imgkit/