设置 request.format 和响应标头
弄清楚了。根据Rails 源码,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