mileszs / wicked_pdf

PDF generator (from HTML) plugin for Ruby on Rails
http://www.mileszs.com/wicked-pdf-plugin
MIT License
3.54k stars 645 forks source link

Using wicked_pdf in pure ruby project. #838

Open theasteve opened 5 years ago

theasteve commented 5 years ago

Issue description

Currently, I'm working on a pure ruby project in which I would like to convert HTML into PDF. I would like to make use of the wicked_pdf gem. But it seems that the initializer is created by running rails generate wicked_pdf which is a rails command. How can I go about using the gem without the need of Rails?

Expected or desired behavior

Using the wicked_pdf in a Ruby project. I'm also making use of pdftk so maybe downloading the binaries for gem 'wkhtmltopdf-binary into bin and accessing it that way.

System specifications

wicked_pdf (1.4.0) Ruby2.5.3p105 Mac OS Mojavee

unixmonkey commented 5 years ago

WickedPdf works well in non-Rails Ruby projects. The generator (rails generate3 wicked_pdf) only creates a file that you can put persistent configuration into. It isn't necessary to work. Some options to render are related to Rails functionality, but many are not, and are directly transformed into command flags for wkhtmltopdf.

Many examples of how to build your PDF can be found in the README under Super Advanced Usage, but the gist of it is that you can use the following top-level APIs

# Set global options used implicitly.
# These options could also just be passed every time to any of
# the `pdf_from_{string, html_file,url}` methods:
WickedPdf.config = {
  exe_path: '/path/to/your/wkhtmltopdf',
  quiet: true
}

# non-global options
options = {
  header: { right: '[page] of [topage]' },
  page_size: 'Letter'
}
wicked_pdf = WickedPdf.new

# Ways to make a PDF from different content sources
pdf = wicked_pdf.pdf_from_string('<h1>Hello There!</h1>', options)
pdf = wicked_pdf.pdf_from_html_file('/path/to/your/file.html', options)
pdf = wicked_pdf.pdf_from_url('https://github.com/mileszs/wicked_pdf', options)

# `pdf` is a string at this point, but you can save it to the disk
File.open('/path/to/output_file.pdf', 'wb') { |file| file << pdf }

Many of the render options are related to Rails functionality, and some options are only for older or newer versions of wkhtmltopdf, but there should be an option for nearly every native wkhtmltopdf option.

I hope this helps. Please let me know if you have any trouble or questions!