wicked_pdf とは何か?
HTMLをPDFに変換しダウンロードまで実現することのできるgemです。
Wicked PDFはRubyバージョン2.2〜2.6、Rails4から6.1で動作することが確認されているみたいです。
手順1 wicked_pdfのgemをインストールする
wicked_pdfをwkhtmltopdfというHTMLをPDFに変換するオープンソースのラッパーなので、wkhtmltopdfとそのgemのwkhtmltopdf-binaryもインストールする必要があります。
Gemfile
gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'
$ bundle install
手順2 Initializerを作成
wkhtmltopdf
の実行可能ファイルのパスがWebサーバー上にない場合は、initializerに記述する必要があります。
より詳しい情報はwkhtmltopdf
のホームページをご覧ください。
config/initializers/wicked_pdf.rb
# これを追記
WickedPdf.config = {
:exe_path => "#{Gem.loaded_specs['wkhtmltopdf-binary'].full_gem_path}/bin/wkhtmltopdf"
}
手順3 実際にwicked_pdfを使ってみる
routes.rb
Rails.application.routes.draw do
get 'resumes/show', to: 'resumes#show'
end
templateはファイルの拡張子まで指定しないと、テンプレートがないというエラーになるのでご注意を。
resumes_controller.rb
def show
respond_to do |format|
format.html
format.pdf do
render pdf: 'filename', # PDF名
template: 'resumes/pdf.html.haml' # viewを対象にする
end
end
end
app/views/layouts/pdf_template.html.haml
にはpdfにしたい内容を記載します。
app/views/layouts/pdf_template.html.haml
%html
%head
%meta{:charset => "utf-8"}
%meta{ name: 'viewport', content: 'width=device-width, initial-scale=1.0' }
%meta{ name: 'x-apple-disable-message-reformatting' }
%body
= yield
app/views/resumes/show.html.haml
%div{style: 'background: #fff;'}
%h1 履歴書
%table{:border => "1"}
%tr
%th{:width => "500", :height => "50", :align => "left"} ふりがな
%tr
%th{:width => "500", :height => "50", :align => "left"} 氏名
%tr
%th{:width => "200", :rowspan => "2", :height => "50", :align => "left"} 現住所