Giter Club home page Giter Club logo

imgkit's Introduction

IMGKit

Create JPGs using plain old HTML+CSS. Uses wkhtmltoimage on the backend which renders HTML using Webkit.

Heavily based on PDFKit.

Install

IMGKit

gem install imgkit

wkhtmltoimage

  1. Use the wkhtmltoimage-binary gem (mac + linux)
gem install wkhtmltoimage-binary
  1. Install by hand: http://wkhtmltopdf.org/downloads.html
  2. Use installer: sudo imgkit --install-wkhtmltoimage install latest version into /usr/local/bin (overwrite defaults with e.g. ARCHITECTURE=amd64 TO=/home/foo/bin)

Usage

# IMGKit.new takes the HTML and any options for wkhtmltoimage
# run `wkhtmltoimage --extended-help` for a full list of options
kit = IMGKit.new(html, :quality => 50)
kit.stylesheets << '/path/to/css/file'
kit.javascripts << '/path/to/js/file'

# Get the image BLOB
img = kit.to_img

# New in 1.3!
img = kit.to_img(:jpg)      #default
img = kit.to_img(:jpeg)
img = kit.to_img(:png)

# Save the image to a file
file = kit.to_file('/path/to/save/file.jpg')
file = kit.to_file('/path/to/save/file.png')

# IMGKit.new can optionally accept a URL or a File.
# Stylesheets nor Javascripts can not be added when source is provided as a URL of File.
kit = IMGKit.new('http://google.com')
kit = IMGKit.new(File.new('/path/to/html'))

