Skip to content

Instantly share code, notes, and snippets.

@mattetti
Created December 4, 2009 10:20
Show Gist options
  • Save mattetti/248955 to your computer and use it in GitHub Desktop.
Save mattetti/248955 to your computer and use it in GitHub Desktop.
#!/usr/local/bin/macruby
framework 'Cocoa'
framework 'WebKit'
class VirtualBrowser
attr_reader :view, :file_name
def initialize
NSApplication.sharedApplication.delegate = self
@view = WebView.alloc.initWithFrame([0, 0, 1024, 768])
window = NSWindow.alloc.initWithContentRect([0, 0, 1024, 768],
styleMask:NSBorderlessWindowMask,
backing:NSBackingStoreBuffered,
defer:false)
window.contentView = view
setup_view_prefs
view.frameLoadDelegate = self
@captured = false
end
def fetch(url, file_name='capture.pdf')
@file_name = file_name
page_url = NSURL.URLWithString(url)
view.mainFrame.loadRequest NSURLRequest.requestWithURL(page_url)
until @captured
NSRunLoop.currentRunLoop.runUntilDate NSDate.date
end
end
def setup_view_prefs
view.mediaStyle = 'screen'
view.customUserAgent = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; en-us) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10'
view.preferences.autosaves = false
view.preferences.shouldPrintBackgrounds = true
view.preferences.javaScriptCanOpenWindowsAutomatically = false
view.preferences.allowsAnimatedImages = false
view.mainFrame.frameView.allowsScrolling = false
end
def webView(view, didFinishLoadForFrame:frame)
save
end
def webView(view, didFailLoadWithError:error, forFrame:frame)
raise "Failed to take snapshot: #{error.localizedDescription}"
quit
end
def webView(view, didFailProvisionalLoadWithError:error, forFrame:frame)
raise "Failed to take snapshot: #{error.localizedDescription}"
quit
end
def quit
NSApplication.sharedApplication.terminate(nil)
end
def save
filepath = File.expand_path(@file_name)
puts "saving #{filepath}"
doc_view = setup_docview
doc_view.dataWithPDFInsideRect(doc_view.bounds).writeToFile(filepath, atomically:true)
doc_view.unlockFocus
@captured = true
`open #{filepath}`
end
def setup_docview
doc_view = view.mainFrame.frameView.documentView
doc_view.window.contentSize = [doc_view.bounds.size.width, doc_view.bounds.size.height]
doc_view.frame = view.bounds
doc_view.needsDisplay = true
doc_view.lockFocus
doc_view
end
end
url = ARGV.shift || "http://rubyinside.com/"
file_name = ARGV.shift || "rubyinside.pdf"
VirtualBrowser.new.fetch(url, file_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment