Skip to content

Instantly share code, notes, and snippets.

@jch
Created May 2, 2013 01:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jch/5499527 to your computer and use it in GitHub Desktop.
Save jch/5499527 to your computer and use it in GitHub Desktop.
some exploration about creating PDFs from a resque background job with PDFKit
class PDFDocument
include ActionDispatch::Integration::Runner # lets you grab assets. See #session
include Rails.application.routes.url_helpers
# quote or invoice or receipt
def initialize(document)
@document = document
end
def pdf
PDFKit.new(translate_paths(fetch_html))
end
def fetch_html
status_code = session.get invoice_order_path(@document)
if status_code == 200
doc = Nokogiri::HTML.parse(session.body)
# inject stylesheets inline, do something similar for images
stylesheets = doc.css('head link').map {|element|
href = element.attr('href')
if session.get(href) == 200
element.remove
element.after(session.body) # pseudo code, append the actual styles inline
end
}
doc.to_html
else
"TODO: non 200 status code"
end
end
# Internal
def app
@app ||= Rails.application
end
def session
@session ||= open_session
end
end
File.open("bar.pdf", "wb") {|f|
f.puts PDFDocument.new(Order.last).pdf.to_pdf
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment