Rails4 wicked_pdfでPDF出力 ※windows未対応
wicked_pdfを使って、HTMLをもとにPDFを生成する手順のメモ。
まず、Gemfileに下記を追加する。
gem 'wkhtmltopdf-binary' gem 'wicked_pdf'
コマンドプロンプトでbundle installを実行する。
bundle insatall --path vendor\bundle
config/initializers/wicked_pdf.rbファイルを作成し、wkhtmltopdfのパスを記載する。
WickedPdf.config = { :exe_path => "#{Gem.loaded_specs['wkhtmltopdf-binary'].full_gem_path}/bin/wkhtmltopdf" }
informationsでPDF出力を行う場合、routes.rbに下記のように書く。
resources :informations, only: [:index] get 'informations/:user_id/information_sheet', :to => 'informations#pdf', :as => :informations_pdf
informationsコントローラにpdfを追加し、下記のように書く。
# pdf出力 def pdf respond_to do |format| format.html { redirect_to informations_pdf_path(:user_id => params[:user_id], :debug => true, :format => :pdf)} format.pdf do render :pdf => "information_sheet", # pdf will download as information_sheet.pdf :encoding => 'UTF-8', :layout => 'pdf.html.erb', # uses views/layouts/pdf.haml :show_as_html => params[:debug].present? # renders html version if you set debug=true in URL end end end
view/informationsにpdf.pdf.erbを追加し、表示したい内容を記載する。
<h1>インフォメーションシート</h1>
view/layoutsにpdf.html.erbを追加し、下記のようにheadに必要な情報を書き込み、bodyにyieldを設定する。
<!DOCTYPE html> <html> <head> <title>RailsProject</title> <%= wicked_pdf_stylesheet_link_tag "application" %> <%= wicked_pdf_javascript_include_tag "application" %> <%= wicked_pdf_stylesheet_link_tag "feedbacks" %> <%= wicked_pdf_stylesheet_link_tag "pdf" %> </head> <body> <%= yield %> </body> </html>
assets/stylesheetsにpdf.css.scssを追加し、スタイルを設定するとよい。
あとは、view/informationsのindex.html.erbにinformations_pdf_pathへのリンクを設定する。
※注意
windows環境では動作しない。
参考:
mileszs/wicked_pdf · GitHub
Generating PDFs using Wicked PDF in Ruby on Rails
RailsアプリでPDFを出力する (Heroku対応) - Qiita [キータ]
Rails4 gemのインストールパスを取得する - ayaketanのプログラミング勉強日記