simonlehmann
simonlehmann

Reputation: 882

Wicked PDF gem generated PDF views are being cached by browsers | Rails 5.2

I'm working on a project that has the functionality to export index views as PDF. This all works perfectly with the Wicked PDF gem, however, in production, the generated PDFs are cached by browsers and therefore can be out of date. Refreshing a PDF view does fetch latest data, but simply navigating to the PDF view only seems to use the browser-cached document. Is there a way to prevent the PDF view from being cached by browsers?

Controller

class InvoicesController < ApplicationController
  # GET /invoices
  def index
    @invoices = Invoice.all

    respond_to do |format|
      format.html
      format.pdf do
        render pdf: "Invoices_#{Time.current.strftime("%Y_%m_%d_at_%H_%M")}",
               template:       'invoices/index',
               show_as_html:   params.key?('debug'),
               title:          "Invoices_#{Time.current.strftime("%Y_%m_%d_at_%H_%M")}", # otherwise first page title is used
               orientation:    :landscape,
               margin:         { top:    15,                     # default 10 (mm)
                                 bottom: 15,
                                 left:   15,
                                 right:  45 },
               footer:         { left: "Extracted: #{Time.current.to_formatted_s(:date_at_time)}",
                                 right: "Page [page] of [topage]" }
      end
    end
  end
end

Any suggestions would be much appreciated.

Upvotes: 2

Views: 509

Answers (1)

Cryptex Technologies
Cryptex Technologies

Reputation: 1163

You can simply do by clearing the cache for that page

 class InvoicesController < ApplicationController
    before_action :set_cache_headers

      private

      def set_cache_headers
        response.headers["Cache-Control"] = "no-cache, no-store"
        response.headers["Pragma"] = "no-cache"
        response.headers["Expires"] = Time.now
      end
    end
end

Upvotes: 2

Related Questions