ruby-on-rails – 如何让Rails为PDFKit呈现PDF特定的HTML?
我正在使用PDFKit中间件来呈现PDF.这是它的作用:
>检查传入的应用程序请求.如果它们用于PDF,请从应用程序中隐藏该事实,但准备修改响应. 一般来说,我想要那种行为.但我有一个案例,我实际上需要我的应用程序根据请求PDF的事实呈现不同的内容. PDFKit为我提供了一个标记来检测它是否计划呈现我的响应:它将env [“Rack-Middleware-PDFKit”]设置为true. 但我需要告诉Rails,基于该标志,我希望它呈现show.pdf.haml.我怎样才能做到这一点? 解决方法
设置request.format和响应头
弄清楚了.根据the Rails source,request.format =’pdf’将手动将响应格式设置为PDF.这意味着Rails将渲染,例如show.pdf.haml. 但是,现在PDFKit不会将响应转换为实际的PDF,因为当我们实际上只生成HTML时,Content-Type标题表明它已经是PDF.所以我们还需要覆盖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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |