LoginSignup
3
6

More than 3 years have passed since last update.

Railsで本番環境(EC2, AmazonLinux)でPDF出力ができない

Posted at

本番環境(EC2, AmazonLinux)でPDF出力ができない

wicked_pdfwkhtmltopdf-binaryというGemを使ってPDF出力機能を付けていますが、開発環境ではうまく行くのに本番環境では下記のエラーが発生。
Railsのバージョンは4.2です。

RuntimeError (Failed to execute:
["/var/www/~~~/shared/bundle/ruby/2.4.0/gems/wkhtmltopdf-binary-0.12.6.3/bin/wkhtmltopdf", "--encoding", "UTF-8", "--page-size", "A4", "file:////tmp/wicked_pdf20201007-11835-gppxfs.html", "/tmp/wicked_pdf_generated_file20201007-11835-j83wu8.pdf"]
Error: PDF could not be generated!
 Command Error: /var/www/~~~/shared/bundle/ruby/2.4.0/gems/wkhtmltopdf-binary-0.12.6.3/bin/wkhtmltopdf_centos_7_amd64: error while loading shared libraries: libpng15.so.15: cannot open shared object file: No such file or directory
):

libpng15.so.15というライブラリがない様ですが、同様のエラーをネットで調べて色々と試しましたが解決しませんでした。

Gemを変更し解決

2016年の記事ですが、下記が参考になりました。
https://qiita.com/s-mori/items/00aef46e6a10499f8254
https://qiita.com/yaboojp/items/526c9397070ca5d05256

wkhtmltopdf-binaryはAmazonLinuxに対応していない様で、
AmazonLinuxに対応しているwkhtmltopdf-binary-amlを使うことでうまくいきました。

修正前のGemfile

gem 'wicked_pdf'
gem 'wkhtmltopdf-binary-aml'

修正後のGemfile

gem 'wicked_pdf'
gem 'wkhtmltopdf-binary-aml', git: 'https://github.com/insphire/wkhtmltopdf-binary-aml'

修正前のwicked_pdf

config/initializers/wicked_pdf.rb
WickedPdf.config = {
  :exe_path => "#{Gem.loaded_specs['wkhtmltopdf-binary'].full_gem_path}/bin/wkhtmltopdf"
}

修正後のwicked_pdf

config/initializers/wicked_pdf.rb
WickedPdf.config = {
  :exe_path => "#{Gem.loaded_specs['wkhtmltopdf-binary-aml'].full_gem_path}/bin/wkhtmltopdf"
}

Bundlerのバージョンが変更されない様にして、bundle installしました。
$ bundle _1.16.1_ install

日本語表示に対応させる

本番環境にデプロイすると、日本語表示がされていませんでした。
なのでIPAフォントを本番サーバでインストールします。

cd /usr/share/fonts

$ yum install -y ipa-gothic-fonts ipa-mincho-fonts

フォントを変更したことでレイアウトが崩れてしまったので、CSSなどを整えて、領収書機能を完成させることができました。

開発環境でのエラー

AmazonLinux対応のGemに変更したことで、今度は開発環境でエラーが起こる様になってしまいました。

RuntimeError - PDF could not be generated!
 Command Error: /Users/~~~/vendor/bundle/ruby/2.4.0/bundler/gems/wkhtmltopdf-binary-aml-e5340ed88aa8/bin/wkhtmltopdf:15:in `exec': Bad CPU type in executable - /Users/~~~/vendor/bundle/ruby/2.4.0/bundler/gems/wkhtmltopdf-binary-aml-e5340ed88aa8/libexec/wkhtmltopdf-darwin-x86 (Errno::E086)

開発環境でも本番環境でもうまくやるには、wicked_pdf.rbif Rails.env.production?などを使ってかき分けたり、
Gemfileを以下の様にして環境別に切り替えればできます。

group :development do
 gem 'wkhtmltopdf-binary'
end
gem 'wkhtmltopdf-binary', group: :development
3
6
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
3
6