Skip to content
Create a gist now

Instantly share code, notes, and snippets.

An optimized version of pdfkit, with a slightly more involved interface
# Usage
class OptimizedPDFKit < PDFKit
def initialize(url_file_or_html, options = {})
@source =
@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 unless File.exists?(PDFKit.configuration.wkhtmltopdf)
def append_stylesheets
raise'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
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
raise "command failed: #{invoke}" unless $?.exitstatus == 0
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 {|arg| %Q{"#{arg.gsub('"', '\"')}"}}

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 commented May 3, 2012

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


I gisted my version here 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
Something went wrong with that request. Please try again.