首页 文章

如何让Rails为PDFKit呈现PDF特定的HTML?

提问于
浏览
4

我正在使用PDFKit中间件来呈现PDF . 这是它的作用:

  • 检查对应用程序的传入请求 . 如果它们用于PDF,请从应用程序中隐藏该事实,但准备修改响应 .

  • 让应用呈现为HTML

  • 在发送之前获取响应并将HTML转换为PDF

一般来说,我想要那种行为 . 但我有一个案例,我实际上需要我的应用程序根据请求PDF的事实呈现不同的内容 .

PDFKit为我提供了一个标记来检测它是否计划呈现我的响应:它将 env["Rack-Middleware-PDFKit"] 设置为true .

但我需要告诉Rails,基于该标志,我希望它呈现 show.pdf.haml . 我怎样才能做到这一点?

2 回答

  • 1

    设置request.format和响应头

    弄清楚了 . 根据the Rails sourcerequest.format = 'pdf' 将手动将响应格式设置为PDF . 这意味着Rails将呈现,例如 show.pdf.haml .

    但是,现在PDFKit不会将响应转换为实际的PDF,因为 Content-Type Headers 说's already PDF, when we'实际上只生成HTML . 所以我们还需要覆盖Rails ' response header to say that it'仍然是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
    
  • 5

    您也可以在没有中间件的情况下使用PDFKit .

相关问题