Skip to content

Instantly share code, notes, and snippets.

@clyfe
Created November 1, 2011 11:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save clyfe/1330326 to your computer and use it in GitHub Desktop.
Save clyfe/1330326 to your computer and use it in GitHub Desktop.
An optimized version of pdfkit, with a slightly more involved interface
# Usage
#
# OptimizedPDFKit.new(html_tempfile).to_pdf(pdf_tempfile_path)
#
class OptimizedPDFKit < PDFKit
def initialize(url_file_or_html, options = {})
@source = Source.new(url_file_or_html)
@stylesheets = []
@options = PDFKit.configuration.default_options.merge(options)
# Skip scan, might be a large file!
# @options.merge! find_options_in_meta(url_file_or_html) unless source.url?
@options = normalize_options(@options)
#raise NoExecutableError.new unless File.exists?(PDFKit.configuration.wkhtmltopdf)
end
def append_stylesheets
raise ImproperSourceError.new('Stylesheets may only be added to an HTML source') if stylesheets.any? && !@source.html?
# # Skip scan, might be a large file ..
# stylesheets.each do |stylesheet|
# if @source.to_s.match(/<\/head>/)
# @source.to_s.gsub!(/(<\/head>)/, style_tag_for(stylesheet)+'\1')
# else
# @source.to_s.insert(0, style_tag_for(stylesheet))
# end
# end
end
def to_pdf(path) # always require path to be given
# Skip this, we use tempfiles
# append_stylesheets
args = command(path)
invoke = args.join(' ')
result = IO.popen(invoke, "wb+") do |pdf|
# pdf.puts(@source.to_s) if @source.html? # always work with files in the optimized version
pdf.close_write
pdf.gets(nil)
end
raise "command failed: #{invoke}" unless $?.exitstatus == 0
path
end
def command(path = nil)
args = [executable]
args += @options.to_a.flatten.compact
args << '--quiet'
args << @source.instance_variable_get(:@source).path
args << (path || '-') # Write to file or stdout
args.map {|arg| %Q{"#{arg.gsub('"', '\"')}"}}
end
end
@NeQuissimus
Copy link

Thanks, not only did this optimize for me but also fixed pdfkit altogether. I kept having problems when creating presentations with showoff and taking some of your code fixed that for me :)

@clyfe
Copy link
Author

clyfe commented May 3, 2012

Thanks for letting me know, I knew that putting this here is a good idea! Your welcome!

@NeQuissimus
Copy link

I gisted my version here https://gist.github.com/2585848. For some reason, pdf.puts kept telling me invalid argument and the usual if result.to_s.strip.empty? was not happy either.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment