ERB (Ruby)
Ruby の標準テンプレートエンジン ERB を使用して HTML 文字列を生成し、それを pdfg の API に送信して PDF に変換する方法を説明します。
技術的な概要
- ERB テンプレートを作成
- テンプレートにデータを渡して HTML 文字列を生成
- 生成された HTML 文字列を pdfg の API に送信して PDF 化
サンプル
テンプレートの定義
<%# templates/invoice.html.erb %>
<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <div class="invoice">
      <h1>請求書</h1>
      <table>
        <thead>
          <tr>
            <th>品目</th>
            <th>金額</th>
          </tr>
        </thead>
        <tbody>
          <% items.each do |item| %>
          <tr>
            <td><%= item[:name] %></td>
            <td><%= item[:price] %>円</td>
          </tr>
          <% end %>
        </tbody>
      </table>
      <p class="total">合計: <%= total %>円</p>
    </div>
  </body>
</html>
テンプレートの使用と PDF 生成
# generate_pdf.rb
require 'erb'
require 'httparty'
# ERBテンプレートの読み込み
template = ERB.new(File.read('templates/invoice.html.erb'))
# データの準備
items = [
  { name: '商品A', price: 1000 },
  { name: '商品B', price: 2000 }
]
total = 3000
# バインディングオブジェクトの作成
class TemplateBinding
  def initialize(items, total)
    @items = items
    @total = total
  end
  def items
    @items
  end
  def total
    @total
  end
  def get_binding
    binding
  end
end
# HTML文字列の生成
html = template.result(TemplateBinding.new(items, total).get_binding)
# pdfgのAPIにリクエスト
response = HTTParty.post(
  'https://api.pdfg.net/v1',
  headers: {
    'Content-Type' => 'application/json',
    'Authorization' => 'Bearer YOUR_API_KEY'
  },
  body: {
    html: html,
    pdfOptions: {
      format: 'A4'
    }
  }.to_json
)
# PDFの保存
if response.success?
  File.binwrite('invoice.pdf', response.body)
end