32
27

More than 5 years have passed since last update.

wicked pdfで生成したpdfを自動ダウンロード

Last updated at Posted at 2015-05-14

忙しい人向けに

コントローラのRenderする箇所をこんな感じで書いてやれば良い

  pdf = render_to_string pdf: "#{params[:id]}.pdf", #PDFファイル名
                            template: "xxx/show.pdf.erb", #ビューファイル
                            encoding: "UTF-8",
                              layout: "pdf.html" #レイアウトファイル
          send_data(pdf) #ファイルのDL開始

詳しく

PDFを出力してくれるgemであるwicked_pdfは大変便利だ。
他のPrawnのように独自DSLを使うことなくErbやHamlでPDFを生成出来て非常に効率がよい

Railsのプロジェクトでwicked_pdfを使ってPDFを出力する場合は、普通にrenderしてしまうと
1. フォームボタン押下
2. PDFのページに遷移
3. PDFをブラウザ操作で「ファイル名前をつけて保存」などしてPCに保存

と言う流れになる、これはこれで中身を確認してからDLできるのでよいが

  1. フォームのボタン押下
  2. PDFダウンロード開始

と言うように一段階ステップを少なくしたい

wicked pdf って何とか、環境構築する場合はこちらが参考にしてください
RailsアプリでPDFを出力する (Heroku対応)

対象のコード

PDF表示版(通常)

xxx_controller.rb
  def show
    @some_model = SomeModel.new(params)

    respond_to do |format|
      format.html { redirect_to xxx_path(format: :pdf, debug: 1) }
      format.pdf do
          render     pdf: "#{params[:id]}",
                encoding: "UTF-8",
                  layout: "pdf.html",
            show_as_html: params[:debug].present? # デバッグ用 パラメタにdebug=1とあるとHTMLを開く
      end
    end
  end

PDFダウンロード版

xxx_controller.rb
  def show
    @some_model = SomeModel.new(params)

    respond_to do |format|
      format.html { redirect_to xxx_path(format: :pdf, debug: 1) }
      format.pdf do
        # デバッグ用 パラメタにdebug=1とあるとHTMLを開く
        if params[:debug].present?
          render     pdf: "#{params[:id]}",
                encoding: "UTF-8",
                  layout: "pdf.html",
            show_as_html: true
        # ここで、PDFを生成してクライアントに送る
        else
          pdf = render_to_string pdf: "#{params[:id]}.pdf", #PDFファイル名
                            template: "xxx/show.pdf.erb", #ビューファイル
                            encoding: "UTF-8",
                              layout: "pdf.html" #レイアウトファイル
          send_data(pdf) #ファイルのDL開始
        end
      end
    end
  end

refs:

32
27
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
32
27