Class: WeasyPDF::Renderer
- Inherits:
-
Object
- Object
- WeasyPDF::Renderer
- Defined in:
- lib/weasy_pdf/renderer.rb
Constant Summary collapse
- WEASYPRINT_OPTIONS =
WeasyPrint-relevant options that the renderer reads. Any other keys in the options hash are silently ignored —this allows wkhtmltopdf options to be passed without error during migration.
%i[ page_size page_height page_width orientation margin margin_top margin_bottom margin_left margin_right encoding zoom media_type base_url stylesheets header footer save_to_file save_only ].freeze
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ Renderer
constructor
A new instance of Renderer.
- #pdf_from_html_file(filepath, options = {}) ⇒ Object
- #pdf_from_string(html_string, options = {}) ⇒ Object
- #pdf_from_url(url, options = {}) ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ Renderer
Returns a new instance of Renderer.
21 22 23 24 25 26 27 28 29 |
# File 'lib/weasy_pdf/renderer.rb', line 21 def initialize( = {}) merged = WeasyPDF.configuration..merge() # :wkhtmltopdf was WickedPdf's per-instance binary override — accept it as exe_path # so apps that pass it during migration don't need to change that option key. @binary = merged.delete(:wkhtmltopdf) || WeasyPDF.configuration.exe_path @timeout = merged.delete(:timeout) || WeasyPDF.configuration.timeout @options = merged.slice(*WEASYPRINT_OPTIONS) validate_binary! end |
Instance Method Details
#pdf_from_html_file(filepath, options = {}) ⇒ Object
55 56 57 58 59 |
# File 'lib/weasy_pdf/renderer.rb', line 55 def pdf_from_html_file(filepath, = {}) raise ArgumentError, "File not found: #{filepath}" unless File.exist?(filepath) pdf_from_string(File.read(filepath.to_s, encoding: "utf-8"), ) end |
#pdf_from_string(html_string, options = {}) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/weasy_pdf/renderer.rb', line 31 def pdf_from_string(html_string, = {}) opts = @options.merge() html = inject_page_css(html_string, opts) FileUtils.mkdir_p(WeasyPDF.configuration.temp_path) input = write_temp_html(html) output = temp_pdf_path begin run!(input, output, opts) result = File.binread(output) if opts[:save_to_file] FileUtils.mkdir_p(File.dirname(opts[:save_to_file].to_s)) File.binwrite(opts[:save_to_file].to_s, result) return nil if opts[:save_only] end result ensure FileUtils.rm_f([input, output]) end end |
#pdf_from_url(url, options = {}) ⇒ Object
61 62 63 64 65 66 67 |
# File 'lib/weasy_pdf/renderer.rb', line 61 def pdf_from_url(url, = {}) response = Net::HTTP.get_response(URI.parse(url)) raise WeasyPDF::Error, "HTTP #{response.code} fetching #{url}" \ unless response.is_a?(Net::HTTPSuccess) pdf_from_string(response.body, ) end |