# Add any kind of option through meta tags
IMGKit.new('<html><head><meta name="imgkit-quality" content="75"...

# Format shortcuts - New in 1.3!
IMGKit.new("hello").to_jpg
IMGKit.new("hello").to_jpeg
IMGKit.new("hello").to_png

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:

# config/initializers/imgkit.rb
IMGKit.configure do |config|
  config.wkhtmltoimage = '/path/to/wkhtmltoimage'
end

You could put the binaries in your bin/ folder and load the correct one depending on the platform and CPU type:

# config/initializers/imgkit.rb
IMGKit.configure do |config|
  if OS.linux? && OS.host_cpu == "x86_64"
    config.wkhtmltoimage =
      Rails.root.join("bin", "wkhtmltoimage-linux-amd64").to_s
  elsif OS.mac? && OS.host_cpu == "x86_64"
    config.wkhtmltoimage =
      Rails.root.join("bin", "wkhtmltoimage-macos-amd64").to_s
  else
    puts OS.report
    abort "You need to add a binary for wkhtmltoimage for your OS and CPU"
  end
end

To get wkhtmltoimage-linux-amd64 you can get the latest .deb (if you are targeting ubuntu) from https://github.com/wkhtmltopdf/packaging/releases

docker run -it -v $(pwd):/data ubuntu:latest /bin/bash
# or with fish
# docker run -it -v (pwd):/data ubuntu:latest /bin/bash
cd data
dpkg -x wkhtmltox_0.12.6-1.focal_amd64.deb out
exit
cp out/usr/local/bin/wkhtmltoimage bin/wkhtmltoimage-linux-amd64

And for wkhtmltoimage-macos-amd64 you can download the .pkg from https://github.com/wkhtmltopdf/packaging/releases, install it, then:

mv /usr/local/bin/wkhtmltoimage bin/wkhtmltoimage-macos-amd64

Default image format

May be set to one of IMGKit::KNOWN_FORMATS = [:jpg, :jpeg, :png]

  config.default_format = :png

Prefix for <meta> tag options (see Usage) :

May be changed from its default (imgkit-):

  config.meta_tag_prefix = 'imgkit-option'

Additional default options

Any flag accepted by wkhtmltoimage may be set thus:

  config.default_options = {
    :quality => 60
  }

For a flag which takes no parameters, use true for the value:

    'no-images' => true

For flags with multiple parameters, use an array:

    :cookie => ['my_session', '123BADBEEF456']

Overriding options

When initializing an IMGKit options may be may be set for the life time of the IMGKit object:

IMGKit.new('http://example.com/form', :post => ['my_field', 'my_unique_value'])

Heroku

get a version of wkhtmltoimage as an amd64 binary and commit it to your git repo. I like to put mine in "./bin/wkhtmltoimage-amd64"

version 0.10.0 has worked best for me

assuming its in that location you can just do:

IMGKit.configure do |config|
  config.wkhtmltoimage = Rails.root.join('bin', 'wkhtmltoimage-amd64').to_s if ENV['RACK_ENV'] == 'production'
end

If you're not using Rails just replace Rails.root with the root dir of your app.

Rails

Mime Types

register a .jpg mime type in:

#config/initializers/mime_type.rb
Mime::Type.register       "image/jpeg", :jpg

register a .png mime type in:

#config/initializers/mime_type.rb
Mime::Type.register       "image/png", :png

Controller Actions

You can respond in a controller with:

@kit = IMGKit.new(render_to_string)

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

- or -

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

- or -

respond_to do |format|
  send_data(@kit.to_img(format.to_sym),
            :type => "image/#{format}", :disposition => 'inline')
end

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 here http://code.google.com/p/wkhtmltopdf/issues/detail?id=387

  require 'imgkit'
  require 'restclient'
  require 'stringio'

  url = 'http://domain/path/to/stylesheet.css'
  css = StringIO.new( RestClient.get(url) )

  kit = IMGKit.new(<<EOD)
  <!DOCTYPE HTML>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>coolest converter</title>
  </head>
  <body>
    <div class="cool">image kit</div>
  </body>
  </html>
  EOD

  kit.stylesheets << css

Paperclip Example

Model:

class Model < ActiveRecord::Base
  # attr_accessible :title, :body
   has_attached_file :snapshot, :storage => :s3,
        :s3_credentials => "#{Rails.root}/config/s3.yml"
end

Controller:

def upload_image
   model = Model.find(params[:id])
   html  = render_to_string
   kit   = IMGKit.new(html)
   img   = kit.to_img(:png)
   file  = Tempfile.new(["template_#{model.id}", 'png'], 'tmp',
                         :encoding => 'ascii-8bit')
   file.write(img)
   file.flush
   model.snapshot = file
   model.save
   file.unlink
end

CarrierWave Workaround

Contributed by @ticktricktrack

  class MyClass < ActiveRecord::Base
    mount_uploader :snapshot, SnapshotUploader

    after_create :take_snapshot

    # private

    def take_snapshot
      file = Tempfile.new(["template_#{self.id.to_s}", '.jpg'], 'tmp', :encoding => 'ascii-8bit')
      file.write(IMGKit.new(self.html_body, quality: 50, width: 600).to_jpg)
      file.flush
      self.snapshot = file
      self.save
      file.unlink
    end
  end

Note on Patches/Pull Requests

  • Fork the project.
  • Setup your development environment with: gem install bundler; bundle install
  • Make your feature addition or bug fix.
  • Add tests for it. This is important so I don't break it in a future version unintentionally.
  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
  • Send me a pull request. Bonus points for topic branches.

Testing

Travis.yml is configured for multiple rubies, so I would just test a 2.1.x version and let travis handle the rest.

Copyright

Copyright (c) 2010 Chris Continanza Based on work by Jared Pace See LICENSE for details.

imgkit's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

imgkit's Issues

wkhtmltoimage --user-style-sheet not working

wkhtmltoimage user-style-sheet option is not working, as reported here: http://code.google.com/p/wkhtmltopdf/issues/detail?id=387

I noticed that stylesheets are inlined with something along the line:

stylesheet = 'non url/path/to/stylesheet'
File.read(stylesheet)

I was going to patch that with:

stylesheet = file # can be either a file path or something that responds to read
stylesheet.respond_to?(:read) && stylesheet.read || File.read(stylesheet)

Is there a better approach to allow loading/inlining of external stylesheet via URL?

IMGKit::CommandFailedError

So I tried following the basic example of converting a URL to an image. But I seem to get the following:

1.9.3-p392 :009 > IMGKit::VERSION
 => "1.4.1" 
1.9.3-p392 :010 > kit = IMGKit.new('http://google.com', quality: 40, zoom: 0.2)
 => #<IMGKit:0x0000000617cc70 @source=http://google.com, @stylesheets=[], @options={:height=>1000, :quality=>40, :zoom=>0.2}> 
1.9.3-p392 :011 > img = kit.to_img(:png) and 'good'
IMGKit::CommandFailedError: Command failed: /usr/local/bin/wkhtmltoimage --height 1000 --quality 40 --zoom 0.2 --format png http://google.com -: Loading page (1/2)
QSslSocket: cannot resolve SSLv2_client_method               ] 10%
QSslSocket: cannot resolve SSLv2_server_method
Rendering (2/2)                                                    
QPixmap: Cannot create a QPixmap when no GUI is being used   ] 25%
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used

        from /home/david/.rvm/gems/ruby-1.9.3-p392/gems/imgkit-1.4.1/lib/imgkit/imgkit.rb:111:in `to_img'
        from (irb):11
        from /home/david/.rvm/gems/ruby-1.9.3-p392/gems/railties-3.2.17/lib/rails/commands/console.rb:47:in `start'
        from /home/david/.rvm/gems/ruby-1.9.3-p392/gems/railties-3.2.17/lib/rails/commands/console.rb:8:in `start'
        from /home/david/.rvm/gems/ruby-1.9.3-p392/gems/railties-3.2.17/lib/rails/commands.rb:41:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'

I did also try following this comment: #32 (comment)

headless webkit fonts

This is actually more of an issue for wkhtmltoimage, but I thought it'd be worth noting (since we talked about it) that system font + @font-face support for the headless browser is mediocre. When I get time I'll take another look at it and see if there's a way to get decent font support into wkhtmltoimage, and then document that here.

Feel free to close this. This thing is the jam and I want it to succeed.

to_jpg => carrierwave

Hi, I don't really know where else to ask, so I do it here:

I'm trying to create a preview from html and store it as a carrierwave upload. I can use kit.to_file and then load the file in my class, but I'd rather assign the resulting image directly.

I'm my class I have defined an uploader

mount_uploader :snapshot, SnapshotUploader

and neither tries works:

my_object.snapshot  = IMGKit.new('testing 123').to_jpg
#or
my_object.snapshot = MiniMagick::Image.read(IMGKit.new('testing 123').to_jpg))

I guess I'm just missing some fundamental Rails knowledge here.
Ray

Weird characters in image

Whenever I use IMGkit to generate an image of my webpage, it places odd characters throughout the page. The characters are like a capital 'A' with a '^' above the A.

However, if I generate an image by directly calling the command line wkhtmltoimage, the characters do not show up. The image is generated correctly. Is there an encoding option I am missing?

I attached an image from our testing site for you to see.

f01

Installing on Ubuntu

It's a great gem. However, I ran into the following error when trying to install it on an Ubuntu Linux 12.04 server:

root@server:/var/www/sitename/staging/current# imgkit --install-wkhtmltoimage
/var/www/sitename/staging/shared/bundle/ruby/2.0.0/gems/imgkit-1.3.9/bin/imgkit:12:in `detect_architecture': Use RbConfig instead of obsolete and deprecated Config.
/var/www/sitename/staging/shared/bundle/ruby/2.0.0/gems/imgkit-1.3.9/bin/imgkit:12:in `detect_architecture': Use RbConfig instead of obsolete and deprecated Config.
/usr/local/rvm/gems/ruby-2.0.0-p0@global/gems/bundler-1.3.0/lib/bundler.rb:272: warning: Insecure world writable dir /var/www/sitename/staging/shared/bundle/ruby in PATH, mode 040777
rm: cannot remove `/usr/local/bin/wkhtmltoimage': No such file or directory
Downloading wkhtmltoimage-0.11.0_rc1-static-amd64.tar.bz2 from http://wkhtmltopdf.googlecode.com/files/wkhtmltoimage-0.11.0_rc1-static-amd64.tar.bz2
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 10.6M  100 10.6M    0     0  1441k      0  0:00:07  0:00:07 --:--:-- 1942k
Installing wkhtmltoimage-0.11.0_rc1-static-amd64.tar.bz2 to /usr/local/bin/wkhtmltoimage
mv: cannot stat `wkhtmltoimage': No such file or directory
chmod: cannot access `/usr/local/bin/wkhtmltoimage': No such file or directory

