LoginSignup
72
75

More than 5 years have passed since last update.

Rails で Wicked PDF 使って PDF を出力してみた ( 日本語もバッチリ )

Last updated at Posted at 2015-02-17

はじめに

Rails で PDF を出力する方法を調べて実装した時のメモ。

「Rails PDF 出力」とかでググると、ThinReports とか引っかかってくるけど、
別途 テンプレートファイルの作成が、必要でかつ、それを作るための別ツールのインストールが必要など、
導入に手間がかかるなぁとおもったので、もっと手軽な Wicked PDF を使って実装してみた。

Wicked PDF は、HTML を変換して PDF として表示する方式のため、
いつも View を html で作っているやり方に、実装できる。
作成中のデバッグも、ブラウザで html を表示してできるので、かなりお手軽。

準備

Gem インストール

Gemfile に下記を追加して、bundle install する

Gemfile
# pdf export
gem 'wkhtmltopdf-binary'
gem 'wicked_pdf'

PDF 変換コマンドを設定

initializers に wicked_pdf.rb を追加

wicked_pdf.rb
WickedPdf.config = {
  :exe_path => "#{Gem.loaded_specs['wkhtmltopdf-binary'].full_gem_path}/bin/wkhtmltopdf"
}

pdf に変換するコマンドのパスを設定している

サンプルコード

下記のような controller 、view テンプレートを用意。
今回は pdf 出力用のテンプレートファイル pdf.html.haml を作成。
売上の一覧表を出力してみる

その前に、テンプレートファイルのタグの書き方が変わるので記載します。

タグ 標準 Wicked PDF サンプルソース (HAML)
CSS stylesheet_link_tag wicked_pdf_stylesheet_link_tag = wicked_pdf_stylesheet_link_tag 'filepath'
JS javascript_include_tag wicked_pdf_javascript_include_tag = wicked_pdf_javascript_include_tag 'filepath'
IMAGE image_tag wicked_pdf_image_tag = wicked_pdf_image_tag 'filepath'

ただし、html でのデバッグする際は、標準のタグにしておく必要がある。

controller

app/controllers/sales_controller.rb
class SalesController < ApplicationController

  def index
    @sales = Sale.all

    respond_to do |format|
      # .html でアクセスした際は、リダイレクト(show_as_html を true にするため、debug: 1 で)
      format.html { redirect_to :action => 'detail', :format => 'pdf', debug: 1 }
      format.pdf do
        render pdf: 'detail',                        # pdf ファイル名
               encording: 'UTF-8',                   # 日本語を使う場合には指定する
               layout: 'pdf.html',                   # レイアウトファイルの指定
               show_as_html: params[:debug].present? # debug するか?
      end
    end
  end
end

html で debug 可能なように記載
url に .html でアクセスすると、html でデバッグ出来る

view

app/views/layouts/pdf.html.haml
!!!
%html
  %head
    %meta{ 'http-equiv' => 'content', content: 'text/html; charset=utf-8' }
      = wicked_pdf_stylesheet_link_tag '//ajax.googleapis.com/ajax/libs/yui/3/build/cssreset/reset-min.css'
  %body
    = yield

とりあえずのリセット CSS 入り。

app/views/sales/index.pdf.haml
%table
  %tr
    %td sales_amount
    %td sales_tax
    %td sum
  - @sales.each do |sale|
    %tr
      %td ¥ #{number_with_delimiter(sale.sales_amount)}
      %td ¥ #{number_with_delimiter(sale.sales_tax)}
      %td ¥ #{number_with_delimiter(sale.sales_sum)}

@sales のレコード数分、テーブルの行が作成される。

日本語対応

日本語を表示したい場合は、別途日本語フォントをインストールが必要。
※ Linux に日本語が入っていないため

下記コマンドで IPA フォントをインストールできる。

$ yum install -y ipa-gothic-fonts
$ yum install -y ipa-mincho-fonts
72
75
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
72
75