gpt4 book ai didi

ruby-on-rails - 如何让 Rails 为 PDFKit 呈现特定于 PDF 的 HTML?

转载 作者:行者123 更新时间:2023-12-05 00:33:59 27 4
gpt4 key购买 nike

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

  • 检查对应用程序的传入请求。如果它们用于 PDF,请从应用程序中隐藏该事实,但准备修改响应。
  • 让应用呈现为 HTML
  • 在发送之前获取响应并将 HTML 转换为 PDF

  • 一般来说,我想要这种行为。但是我有一种情况,我实际上需要我的应用程序根据请求 PDF 的事实来呈现不同的内容。

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

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

    最佳答案

    设置 request.format 和响应头

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

    但是,现在 PDFKit 不会将响应转换为实际的 PDF,因为 Content-Type header 说它已经是 PDF,当我们实际上只生成 HTML 时。所以我们还需要覆盖 Rails 的响应头,以表明它仍然是 HTML。

    这个 Controller 方法处理它:

    # 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

    这意味着 Controller Action 看起来像:
    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

    关于ruby-on-rails - 如何让 Rails 为 PDFKit 呈现特定于 PDF 的 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11250313/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com