wicked_pdfを用いてpdfファイルを作成するためのメモ。逐一付け足していきたい。
gemを導入
Gemfileに以下のように記述。公式リファレンスによると、"wicked_pdf is a wrapper for wkhtmltopdf, you'll need to install that, too."とのことなので、二つのgemが必要になる。
Gemfile
gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'
設定ファイルの作成
ターミナル上で以下のコマンドを打ち込んで設定ファイルを作成。
$ rails generate wicked_pdf
configファイルの設定
configファイルを以下のように設定。公式リファレンスによると、"If your wkhtmltopdf executable is not on your webserver's path, you can configure it in an initializer:"とのことで、wkhtmltopdfに対してpathを通してあげて実行可能な状態にしてあげないといけない。
config/initializers/wicked_pdf.rb
WickedPdf.config = {
:exe_path => "#{Gem.loaded_specs['wkhtmltopdf-binary'].full_gem_path}/bin/wkhtmltopdf"
}
ルーティングの設定
以下のような感じでルーティングを設定。
get 'get_pdf', to: 'pdf#get_pdf', format: 'pdf'
コントローラーの設定
コントローラーの設定。
def get_pdf
respond_to do |format|
format.pdf do
render pdf: "pdf-success", # 作成されるファイルの名前を記入
template: 'path/to/your/template_file' # pdfをして出力したいファイルへのpath
encoding: 'UTF-8' # 文字コード指定
end
end
end
viewの記入
以下のように記入して"success"と書かれたpdfが表示されたら成功。
path/to/your/template_file
%h1 success
参考資料
公式リファレンスは強い。
https://github.com/mileszs/wicked_pdf