Skip to content

Commit

Permalink
Merge pull request #949 from cntral/read_content_in_chunks
Browse files Browse the repository at this point in the history
Read HTML string and generated PDF file in chunks.
  • Loading branch information
unixmonkey authored Oct 30, 2020
2 parents 60b6c40 + 7685921 commit 8c007a7
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions lib/wicked_pdf.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,22 @@ def pdf_from_string(string, options = {})
options.merge!(WickedPdf.config) { |_key, option, _config| option }
string_file = WickedPdfTempfile.new('wicked_pdf.html', options[:temp_path])
string_file.binmode
string_file.write(string)
string_io = StringIO.new(string)
until string_io.eof?
string_file.write(string_io.read(1024 * 1024)) # Read 1 MB chunks at a time to avoid `Errno::EINVAL` errors like `Invalid argument @ io_fread` and `Invalid argument @ io_write`.
end
string_file.close

pdf = pdf_from_html_file(string_file.path, options)
pdf
rescue Errno::EINVAL => e
Rails.logger.error '[wicked_pdf] The HTML file is too large! Try reducing the size or using the return_file option instead.'
raise e
ensure
string_file.close if string_file
end

def pdf_from_url(url, options = {})
def pdf_from_url(url, options = {}) # rubocop:disable Metrics/PerceivedComplexity
# merge in global config options
options.merge!(WickedPdf.config) { |_key, option, _config| option }
generated_pdf_file = WickedPdfTempfile.new('wicked_pdf_generated_file.pdf', options[:temp_path])
Expand All @@ -75,11 +81,19 @@ def pdf_from_url(url, options = {})
end
generated_pdf_file.rewind
generated_pdf_file.binmode
pdf = generated_pdf_file.read

pdf = ''
until generated_pdf_file.eof?
pdf << generated_pdf_file.read(1024 * 1024) # Read 1 MB chunks at a time to avoid `Errno::EINVAL` errors like `Invalid argument @ io_fread` and `Invalid argument @ io_write`.
end

raise "Error generating PDF\n Command Error: #{err}" if options[:raise_on_all_errors] && !err.empty?
raise "PDF could not be generated!\n Command Error: #{err}" if pdf && pdf.rstrip.empty?

pdf
rescue Errno::EINVAL => e
Rails.logger.error '[wicked_pdf] The PDF file is too large! Try reducing the size or using the return_file option instead.'
raise e
rescue StandardError => e
raise "Failed to execute:\n#{command}\nError: #{e}"
ensure
Expand Down

0 comments on commit 8c007a7

Please sign in to comment.