その他
    ホーム 技術発信 DoRuby Railsからデータをエディタで作成したPDFに出力する方法

    Railsからデータをエディタで作成したPDFに出力する方法

    この記事はアピリッツの技術ブログ「DoRuby」から移行した記事です。情報が古い可能性がありますのでご注意ください。

    「ThinReports Editor」と「ThinReports Generator」 があればエディタで作成した形に

    データを出力できるようになり、納品書等の帳票が簡単に作れます。

     動作環境

    Ruby 1.8.7,1.9.3

     1、「ThinReports Generator」をインストール

    まずはRailsから出力するための必要な「ThinReports Generator」をインストールします。

    $ gem install thinreports

    ※Ruby1.8.7の場合は、別途 json のインストールが必要

    $ gem install json

     2、「ThinReports Editor」 のインストール

    次にPDFのデザイン作成に必要な「ThinReports Editor」 をインストールします。

    下記のURLにアクセスして自分のOSにあったものをインストールしてください。

    http://www.thinreports.org/download/

    インストールするものは以上です。

    参考:http://osc.matsukei.net/projects/thinreports/wiki/Installation_Guide

     3、PDFのレイアウトを作成する

    先ほどインストールした「ThinReports Editor」をつかい.tlfファイルを作成します

    下記のURL先で使い方がわかると思います。

    http://osc.matsukei.net/projects/thinreports/wiki/Getting_Started

    .tlfファイルを作成し終わったらRailsの/public/の下にでも置いてください。

     4、PDFにデータを出力してダウンロードする

    このアクションが呼ばれればPDFをダウンロードできます。

    require ‘thinreports’

    ~~~~~~~~~~

    ~~~~~~~~~~

    def pdf_download

     #Reportオブジェクトの生成、先ほど作ったレイアウトの読み込み

     report = ThinReports::Report.new :layout => ”/public/pdf_layout”

     #新しいページを作る際にここが呼ばれます

     report.events.on :page_create do |e|

      e.page.item(:page_num).value(e.page.no) #現在のページ数入力

     end

     #PDFを生成するときにここが呼ばれます

     report.events.on :generate do |e|

      e.pages.each do |page|

       page.item(:page_total).value(e.report.page_count) #総ページ数入力

      end

     end

     #ページを作成し、データを入力していきます。

     report.start_new_page do |page|

      page.item(:name).value(‘名前’)

      #リストを作っていた場合はリストに入力していきます。

      for i in 0..10 #10行分

       page.list(:list_test).add_row do |row|

        row.item(:quantity).value(“数量#{i}”)

        row.item(:price).value(“値段#{i}”)

       end

      end

     end

     #PDF生成

     send_data report.generate, :filename => ”ファイル名.pdf”,

     :type => ’application/pdf’,

     :disposition => ’attachment’

    end

    記事を共有