Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

An optimized version of pdfkit, with a slightly more involved interface

View optimized_pdfkit.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
# 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

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 :)

Owner
clyfe commented

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

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
Something went wrong with that request. Please try again.