13
10

More than 5 years have passed since last update.

[Rails5]wicked_pdfってなんぞ?

Last updated at Posted at 2019-01-08

はじめに

Railsの勉強としてgem周りを触ってみる企画です。
今回は・・・

wicked_pdf

を試してみようかと思います。

どういうgemなの?

簡単にいうとHTMLをPDFに変換してダウンロードする、を実現するgemです。

合わせてwkhtmltopdfというコマンドラインツールのgemも使います。
このwkhtmltopdfをRails使うために今回のwicked_pdfが必要になります。
(wicked_pdfはラッパーにあたるgemらしい。)

早速トライしてみましょう。

検証環境

以下の環境で実施しました。

[client]
・MacOS Mojave(10.14.2)
・Vagrant 2.2.2
・VBoxManage 6.0.0

[virtual]
・CentOS 7.6
・Rails 5.2.2
・ruby 2.3.1

ご参考までに。

wicked_pdf導入

1.gemのインストール

事前にRails勉強用に作成したプロジェクトで進めます。
各MVCは適当に掲示板アプリを想定してPostsコントローラーなどを生成済みです。
(index,show,editの空ページが見れる程度)

$ rails g model post
$ rails g controller posts index show edit

その前提のもと、Gemfileに以下を追記。

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

追記したらインストール。

$ bundle install

-----------
Fetching wicked_pdf 1.1.0
Installing wicked_pdf 1.1.0
Fetching wkhtmltopdf-binary 0.12.4
Installing wkhtmltopdf-binary 0.12.4
-----------
→無事に完了。

続けてイニシャライザを生成。

$ rails g wicked_pdf
    create  config/initializers/wicked_pdf.rb

2.wicked_pdfの設定をする

上記コマンドで生成されたファイルの中身を調整します。

wicked_pdf.rb
# WickedPDF Global Configuration
#
# Use this to set up shared configuration options for your entire application.
# Any of the configuration options shown here can also be applied to single
# models by passing arguments to the `render :pdf` call.
#
# To learn more, check out the README:
#
# https://github.com/mileszs/wicked_pdf/blob/master/README.md

WickedPdf.config = {
  # Path to the wkhtmltopdf executable: This usually isn't needed if using
  # one of the wkhtmltopdf-binary family of gems.
  # exe_path: '/usr/local/bin/wkhtmltopdf',
  #   or
  # exe_path: Gem.bin_path('wkhtmltopdf-binary', 'wkhtmltopdf')

  # これを追記
  :exe_path => "#{Gem.loaded_specs['wkhtmltopdf-binary'].full_gem_path}/bin/wkhtmltopdf"

  # Layout file to be used for all PDFs
  # (but can be overridden in `render :pdf` calls)
  # layout: 'pdf.html',
}

この設定の記述方法はこちらを参考にしました。

引用:
railsでwicked_pdfの使い方
by @hogehoge1234

また、gemのREADMEにも書いてありますが、
Railsのバージョンが古い場合は、mime_types.rb
以下の記述が必要になるようです。

mime_types.rb
Mime::Type.register "application/pdf", :pdf

今回は新しいバージョンのRailsのため、
特に追加しなくてもいけるのでスルー。

3.wicked_pdfを使ってみる

では早速wicked_pdfを使って実装してみます。

posts_controller.rb
def show
  # とりあえず愚直に
  respond_to do |format|
    format.html
    format.pdf do
      render pdf: "sample",   # PDF名
             template: "posts/show.html.erb" # viewを対象にする
    end
  end
end

4.動作確認

ではサーバーを立ち上げてページを見てみましょう。
アクセスURLとして、/posts/showあるいは/posts/show.htmlとすると、
これまで通り、通常のHTMLページが表示されました。

そして本題のposts/show.pdfにアクセスすると・・・
エラー!!!!!!!!!

RuntimeError (Failed to execute:
["/usr/local/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/wkhtmltopdf-binary-0.12.4/bin/wkhtmltopdf", "-q", "file:////tmp/wicked_pdf20190108-8274-1n8d1sj.html", "/tmp/wicked_pdf_generated_file20190108-8274-7au09y.pdf"]
Error: PDF could not be generated!
 Command Error: /usr/local/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/wkhtmltopdf-binary-0.12.4/bin/wkhtmltopdf_linux_amd64: error while loading shared libraries: libXrender.so.1: cannot open shared object file: No such file or directory
):

コマンドエラーの結果として生成失敗している。
libXrender.so.1が無い?

エラー解消

しょんなぁ・・・。
って感じで壁にぶつかったので、
Google先生にいろいろ聞きながら対応策を調べる。

調査した結果、今の仮想環境にライブラリが足りていない様子。
とりあえずlibXrenderを入れてみる。

$ yum -y install libXrender

上記をインストールした後、再度ページを表示したところ、
今度は"libfontconfig.so.1"が〜というエラー!
続けて追加追加追加ぁ!
(他にも同様にエラーが出たので一気にまとめて記載します)

$ yum -y install libfontconfig.so.1
$ yum -y install fontconfig
$ yum -y install libXext

そしてついに・・・

cap1.png

表示されたやったーーー!

所感

ドハマりしました。
gemだし、そこまで苦労せず触れるだろうと思ってたけど、
そんなことはなかった。ただの幻想でした。

けどどうにか、
本来やりたかったHTMLをPDFに変換するという機能は出来たので、
良かった良かった。

多分ここから先は、
日本語入れたり、出力時のレイアウト調整等、
いろいろ更に大変なことがあるとは思うけど、
まずはひと段落として一旦ここで区切ります。

2019/01/09 追記:
続き書きました。

おわりに

何かお気づきの点がありましたら、
ご指摘やアドバイス等頂けると大変助かります!

13
10
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
13
10