logo

ERB (Ruby)

This guide explains how to generate an HTML string using Ruby's standard ERB template engine and convert it to PDF by sending it to pdfg's API.

Technical Overview

  1. Create an ERB template
  2. Pass data to the template to generate an HTML string
  3. Send the generated HTML string to pdfg's API to convert it to PDF

Sample

Defining the Template

<%# templates/invoice.html.erb %>
<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <div class="invoice">
      <h1>Invoice</h1>
      <table>
        <thead>
          <tr>
            <th>Item</th>
            <th>Amount</th>
          </tr>
        </thead>
        <tbody>
          <% items.each do |item| %>
          <tr>
            <td><%= item[:name] %></td>
            <td><%= item[:price] %> USD</td>
          </tr>
          <% end %>
        </tbody>
      </table>
      <p class="total">Total: <%= total %> USD</p>
    </div>
  </body>
</html>

Using the Template and Generating PDF

# generate_pdf.rb
require 'erb'
require 'httparty'

# Load ERB template
template = ERB.new(File.read('templates/invoice.html.erb'))

# Prepare data
items = [
  { name: '商品A', price: 1000 },
  { name: '商品B', price: 2000 }
]
total = 3000

# Create a binding object
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

# Generate HTML string
html = template.result(TemplateBinding.new(items, total).get_binding)

# Request to pdfg's 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