Skip to content

Commit

Permalink
Add option use_xvfb to emulate an X server (#909)
Browse files Browse the repository at this point in the history
On some systems an X server is not available, and thus a PDF generation
is not possible. This can be avoided when installing `xvfb-run` which
emulates an X server.

Enabling the `use_xvfb` option will wrap any `wkhtmltopdf` commands
around the command `xvfb-run`, in order to be able to create PDF's, even
without having an X server running.
  • Loading branch information
mschnitzer committed Jun 12, 2020
1 parent 23c13d7 commit aefa10f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
6 changes: 6 additions & 0 deletions generators/wicked_pdf/templates/wicked_pdf.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,10 @@
# Layout file to be used for all PDFs
# (but can be overridden in `render :pdf` calls)
# layout: 'pdf.html',

# Using wkhtmltopdf without an X server can be achieved by enabling the
# 'use_xvfb' flag. This will wrap all wkhtmltopdf commands around the
# 'xvfb-run' command, in order to simulate an X server.
#
# use_xvfb: true,
}
14 changes: 13 additions & 1 deletion lib/wicked_pdf.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def pdf_from_url(url, options = {})
options.merge!(WickedPdf.config) { |_key, option, _config| option }
generated_pdf_file = WickedPdfTempfile.new('wicked_pdf_generated_file.pdf', options[:temp_path])
command = [@exe_path]
command.unshift(find_xvfb_run_binary_path) if options[:use_xvfb]
command += parse_options(options)
command << url
command << generated_pdf_file.path.to_s
Expand Down Expand Up @@ -328,9 +329,13 @@ def parse_others(options)
r
end

def find_wkhtmltopdf_binary_path
def possible_binary_locations
possible_locations = (ENV['PATH'].split(':') + %w[/usr/bin /usr/local/bin]).uniq
possible_locations += %w[~/bin] if ENV.key?('HOME')
end

def find_wkhtmltopdf_binary_path
possible_locations = possible_binary_locations
exe_path ||= WickedPdf.config[:exe_path] unless WickedPdf.config.empty?
exe_path ||= begin
detected_path = (defined?(Bundler) ? Bundler.which('wkhtmltopdf') : `which wkhtmltopdf`).chomp
Expand All @@ -341,4 +346,11 @@ def find_wkhtmltopdf_binary_path
exe_path ||= possible_locations.map { |l| File.expand_path("#{l}/#{EXE_NAME}") }.find { |location| File.exist?(location) }
exe_path || ''
end

def find_xvfb_run_binary_path
possible_locations = possible_binary_locations
path = possible_locations.map { |l| File.expand_path("#{l}/xvfb-run") }.find { |location| File.exist?(location) }
raise StandardError.new('Could not find binary xvfb-run on the system.') unless path
path
end
end

0 comments on commit aefa10f

Please sign in to comment.