Created
May 2, 2013 01:07
-
-
Save jch/5499527 to your computer and use it in GitHub Desktop.
some exploration about creating PDFs from a resque background job with PDFKit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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