From aefa10f0b61cb060a69553d2ffc4fb7057c9fa18 Mon Sep 17 00:00:00 2001 From: Manuel Schnitzer Date: Fri, 12 Jun 2020 17:12:07 +0200 Subject: [PATCH] Add option `use_xvfb` to emulate an X server (#909) 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. --- generators/wicked_pdf/templates/wicked_pdf.rb | 6 ++++++ lib/wicked_pdf.rb | 14 +++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/generators/wicked_pdf/templates/wicked_pdf.rb b/generators/wicked_pdf/templates/wicked_pdf.rb index 824095dc..262cdcfa 100644 --- a/generators/wicked_pdf/templates/wicked_pdf.rb +++ b/generators/wicked_pdf/templates/wicked_pdf.rb @@ -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, } diff --git a/lib/wicked_pdf.rb b/lib/wicked_pdf.rb index 565d7950..9c3a6638 100644 --- a/lib/wicked_pdf.rb +++ b/lib/wicked_pdf.rb @@ -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 @@ -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 @@ -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