設置請求。格式和響應標頭
找出來。根據the Rails source,request.format = 'pdf'
將手動將響應格式設置爲PDF。這意味着Rails將渲染,例如,show.pdf.haml
。
但是,現在PDFKit不會將響應轉換爲實際PDF,因爲Content-Type
標題表示它已經是PDF,因爲實際上我們只生成HTML。所以我們還需要重寫Rails的響應頭,以表示它仍然是HTML。
該控制器的方法處理它:
# By default, when PDF format is requested, PDFKit's middleware asks the app
# to respond with HTML. If we actually need to generate different HTML based
# on the fact that a PDF was requested, this method reverts us back to the
# normal Rails `respond_to` for PDF.
def use_pdf_specific_template
return unless env['Rack-Middleware-PDFKit']
# Tell the controller that the request is for PDF so it
# will use a PDF-specific template
request.format = 'pdf'
# Tell PDFKit that the response is HTML so it will convert to PDF
response.headers['Content-Type'] = 'text/html'
end
這意味着控制器動作的樣子:
def show
@invoice = Finance::Invoice.get!(params[:id])
# Only call this if PDF responses should not use the same templates as HTML
use_pdf_specific_template
respond_to do |format|
format.html
format.pdf
end
end
對於2014年在家中的任何人,我發現這個現在是'request.env [「Rack-Middleware-PDFKit」]'並且它返回一個字符串,例如: ' 「真」'。 – pdobb