I'm using IMGKIT in one of my projects and had to use their css with html option to satisfy a requirment. I noticed that if stylesheets are set as follows:
kit = IMGKit.new(html, :quality => 50)
kit.stylesheets << '/path/to/css/file'
and the stylesheet has a background property with a relative url('image.png'), image is not generated when exporting it using kit.to_file:
(Rails.root + "public/pngs/" + "image.png")
The request hangs, and if we replace the background url to full url with protocol, host and port, it is well exported.
Do I need to have absolute urls to all my images in my stylesheet?
I have tried defining asset_host in my development.rb file:
config.action_controller.asset_host = Proc.new { |source|
"#{request.protocol}#{request.host_with_port}"
}
It does replace the url in the css if I check on browser but still the images are not generated when exported through IMGKIT.
IMGKIT reqiured css with absolute url for any background image or other assets. So you can generate it dynamically following this link https://coderwall.com/p/exj0ig and some steps as
A) Put your all images in assets/images folder of rails app
B) Install gem 'sass-rails' if not install https://github.com/rails/sass-rails
C) create another css file name as css_file_name.css.sccs.erb
D) put your all other css file content in it.
E) In css file just put your image file name as below: background-image: image-url('image.png');
F) Use assets pipline (http://guides.rubyonrails.org/asset_pipeline.html#how-to-use-the-asset-pipeline) Run below command as your app mode: (1) Development Mode: RAILS_ENV=development bundle exec rake assets:precompile (2) Production Mode: RAILS_ENV=production bundle exec rake assets:precompile
G) In your config/environments/
(1) In development.rb config.action_controller.asset_host = "YOUR LOCAL HOST URL i.e YOUR_LOCALHOST_ADDRESS"
(2) In production.rb config.action_controller.asset_host = "http://assets.example.com" /YOUR ADDRESS/
H) And last relate your stylesheet with IMGKIT as below
html_content = "YOUR HTML CONTENT"
kit = IMGKit.new(html_content, height: 900, transparent:true, quality:10) /*YOUR SETTING*/
kit.stylesheets << "#{Rails.root}/public/assets/application.css"
file = kit.to_file(Rails.root + "public/pngs/" + "screenshot.png") /*YOUR IMAGE NAME*/
send_file("#{Rails.root}/public/pngs/screenshot.png", :filename => "screenshot.png", :type => "image/png",:disposition => 'attachment',:streaming=> 'true') /*YOUR ADDRESS WHERE U WANT TO STORE PNG FILE*/
I) Restart server and enjoy!!!!!
[NOTE: After every changes please run assets pipline command to get latest application.css which is made from .sccs.erb extension file.]
来源:https://stackoverflow.com/questions/14208403/rails-imgkit-issues-in-exporting-images-with-html-and-css