1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails × HexaPDF】でテーブル付きPDFを生成してみた!

Posted at

皆さん、こんにちは。

今回は「Ruby on Rails で HexaPDF を用いて PDF にテーブルを作成する方法」について紹介させていただきます。

Rails で PDF を生成したい場面、意外と多くありませんか?

  • 見積書・請求書をPDFで出力したい
  • ユーザー情報の一覧をPDFで印刷したい
  • テーブルを含んだ帳票をきれいに出力したい

そんなときに役立つのが HexaPDF です!

この記事では、HexaPDF を使って、Railsアプリ上でテーブル付きのPDFファイルを生成する方法を紹介します。

HexaPDFとは?

HexaPDF は、Rubyで書かれた純粋なPDF操作ライブラリです。以下のような特徴があります:

  • 外部ライブラリなしで完結
  • PDFファイルの読み書きが可能
  • 細かいレイアウト制御が可能
  • テキスト、画像、図形の描画も自由自在

ただし注意点として、ネイティブな「テーブル機能」は提供されていないため、自分でレイアウトを計算して描画する必要があります。

環境準備

まずは Gemfile に HexaPDF を追加します。

# Gemfile
gem 'hexapdf'
$ bundle install

実装:PDFにテーブルを描画する

コントローラでPDFを生成し、簡単なテーブルを描画してみましょう。

class PdfsController < ApplicationController
  def generate
    pdf = HexaPDF::Document.new
    canvas = pdf.pages.add.canvas

    # テーブルのヘッダーと行データ
    headers = ['名前', '年齢', '職業']
    rows = [
      ['田中 太郎', '30', 'エンジニア'],
      ['山田 花子', '25', 'デザイナー'],
      ['佐藤 次郎', '28', 'マーケター']
    ]

    draw_table(canvas, headers, rows, x: 50, y: 700)

    send_data pdf.write, filename: 'sample_table.pdf', type: 'application/pdf'
  end

  private

  def draw_table(canvas, headers, rows, x:, y:)
    col_widths = [150, 100, 150]
    row_height = 30

    table_data = [headers] + rows
    table_data.each_with_index do |row, row_index|
      row.each_with_index do |cell, col_index|
        x0 = x + col_widths[0...col_index].sum
        y0 = y - row_index * row_height

        # セル枠を描画
        canvas.rectangle(x0, y0 - row_height, col_widths[col_index], row_height).stroke
        # セル内テキストを描画
        canvas.text(cell, at: [x0 + 5, y0 - 10])
      end
    end
  end
end

応用のアイデア

HexaPDFは非常に柔軟なので、以下のような応用も可能です:

  • セル内の文字揃え(中央、右寄せ)
  • 色付きのヘッダー行(背景塗りつぶし)
  • ページを跨いだ長いテーブルの分割処理
  • PDF内に画像やQRコードを追加

必要に応じて、canvas.fill_color, canvas.draw_text, canvas.image などを使い分けて対応できます。

HexaPDFを使えば、Railsでも自在にPDFを出力できます。帳票や一覧表のPDF化が必要な場面に、ぜひ取り入れてみてください!

今日は以上です。

ありがとうございました。
よろしくお願いいたします。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?