Ruby wrapper for wkhtmltopdf to render PDF from HTML
MIT License
This gem is a wrapper for a popular wkhtmltopdf
library to generate PDF files from HTML.
Add this line to your application's Gemfile and then run bundle install
:
gem 'wkhtmltopdf_runner'
You also need to have installed wkhtmltopdf
. Easy way to do that is to add binary files to your Gemfile.
gem 'wkhtmltopdf-binary' # or 'wkhtmltopdf-binary-edge'
If you have custom path for wkhtmltopdf
please see Configuration
Use in a block which has File argument that will be returned after PDF generation as a TempFile.
These examples show how to attach a file to a user with ActiveStorage::Attach. You can render PDF from HTML string:
string = '<h1>Hello user</h1>'
WkhtmltopdfRunner.pdf_from_string(string) do |file|
user.document.attach(io: file, file_name: 'document.pdf')
end
You can render PDF from HTML file:
File.open('index.html') do |html_file|
WkhtmltopdfRunner.pdf_from_file(html_file) do |file|
user.document.attach(io: file, file_name: 'document.pdf')
end
end
You can render PDF from URL:
WkhtmltopdfRunner.pdf_from_url('https://github.com') do |file|
user.document.attach(io: file, file_name: 'document.pdf')
end
You can send the resultant file as a download.
WkhtmltopdfRunner.pdf_from_url('https://github.com') do |file|
send_file file, { filename: 'document.pdf' }
end
You can also just save it to a file.
WkhtmltopdfRunner.pdf_from_url('https://github.com') do |file|
doc = File.open('document.pdf', 'w')
doc.write(file.read)
doc.close
end
If you will not provide block, PDF string will be returned.
Warning: Be careful when using this method because all PDF content will be stored in Memory. Better to use block which will return file. See examples above.
pdf_string = WkhtmltopdfRunner.pdf_from_url('https://github.com')
If you're using Rails, create file in config/initializers/wkhtmltopdf_runner.rb
WkhtmltopdfRunner.configure do |config|
config.debug = true # Default: false
config.logger = Logger.new('runner.log') # Default: STDOUT or Rails.logger in Rails
config.binary_path = '/path/to/wkhtmltopdf' # Default: will search automatically in PATH or Gemfile
end
Bug reports and pull requests are welcome on GitHub at https://github.com/jpalumickas/wkhtmltopdf_runner. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
Everyone interacting in the WkhtmltopdfRunner project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.
The gem is available as open source under the terms of the MIT License.