Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read HTML string and generated PDF file in chunks. #949

Merged
merged 1 commit into from
Oct 30, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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