Prawnで日本語文書文書のPDFを表示

Prawnを使ってモデルから取得した日本語データをPDFとして表示する手順をまとめました。   下記サイトのサンプルコードをベースに作成しました。 http://www.sitepoint.com/pdf-generation-rails/ 1)日本語のフォントを入手して配置   下記サイトから入手し、vendor/fonts/ipam.ttfに配置しました。 http://ossipedia.ipa.go.jp/ipafont/index.html   2)ヘッダー画像をapp/assets/images/header.jpgにアップロード   3)PDFを生成するコードをapp/pdfsディレクトリ内に定義   上記サイトのサンプルコードをベースに日本語フォントの設定を追加しました。   ・jp_fontの定義 ・table_content内の下記コードを削除 row(0).font_style = :bold   $ vi app/pdfs/report_pdf.rb
class ReportPdf < Prawn::Document
  def initialize(trade_items)
    super()
    @trade_items = trade_items
    header
    text_content
    jp_font
    table_content
  end

  def jp_font
    font "#{Rails.root}/vendor/fonts/ipam.ttf"
  end

  def header
    image "#{Rails.root}/app/assets/images/header.jpg", width: 530, height: 150
  end
 
  def text_content
    y_position = cursor - 50
    bounding_box([0, y_position], :width => 270, :height => 300) do
      text "Lorem ipsum", size: 15, style: :bold
      text "Lorem ・・."
    end
    bounding_box([300, y_position], :width => 270, :height => 300) do
      text "Duis vel", size: 15, style: :bold
      text "Duis vel ・・"
    end
  end
 
  def table_content
    table trade_item_rows do
      self.header = true
      self.row_colors = ['DDDDDD', 'FFFFFF']
      self.column_widths = [40, 300, 200]
    end
  end
 
  def trade_item_rows
    [['#', 'Name']] +
      @trade_items.map do |trade_item|
      [trade_item.id, trade_item.trade_item_name]
    end
  end
end
  4)コントローラのindexアクションを定義   上記3)で定義したReportPdfを実行します。
  def index
    @trade_items = TradeItem.all
    respond_to do |format|
      format.html
      format.pdf do
        pdf = ReportPdf.new(@trade_items)
        send_data pdf.render, filename: 'report.pdf', type: 'application/pdf'
      end
    end
  end
  5)動作確認   http://localhost:3000/trade_items.pdfをブラウザに入力すると”report.pdf”というファイルがダウンロードされます。 ヘッダー画像、サンプルテキスト、モデルから取得した日本語データが表示出来ていることが確認出来ました。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です