rails convert html to image

流过昼夜 提交于 2019-12-03 06:51:04

问题


I'm looking for a way to convert html tags to a image on the fly...

That means, that I want to be able to make a image_tag with a path to a method which returns the image created form html.

I was looking for a solution on that, but couldn't come up with a proper way to solve that...

Any Ideas?

Maechi


回答1:


IMGkit can do the job (details on github)

Create JPGs using plain old HTML+CSS

kit = IMGKit.new('http://google.com')
kit.to_jpg
kit.to_jpeg 
kit.to_png
kit.to_tif
kit.to_tiff

or in your controller

@kit = IMGKit.new(render_as_string)

format.jpg do
  send_data(@kit.to_jpg, :type => "image/jpeg", :disposition => 'inline')
end



回答2:


I'm going to take a wild guess here and guess that you want to convert HTML to an image, so take a "snapshot" of a web page or something. I'm not sure exactly how to do this in one step, but one way to do it is to use PDFKit to convert to PDF and then use RMagick to convert to whatever image format you want.




回答3:


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/4563707/rails-convert-html-to-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!