I can then do the following, and after that I can use IMGKit without problems:

$ cd /tmp
$ mv wkhtmltoimage-amd64 /usr/local/bin/wkhtmltoimage

Thanks,
/Lasse

Broken output image

I got broken image when trying to create an image from an address. Here is my code:

kit = IMGKit.new("http://www.abv.bg/")
kit.to_file(Rails.root + "public/image.jpg")

Configuration is
`require 'imgkit'

IMGKit.configure do |config|
config.wkhtmltoimage = "c:/Program Files (x86)/wkhtmltopdf/wkhtmltoimage.exe"
config.default_options = {
:quality => 100,
# :encoding => "ASCII-8BIT", # tried with both and without encoding
:encoding => "UTF-8",
:binmode => false # tried also without this
}
config.default_format = :jpg
end
`
The result is
image

When run the command in the console a valid image is created:
wkhtmltoimage "http://www.abv.bg" "d:\image.jpg"

Also tried with both 0.10.0.rc2 and 0.11.0.rc1 versions of wkhtmltoimage.

I am on Windows 7 64bit, Rails 3.2.13, got ImageMagick (if this is important).

Any help or ideas are welcome.

Support for PhantomJS

I wrote a wkhtmltoimage wrapper for PhantomJS. It's a work in progress / proof of concept. https://github.com/sodabrew/pjhtmltopdf

Some questions before I continue more work on this:

  • Would you like to support PhantomJS?
  • Should that support happen by drop-in script...
  • ...or would you prefer "native" phantomjs support in IMGKit?

Setting default width in meta tags?

I tried creating a meta tag like this: <meta name="imgkit-width" content="900" />

This is not working. The image is always generated as 1024px wide.

Error when screenshotting

This is not necessarily about the gem. FYI - I think it's awesome!

But I'm attempting to get a screenshot of items on our site, but it errors:

/tmp $ /app/bin/wkhtmltoimage-amd64 --quality 60 --format jpg http://spokely.com /tmp/screenshot.png
Loading page (1/2)
Rendering (2/2)                                                    
Error: Will not output an empty image                             
QPainter::begin: Paint device returned engine == 0, type: 3
Segmentation fault

However, when I try with Google, it works:

~ $ /app/bin/wkhtmltoimage-amd64 --quality 60 --format jpg http://www.google.com /tmp/screenshot.png
Loading page (1/2)
Rendering (2/2)                                                    
QPixmap: Cannot create a QPixmap when no GUI is being used   ] 25%
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used
Done   

Do you have any idea what on the site would cause it not to work???

'which' command in configuration.rb fails on Windows

Not sure if imgkit is supported on Rails 2 . . . but if it is, I can't seem to get it to work with Windows. The configuration.rb accounts for the existence of bundle or the 'which' command, and neither of these is available using Rails 2 on Windows. Thoughts?

