How to take screenshot of a website with Rails 3.1? -- without using a service
Asked Answered
U

4

13

Almost every answer I've found references using some existing service. Is there a way to do this using Rails 3.1 programmatically? This was dead easy to do with PHP (there are prebuilt libraries in PHP that do this).

What I'm looking to do, given a URL, is:

  1. Take a screenshot of the website

  2. Crop it (only take the top left most 100x100 pixels

PS. Here is my environment: Rails 3.1, Ruby 1.9.2

Note: The solution would probably need to follow any redirections on the URL as well.

Updates:

Unbeknown answered 21/11, 2011 at 21:3 Comment(0)
Y
8

There is a Rails gem for this task.

 gem install selenium-webdriver

Simple use case:

require 'selenium-webdriver'
 width = 1024
 height = 728
 driver = Selenium::WebDriver.for :firefox
 driver.navigate.to 'http://domain.com'
 driver.execute_script %Q{
   window.resizeTo(#{width}, #{height});
 }
 driver.save_screenshot('/tmp/screenshot.png')
 driver.quit
Yokoyama answered 5/12, 2012 at 12:6 Comment(3)
Clever solution, though I think it needs to be installed on a client with those browsers installed as I had trouble server side doing this.Mcbee
Note that execute_script part should be replaced with driver.manage.window.resize_to(width,height)Typewriter
This works thx! But how can I do to execute same script on my linux server (without browser)?Britska
H
4

This might help: https://github.com/csquared/IMGKit

Harilda answered 21/11, 2011 at 22:0 Comment(2)
It's dependent on wkhtmltoimage which is not available for many platforms (including Mac)Unbeknown
wkhtmltoimage is available on Mac.Glavin
W
2

You could use wkhtmltoimage to load up the webpage and save it as an image, then imagemagick, (or one of the ruby wrappers for it) to crop it.

wkhtmltoimage www.google.com output.jpg
convert -crop 100x100+0+100 output.jpg cropped.jpg

There isn't a prebuilt wkhtmltoimage binary for OSX though, so perhaps you may want to use wkhtmltopdf instead and then imagemagick to convert to an image.

wkthmltopdf www.google.com output.pdf
convert -crop 100x100+0+100 output.pdf cropped.jpg
Wristlet answered 21/11, 2011 at 22:11 Comment(3)
The rendering of wkthmltopdf appears to bad for most sites :( Otherwise this would have been the way to go.Unbeknown
@Unbeknown I've never had a problem with it. Maybe you don't have enough fonts or a QT-enabled build.Wristlet
I'm going to try this again on mac and see if I'm missing any fonts, etc. Thanks!Unbeknown
U
2

A simple, but Mac only, solution seems to be http://www.paulhammond.org/webkit2png/

Just chmod -x that script and use as python webkit2png http://www.google.com/ and it creates 3 files:

  1. Full screenshot
  2. Thumbnail of the top most portion of site
  3. Thumbnail of the full screenshot
Unbeknown answered 21/11, 2011 at 22:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.