Wicked PDFを使ってPDFを生成してみました。日本語表示については調査中ですがとりあえず備忘として残しました。
1)インストール
$ vi Gemfile
gem ‘wkhtmltopdf-binary’
gem ‘wicked_pdf’
$ bundle install
Installing wicked_pdf (0.9.10)
2)PDF Mimeタイプを登録
$ vi config/initializers/mime_types.rb
Mime::Type.register “application/pdf”, :pdf
3)コントローラにPDFの設定
$ vi app/controllers/trade_items_controller.rb
def index
@trade_items = TradeItem.all
respond_to do |format|
format.html
format.pdf do
render :pdf => "report", :layout => 'pdf.html.erb'
end
end
end
4)レイアウトファイル作成
$ vi app/views/layouts/pdf.html.erb
<!DOCTYPE html> <html> <head> <title>RailsProject</title> <%= wicked_pdf_stylesheet_link_tag "pdf" %> <%= wicked_pdf_javascript_include_tag "pdf" %> </head> <body> <%= yield %> </body> </html>
5)ビューを作成
$ vi app/views/trade_items/index.pdf.erb
<h1>Rails Wicked PDF</h1>
<table>
<thead>
<tr>
<th>ID</th><th>名前</th>
</tr>
</thead>
<tbody>
<% @trade_items.each do |trade_item| %>
<tr>
<td><%= trade_item.id %></td>
<td><%= trade_item.trade_item_name %></td>
</tr>
<% end %>
</tbody>
</table>
6)動作確認
下記URLにアクセスします。
http://localhost:3000/trade_items.pdfをブラウザに入力して動作確認
※日本語表示について
下記設定を行いましたが、日本語の表示が出来ませんでした。調査中です。
①フォントを追加
$ ls vendor/fonts/ipam.ttf
vendor/fonts/ipam.ttf
②config/application.rbにアセットの設定
$ vi config/application.rb
config.assets.paths << Rails.root.join(‘vendor’, ‘fonts’)
③スタイルシートの設定
$ vi app/assets/stylesheets/pdf.css.scss
@font-face {
font-family: 'IPA明朝';
src: url('<%= asset_path "ipam.ttf" %>') format('truetype');
}