not working with url source referring to application

--following is what i'm trying to do......

filename = current_user.slug + "-" + Time.now.to_i.to_s
kit = IMGKit.new("http://127.0.0.1:3000/snapshot/#{current_user.slug}")
img = kit.to_img(:png)
temp_dir = Rails.root.join('tmp')
Dir.mkdir(temp_dir) unless Dir.exists?(temp_dir)
file = Tempfile.new([filename, 'png'], temp_dir,
:encoding => 'ascii-8bit')
file.write(img)
file.flush
current_user.shares.create!(share_type: "image", snap: file)
file.unlink

--when the url source is "http://127.0.0.1:3000" or my staging app url "http://recroup-stage.herokuapp.com/ " it goes into an endless loop...

--when i do the same thing in rails console it works but not in the app

--please let me know what i'm doing wrong here..

Is there a way to take snapshot of a website when it's fully loaded?

My Code :

    resource = Resource.find_by_id(resource_id)
    kit   = IMGKit.new(url, 'load-error-handling' => 'ignore')
    img   = kit.to_img(:png)
    file  = Tempfile.new("template_"+resource_id.to_s+'.png', 'tmp',
                           :encoding => 'ascii-8bit')
    file.write(img)
    file.flush

    resource.image = file

    if resource.save
      file.unlink
    end

When it makes snapshot of some website with loading, it immediately saves the loading screen to the image, is there way to wait until the website is fully loaded, then save it to image?

xvfb-run error pointing to incorrect wkhtmltoimage path

I have the config setup for wkhtmltoimage as such

 2.0.0-p247 :015 > IMGKit.to_json
  => "{\"configuration\":{\"meta_tag_prefix\":\"imgkit-\",\"default_options\":{\"height\":1000},\"default_format\":\"jpg\",\"wkhtmltoimage\":\"/home/wecora/bin/wkhtmltoimage\"}}" 

but trying to run IMGKit always produces the following error:

  2.0.0-p247 :001 > kit = IMGKit.new('http://google.com')
   => #<IMGKit:0x00000007bc1ef0 @source=#<IMGKit::Source:0x00000007bc1e00 @source="http://google.com">, @stylesheets=[], @options={:height=>1000}> 
  2.0.0-p247 :002 > img = kit.to_img(:jpg)
   => "/usr/bin/xvfb-run: line 166: /bin/wkhtmltoimage: No such file or directory\n" 

As can be seen, xvfb-run is looking for wkhtmltoimage in the wrong location and I have no idea how to point it to the correct location. Any suggestions?

Bad snapshot while "Exit with code 2 due to http error: 404 Page not found"

Hi guys, thank you for this great gem!
I'm using it in my project but I have a big problem! When I try to make a snapshot of a webpage with corrupted internal files (e.g. image src not found), the result snapshot appears without linked stylesheets (they originally works). And it doesn't happen everytime, but only sometimes on the same webpage. Below my script:

I try this command-line:
wkhtmltoimage --width 1530 --height 1010 --no-stop-slow-scripts --javascript-delay 500 --load-error-handling skip http://example.com /path/file.jpg

With this output:
Loading page (1/2)
Warning: SSL error ignored
Rendering (2/2)
Done
Exit with code 2 due to http error: 404 Page not found

I convert the same string in ruby in this way:
kit = IMGKit.new( 'http://example.com', 'width' => '1530', 'height' => '1010', 'no-stop-slow-scripts' => true, 'javascript-delay' => 500, 'load-error-handling' => 'skip' )

How can I catch the wkhtmltoimage errors in IMGKIT?

Thank you

PS I'm using wkhtmltoimage 0.10 on ubuntu amd64 because the 0.11 doesn't work.

IMG Unicode Problem

Dear Mr. Chris Continanza
I have a question to ask you. I have a problem with IMGKit. when I save the file to image file with unicode language it does not support. like Thailand language when render from thailand website it does not support thailand language and other unicode language. why ?

IMGKit on heroku

As per instructions https://github.com/csquared/IMGKit

I've placed the wkhtmltoimage as an amd64 binary inside ./bin/wkhtmltoimage-amd64 in app directory of my rails app

and have config/initializers/imgkit.rb as follows:

IMGKit.configure do |config|
config.wkhtmltoimage = Rails.root.join('bin', 'wkhtmltoimage-amd64').to_s if ENV['RACK_ENV'] == 'production'
end

