Skip to content

Instantly share code, notes, and snippets.

@robwilliams
Last active October 16, 2015 22:19
Show Gist options
  • Save robwilliams/dc34f1327fc1cf28d018 to your computer and use it in GitHub Desktop.
Save robwilliams/dc34f1327fc1cf28d018 to your computer and use it in GitHub Desktop.
Generate PDF from url

https://raw.githubusercontent.com/ariya/phantomjs/master/examples/rasterize.js

phantomjs rasterize.js http://www.smashingmagazine.com/2013/11/guidelines-navigation-categories-ecommerce-study test.pdf A4

require 'open3'

class PdfFromUrl
  def initialize(url, path)
    @url = url
    @path = path
  end

  def generate
    Open3.popen3(command) do |stdin, stdout, stderr, wait_thread|
      exit_status = wait_thread.value

      output = stdout.read + stderr.read

      if exit_status.success?
        File.open(path)
      else
        fail "'#{command}' failed"
      end
    end
  end

  private
  attr_reader :url, :path

  def command
    "phantomjs rasterize.js #{url} #{path} A4"
  end
end

p PdfFromUrl.new('http://www.google.co.uk', 'file.pdf').generate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment