3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【その1】wicked_pdfで履歴書を作成するまで

Last updated at Posted at 2020-09-17

wicked_pdf とは何か?

HTMLをPDFに変換しダウンロードまで実現することのできるgemです。
Wicked PDFはRubyバージョン2.2〜2.6、Rails4から6.1で動作することが確認されているみたいです。

手順1 wicked_pdfのgemをインストールする

wicked_pdfをwkhtmltopdfというHTMLをPDFに変換するオープンソースのラッパーなので、wkhtmltopdfとそのgemのwkhtmltopdf-binaryもインストールする必要があります。

Gemfile
gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'
$ bundle install

手順2 Initializerを作成

wkhtmltopdfの実行可能ファイルのパスがWebサーバー上にない場合は、initializerに記述する必要があります。
より詳しい情報はwkhtmltopdfホームページをご覧ください。

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

手順3 実際にwicked_pdfを使ってみる

routes.rb
Rails.application.routes.draw do
 get 'resumes/show', to: 'resumes#show'
end

templateはファイルの拡張子まで指定しないと、テンプレートがないというエラーになるのでご注意を。

resumes_controller.rb
 def show
   respond_to do |format|
     format.html
      format.pdf do
        render pdf: 'filename',   # PDF名
               template: 'resumes/pdf.html.haml' # viewを対象にする
      end
    end
  end

app/views/layouts/pdf_template.html.hamlにはpdfにしたい内容を記載します。

app/views/layouts/pdf_template.html.haml

%html
  %head
    %meta{:charset => "utf-8"}
    %meta{ name: 'viewport', content: 'width=device-width, initial-scale=1.0' }
    %meta{ name: 'x-apple-disable-message-reformatting' }
  %body
    = yield
app/views/resumes/show.html.haml

%div{style: 'background: #fff;'}
  %h1 履歴書
  %table{:border => "1"}
    %tr
      %th{:width => "500", :height => "50", :align => "left"} ふりがな
    %tr
      %th{:width => "500", :height => "50", :align => "left"} 氏名
    %tr
      %th{:width => "200", :rowspan => "2", :height => "50", :align => "left"} 現住所

スクリーンショット 2020-09-16 15.44.03.png

URLに .pdf をつけるとPDFが表示されるはずです。
スクリーンショット 2020-09-17 15.23.12.png

3
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?