But I keep getting IMGKit::NoExecutableError (No wkhtmltoimage executable found at location

Any help is much appreciated

Why i can not render jpg?

Hi. Here is the code:

This does not work(it looks like it gets into endless loop:
@kit = IMGKit.new("http://localhost:3000")
file = @kit.to_file('/home/miha/uploads/file.jpg')

when i disable the web server i get:
Command failed: /usr/local/bin/wkhtmltoimage --quality 80 --format jpg http://localhost:3000 -: Loading page (1/2)
[> ] 0%
[======> ] 10%
[============================================================] 100%
Error: Failed loading page http://localhost:3000 (sometimes it will work just to ignore this error with --load-error-handling ignore)

On the other hand, this works perfectly:
@kit = IMGKit.new("http://www.google.com")
file = @kit.to_file('/home/miha/uploads/file.jpg')

Any help?

Thank you!

Miha

can I capture full screen

I try option {:height => '100%'} and it through error.
Is there any way to capture full screen.
I wonder maybe use merchanize get it height then setting capture But I don't know merchanize can get heigh of page or not?
Could you share me any idea?

Source#url? returns true erroneously

The regular expression that Source#url? uses to determine if the url_file_or_html is a URL returns true if any line in the passed in string starts with http. If you pass in HTML that happens to have a line beginning with a URL, then Source#url? returns true, and IMGKit tries to retrieve content from http://{HTML CONTENT}.

For example:

html = "<p>
some text with a non-linked URL
http://google.com/
</p>"

IMGKit::Source.new(html).url? # => true

This is happening because the regular expression in Source#url? is matching each line in the input. To fix this, you could use a regular expression that tests for URLs more comprehensively, or you could change the regular expression from /^http/ to /\Ahttp/. (In other words, change from matching the beginnings of lines to matching the beginning of the entire string.) The latter solution is simpler, but it still will fail if someone happens to have HTML that begins with a URL.

Let me know which solution you prefer, and I can provide a pull request.

Thanks for the library. It's working perfectly for me otherwise.

Chris

to_tiff method doesn't seem to work

Thanks for this excellent gem! I've got jpgs and pngs working great, but am having some issues with tiffs. I'm using pretty much the code you've provided, like so:

    @kit = IMGKit.new(render_to_string('show'))
    send_data(@kit.to_tiff, :type => "image/tiff", :disposition => 'attachment', :filename => "image.tiff")

This does indeed produce a tiff (or a tiff container), but the file seems to be corrupted--it can't be opened by anything. I get this error from Preview: "It may be damaged or use a file format that Preview doesn’t recognize."

I did note this issue with wkhtmltoimage itself: http://code.google.com/p/wkhtmltopdf/issues/detail?id=534

It looks like passing an html string is a problem, but hitting a URL isn't an issue. Have you heard of anyone else having this issue? I'm happy to fork and investigate, but I just wanted to see if anyone else could confirm/deny this issue.

Thanks!

Problem with paperclip

Hello, I am using this gem and everything was working well. For some reason it stopped working.
My code is VERY simple.
The variables cssstring and html_to_show have contents.

class NonProfitsController < ApplicationController
    def show
       @non_profit = NonProfit.find_by_id(params[:id])
       save_snapshot(@non_profit)
    end

   private 
   def save_snapshot(non_profit)
       url = request.protocol()+request.host_with_port  + '/assets/blocks.css'
       css = StringIO.new( RestClient.get(url) )
       cssstring = css.string
       html_to_show = render_to_string :partial => 'blocks/blocks.html.erb' 
       html_to_show = "<html><head><style>" + cssstring + "</style></head><body>" + html_to_show + "</body></html>"
       kit = IMGKit.new(html_to_show, quality: 40, zoom: 0.2)
       img = kit.to_img(:png)
       file = Tempfile.new(["template_#{non_profit.id.to_s}", 'png'], 'tmp', :encoding => 'ascii-8bit')
       file.write(img)
       non_profit.snapshot = file
       file.unlink

       non_profit.save
   end
end

This is my config file.

IMGKit.configure do |config|
  config.wkhtmltoimage = '/usr/local/bin/wkhtmltoimage'
  config.default_options = {
    :quality => 60
  }
  config.default_format = :png
end

I am getting the following errors:

can't convert nil into String

Application Trace | Framework Trace | Full Trace
app/controllers/non_profits_controller.rb:31:in save_snapshot' app/controllers/non_profits_controller.rb:6:inshow'

IMPORTANT: Line 31 is "non_profit.snapshot = file"

This is my model

class NonProfit < ActiveRecord::Base
  has_attached_file :snapshot, :storage => :s3, 
      :s3_credentials => "#{Rails.root}/config/s3.yml"
 end

cant convert to img

This is what i do on a rails console:
kit = IMGKit.new("http://www.google.com", quality: 40, zoom: 0.2)
img = kit.to_img(:png)

and the result is an error like this:

Errno::ENOEXEC: Exec format error - /Users/danielaguilar/Documents/acid/efizity/lib/wkhtmltoimage-i386
from /Users/danielaguilar/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/1.9.1/open3.rb:202:in spawn' from /Users/danielaguilar/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/1.9.1/open3.rb:202:inpopen_run'
from /Users/danielaguilar/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/1.9.1/open3.rb:90:in popen3' from /Users/danielaguilar/.rvm/gems/ruby-1.9.2-p320@efizity/gems/imgkit-1.3.7/lib/imgkit/imgkit.rb:88:incapture3'
from /Users/danielaguilar/.rvm/gems/ruby-1.9.2-p320@efizity/gems/imgkit-1.3.7/lib/imgkit/imgkit.rb:108:in to_img' from (irb):2 from /Users/danielaguilar/.rvm/gems/ruby-1.9.2-p320@efizity/gems/railties-3.1.3/lib/rails/commands/console.rb:45:instart'
from /Users/danielaguilar/.rvm/gems/ruby-1.9.2-p320@efizity/gems/railties-3.1.3/lib/rails/commands/console.rb:8:in start' from /Users/danielaguilar/.rvm/gems/ruby-1.9.2-p320@efizity/gems/railties-3.1.3/lib/rails/commands.rb:40:in<top (required)>'
from script/rails:6:in require' from script/rails:6:in

'

taking options in meta tags does not seem to be working

Love the gem. I don't seem to be able to get IMGKit to pass height, width or crop options to wdhtmltoimage via meta tags. For example, there is no response to this meta tag:

meta name='imgkit-height' content='420'

In a rails controller i have:

kit = IMGKit.new("https://www.myapp.com/applet/?auth_token=" + token)
img = kit.to_img(:jpg)
file = kit.to_file(Rails.root + "public/profile_images/" + filename)

For what it is worth, I wrote this post (http://stackoverflow.com/questions/10146873/imgkit-in-a-rails-3-app-to-email-an-image-of-a-web-page) and there are a significant amount of views in a short period of time.

immediately rendering an IMGKit image

I'm fairly new to Rails, and I'm having a hard time configuring IMGKit to the needs of my app. I want to be able to immediately turn around and display the IMGKit image in a pop-up image without saving the IMGKit image anywhere or emailing it. Is this possible?

In my controller:
@kit = IMGKit.new("http://www.google.com")

And then in my view:
I'd like to do something similar to <%= image_tag(@kit) %>
Can someone please advise?

Not able to pass custom_header option

When I run command in shell:

/usr/local/bin/wkhtmltoimage --no-stop-slow-scripts --use-xserver --custom-header 'User-Agent' 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7' --custom-header-propagation http://whatsmyuseragent.com/ mobile_agent.png

It works perfect. User agent is set as needed. But when I try to make it in ruby code:

kit = IMGKit.new "http://whatsmyuseragent.com/", {use_xserver: true,
  no_stop_slow_scripts: true, 
  custom_header: "'User-Agent' 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7'", 
  custom_header_propagation: true}

File.open('mobile_agent.png', 'w', :encoding => 'ascii-8bit') {|f| f.write kit.to_img(:png) }

It gets me Bad Request - Invalid Header

Debugging or logging missing

The implementation works perfectly locally or via the console, but when we try to run it in our app on the remote servers it fails. Unfortunately there is NO debugging or error logging anywhere to help us figure out what is going on.

Is there some way to turn on logging so we can get SOME insight into what is going on?

Can not capture some page

I am using rubyrails3
when capture page thegioikpop.com, It through error

QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Cannot create a QPixmap when no GUI is being used

I search for solution and see this http://code.google.com/p/wkhtmltopdf/issues/detail?id=786
=> wkhtmltoimage --use-xserver
How to config --use-xserver in gem IMGKit.
Need your helps :)

"Timeout" option to IMGKit.new

Hi people,

I'm loving using IMGKit, but I'm having some problems with pages that load forever (yes, they don't give me error and they don't give me the page, just load 'forever').

I already try to use Timeout with IMGKit, but this seems to not work. So, I wanna suggest a thing that can save a lot of people: Timeout option to IMGKit.new.

I'm talking about something like:
IMGKit.new('http://www.myurl.com', :quality => 80, (...), :timeout => 5)

In this example, if website don't finish loading or website gives you a 404 error in 5 seconds, IMGKit returns "nil" or something like that.

What you think?

/config/unicorn.conf: No such file or directory - bundle exec which wkhtmltoimage

IMGKit.configure do |config|
  config.wkhtmltoimage = "#{Rails.root}/lib/assets/wkhtmltoimage"
end

It run fine at local. But in sever it through error 502 . and in unicorn log:

unicorn worker[1] -D -c /home/rails/....com/config/unicorn.conf: No such file or directory - bundle exec which wkhtmltoimage
E, [2013-11-06T13:44:27.575282 #12544] ERROR -- : undefined method `chomp' for nil:NilClass (NoMethodError)
/home/rails/....com/vendor/bundle/ruby/1.9.1/gems/imgkit-1.3.9/lib/imgkit/configuration.rb:9:in `initialize'
/home/rails/....com/vendor/bundle/ruby/1.9.1/gems/imgkit-1.3.9/lib/imgkit/configuration.rb:27:in `new'
/home/rails/....com/vendor/bundle/ruby/1.9.1/gems/imgkit-1.3.9/lib/imgkit/configuration.rb:27:in `configuration'
/home/rails/....com/vendor/bundle/ruby/1.9.1/gems/imgkit-1.3.9/lib/imgkit/configuration.rb:32:in `configure'
/home/rails/....com/config/initializers/imgkit.rb:1:in `<top (required)>'

I run: which wkhtmltoimage OR bundle exec which wkhtmltoimage. it return:
/usr/local/bin/wkhtmltoimage

I don't know why it happen. search google not find any match my error

Trouble Figuring Out How to Install wkhtmltoimage

After running "gem install imgkit" and adding the gem to my gemfile, I try running "sudo imgkit --install-wkhtmltoimage" but it can't find the file. I tried downloading the executable, but I can't seem to figure out the right place to put it (As you can tell, I'm really bad with installation. Always have been). I'm on Mac OSX.

Issues in exporting images with html and css

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 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?

Using IMGKit in Mailers

I'm trying to use the Paperclip sample code and adapt it for using ActionMailer. It seems like something is getting lost between creating a Tempfile and storing it as an attachment. Is anyone else trying to do the same?

def new_user(user)
    @user = user

     kit   = IMGKit.new('http://google.com')
     img   = kit.to_img(:png)
     file  = Tempfile.new(["mail_#{user.id}", 'png'], 'tmp',
                     encoding: 'ascii-8bit')
     file.write(img)
     file.flush

    attachments.inline["mail_1234.png"] = file
    file.unlink

    mail to: @user.email, subject: "Welcome!: #{@user.name}"
end

output files corrupted by wkhtmltoimage

I have found a case where wkhtmltoimage incorrectly prepends a jpg file written to stdout with a console progress message. I've posted an issue on the wkhtmltopdf list with an example - http://code.google.com/p/wkhtmltopdf/issues/detail?id=981&start=400

Because IMGKit#to_file(path) captures the generated image via stdout before writing to the specified file, this turns out to be a problem here as well. And the chances of it being fixed upstream seem slim considering the number of open issues on wkhtmltopdf/image.

The solution I'm currently using is to modify #to_file so that it specifies the output filename to wkhtmltoimage directly, rather than relying on stdout. My code is here - MarkMT@5c680be .

This is not necessarily the most elegant solution, since although it solves the #to_file problem, it doesn't avoid data generated by #to_img being corrupted in the same way.

Stalling out

I'm running this img = IMGKit.new('http://google.com').to_png in my rails console and stalls then displays a bunch of things like this

\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00

What's going on?

Path for images in <img> tags

While embedding images with html there is an issue with mentioning image path . A path starting with "http://localhost:3000/" sends the rails server into a loop .

question = IMGKit.new('< img_tag src = 'http://localhost:3000/assets/qimage/629a3a4_1_original.jpg' />',:quality => 100)

question.to_file("/home/superq/quizot/app/assets/images/questions/test_123.jpg")

If I use an absolute path of my local machine , it works fine . However that is not a very convenient option . How should the path of the image be mentioned ? I am on Rails 3

Note : I am using img_tag above so that it is not picked up as an actual tag here.

Consider a default height parameter

This is a wkhtmltoimage issue, however it could be workaround fixed here as well, since wkhtmltoimage has 1000 open issues and seems to make very little progress. I did file a report with them, but I don't expect much.

wkhtmltoimage 'http://de.wikipedia.org/wiki/Geschichte_Italiens' wiki.jpg

does not terminate, and gets stuck with 100% CPU load

Setting a height fixes the issue:

wkhtmltoimage --height 1000 'http://de.wikipedia.org/wiki/Geschichte_Italiens' wiki.jpg

Consider a default height, that would prevent this bug from escalating, possibly in production mode.

Problems All Around

─▪ rvm use 1.9.2
Using /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180

─▪ gem install imgkit
******************************************************************

Now install wkhtmltoimage binaries:
Global: sudo `which imgkit` --install-wkhtmltoimage
or inside RVM folder: export TO=`which imgkit | sed 's:/imgkit:/wkhtmltoimage:'` && imgkit --install-wkhtmltoimage
(run imgkit --help to see more options)

******************************************************************
Successfully installed imgkit-1.3.1
1 gem installed

─▪ sudo `which imgkit` --install-wkhtmltoimage
Password:
/Users/krainboltgreene/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems.rb:900:in `report_activate_error': Could not find RubyGem imgkit (>= 0) (Gem::LoadError)
  from /Users/krainboltgreene/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems.rb:248:in `activate'
  from /Users/krainboltgreene/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems.rb:1276:in `gem'
  from /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/bin/imgkit:18:in `<main>'


─▪ cd ~/.rvm/

─▪ export TO=`which imgkit | sed 's:/imgkit:/wkhtmltoimage:'` && imgkit --install-wkhtmltoimage
rm: /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/bin/wkhtmltoimage: No such file or directory
/Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/gems/imgkit-1.3.1/bin/imgkit:32:in `download_wkhtmltoimage': File not found.. (RuntimeError)
  from /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/gems/imgkit-1.3.1/bin/imgkit:75:in `block (3 levels) in <top (required)>'
  from /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/gems/imgkit-1.3.1/bin/imgkit:90:in `call'
  from /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/gems/imgkit-1.3.1/bin/imgkit:90:in `<top (required)>'
  from /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/bin/imgkit:19:in `load'
  from /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/bin/imgkit:19:in `<main>'

─▪ brew install wkhtmltoimage
Error: No available formula for wkhtmltoimage

─▪ # So then I downloaded it from the Code Project.

─▪ # And then I unzipped it.

─▪ mv ~/Downloads/wkhtmltoimage /usr/local/bin

─▪ imgkit --help
IMGKit

Options are:
        --use-bzip                   Force bzip download for Ubuntu because lzcat is broken
        --install-wkhtmltoimage      Install wkhtmltoimage binaries (TO=/usr/local/bin ARCHITECTURE=i386)
        --version                    Show Version.
    -h, --help                       Show this.


─▪ imgkit --version
/Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/gems/imgkit-1.3.1/bin/imgkit:83:in `read': No such file or directory - /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/gems/imgkit-1.3.1/VERSION (Errno::ENOENT)
  from /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/gems/imgkit-1.3.1/bin/imgkit:83:in `block (3 levels) in <top (required)>'
  from /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/gems/imgkit-1.3.1/bin/imgkit:90:in `call'
  from /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/gems/imgkit-1.3.1/bin/imgkit:90:in `<top (required)>'
  from /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/bin/imgkit:19:in `load'
  from /Users/krainboltgreene/.rvm/gems/ruby-1.9.2-p180/bin/imgkit:19:in `<main>'

Providing image size

Is there any feature that would allow IMGKit to receive the desired dimensions of the exported image?

I have an HTML page which is based on just a container with defined width and height, and I just care about the contents of that container for the image.

Is there any way I can specify viewport width/height to IMGKit, so that just that part of the HTML gets exported to PNG?

Can't install wkhtmltoimage on OSX

I'm running into this error when trying to install wkhtmltoimage per the directions, both inside rvm and outside:

$rvmsudo imgkit --install-wkhtmltoimage
Password:
/Users/dave/.rvm/gems/ruby-1.9.3-p194@spacejunk/gems/imgkit-1.3.6/bin/imgkit:12: Use RbConfig instead of obsolete and deprecated Config.
/Users/dave/.rvm/gems/ruby-1.9.3-p194@spacejunk/gems/imgkit-1.3.6/bin/imgkit:79:in block (3 levels) in <top (required)>': undefined method+' for nil:NilClass (NoMethodError)
from /Users/dave/.rvm/gems/ruby-1.9.3-p194@spacejunk/gems/imgkit-1.3.6/bin/imgkit:98:in call' from /Users/dave/.rvm/gems/ruby-1.9.3-p194@spacejunk/gems/imgkit-1.3.6/bin/imgkit:98:in<top (required)>'
from /Users/dave/.rvm/gems/ruby-1.9.3-p194@spacejunk/bin/imgkit:19:in load' from /Users/dave/.rvm/gems/ruby-1.9.3-p194@spacejunk/bin/imgkit:19:in

'

Passing options with no arguments

I'm trying to pass in some of the available options to wkhtmltoimage - namely --enable-plugins which doesn't take any extra parameters.

However every permutation I've tried to pass it in with, using the option hash, has failed:

irb(main):016:0> kit = IMGKit.new('http://www.youtube.com/watch?v=9bZkp7q19f0', :'enable-plugins' => '')

Or...

irb(main):018:0> kit = IMGKit.new('http://www.youtube.com/watch?v=9bZkp7q19f0', :enableplugins => '')

This fails silently when followed by:

irb(main):021:0> file = kit.to_file('/Users/ashleyconnor/gangnam.jpg')

Writes out a 5-byte file.

The "tail" of the image gets chopped away

When generating image from the html below it cuts away the bottom part of the image. Giving the same html directly to the wkhtmltoimage (0.11.0 rc1) with "wkhtmltoimage test.html result.png" produces a complete image.

The commands I used with IMGKit.
htmlfile = File.read('test.html')
kit = IMGKit.new(htmlfile)
kit.to_file('result.png')

I just noticed that when I don't give any height option to the IMGKit.new() it sets the height to default value of 1000 pixels. It must be this what cuts the bottom of the image away. Then I tried to set the height to nil by "kit = IMGKit.new(htmlfile, height: nil)" and after that the generated image was complete.

I'll still post this issue and mark it as closed right away.

imgkit #to_img modifies input

I experience strange behavior when using imgkit and giving html through an object. It seems that it modifies the html string object which IMHO should not be intended. The following method is inside a rails activerecord model.

def create_preview
        IMGKit.configure do |config|
            config.default_format = :jpg
        end

        css = Tempfile.new 'css'
        css << self.raw_css
        css.close

        kit = IMGKit.new self.raw_html, :quality => 90
        kit.stylesheets << css.path


        img = Tempfile.new 'img'

        # self.raw_html untouched
        img << kit.to_img(:jpg).force_encoding('UTF-8') 
        #self.raw_html changed

        img.flush
        css.delete

        self.preview = img
    end

After img << kit.to_img(:jpg).force_encoding('UTF-8'), self.raw_html is prepended with a <style>-tag containing the contents of the css.

Have I misunderstood something or is this really an imgkit issue?

Not getting the background

Hello,

I think that IMGKit is not waiting for the complete loading of the page, because it's transforming it to image without the background. Can you guys confirm that? Is there any option that I can set to fix this?

Thanks,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.