概要

WickedPDF というライブラリを使って Rails で PDF を扱う方法を紹介します。

検証で使用した環境
Rails 6.1.4
Ruby 3.0.0

セットアップ

ライブラリのインストールから

# Gemfile
gem 'wicked_pdf'
gem "wkhtmltopdf-binary"

インストールしたらジェネレーターで設定ファイルを作成します。

rails generate wicked_pdf

必要であれば初期設定を変更します。

# config/initializers/wicked_pdf.rb
WickedPdf.config = {
  layout: "layout_pdf.html.erb"
}
# config/initializers/mime_types.rb
Mime::Type.register "application/pdf", :pdf

基本的な使い方

PDFをブラウザに表示させます。
ファイル名とビューファイルを指定します。

class ThingsController < ApplicationController
  def show
    respond_to do |format|
      format.html
      format.pdf do
        render pdf: "file_name", template: "things/show.html.erb"
      end
    end
  end
end
<%= link_to "PDF", thing_path(@thing, format: :pdf) %>

スタイリング

PDFファイルにCSSのスタイリングを適用させます。
PDF用のレイアウトファイルとCSSファイルを作成します。

# app/views/layouts/layout_pdf.html.erb
<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
    <%= wicked_pdf_stylesheet_link_tag "pdf" %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

メールに添付する

PDFファイルをメールに添付するにはActionMailerのattachmentsに格納します。

# app/mailers/user_mailer.rb
def welcome_email
  @user = params[:user]
  
  attachments['things.pdf'] = WickedPdf.new.pdf_from_string(
    render_to_string(template: 'things/show.html.erb', pdf: 'filename')
  )
  mail(to: @user.email, subject: '私の素敵なサイトへようこそ')
end

日本語を使えるようにする

PDFに日本語を表示させる場合はサーバーにフォントをインストールする必要があります。
以下ではIPAの日本語フォントをインストールしてユーザーのフォントに設定しています。

apt-get update && apt-get install wget unzip fontconfig
wget https://moji.or.jp/wp-content/ipafont/IPAexfont/IPAexfont00401.zip
mkdir -p /usr/share/fonts/japanese/TrueType
mv -i IPAexfont00401/*ttf /usr/share/fonts/japanese/TrueType/
fc-cache -fv