【问题标题】:PDF from ERB template with PDFKit and Rails使用 PDFKit 和 Rails 来自 ERB 模板的 PDF
【发布时间】:2017-07-31 18:06:12
【问题描述】:

在我的 Rails 应用程序中,我希望有一个特殊的路径来下载自定义 PDF。

此 PDF 应通过 PDFKit 从我的应用程序中的 ERB 模板生成。与其描述我想要实现的目标,不如粘贴一些不可执行但带有注释的代码:

class MyController < ApplicationController
  def download_my_list_as_pdf
    # The template uses the instance variables below
    @user_id = params[:user_id]
    @items = ['first_item', 'second_item']

    # This line describes what I'd like to do but behaves not like I want ;)
    # Render the ERB template and save the rendered html in a variable
    # I'd also use another layout
    rendered_html = render :download_my_list_as_pdf

    kit = PDFKit.new(rendered_html, page_size: 'A4')
    kit.to_pdf

    pdf_file_path = "#{Rails.root}/public/my_list.pdf"
    kit.to_file(pdf_file_path)

    send_file pdf_file_path, type: 'application/pdf'

    # This is the message I'd like to show at the end
    # But using 'render' more than once is not allowed
    render plain: 'Download complete'
  end
end

我还没有找到这个问题的答案,任何帮助将不胜感激!

【问题讨论】:

    标签: ruby-on-rails ruby pdfkit


    【解决方案1】:

    render_to_string(*args, &amp;block)

    将模板原始呈现为字符串。

    和render类似,只是不设置response_body 并且应该保证总是返回一个字符串。

    render 不返回设置响应的response_body 的字符串。

    class MyController < ApplicationController
      def download_my_list_as_pdf
        # The template uses the instance variables below
        @user_id = params[:user_id]
        @items = ['first_item', 'second_item']
    
        # This line describes what I'd like to do but behaves not like I want ;)
        # Render the ERB template and save the rendered html in a variable
        # I'd also use another layout
        rendered_html = render_string(:download_my_list_as_pdf)
    
        kit = PDFKit.new(rendered_html, page_size: 'A4')
        kit.to_pdf
    
        pdf_file_path = "#{Rails.root}/public/my_list.pdf"
        kit.to_file(pdf_file_path)
    
        send_file pdf_file_path, type: 'application/pdf'
      end
    end
    

    但是,如果您要发送文件,则也不能发送文本或 html。这不是 Rails 的限制,而是 HTTP 的工作方式。一个请求 - 一个响应。

    通常使用 javascript 来创建有关文件下载的通知。但首先考虑一下是否真的需要它,因为它对用户来说非常烦人,因为浏览器通常会告诉你无论如何你下载了一个文件。

    【讨论】:

    • 嘿@max,感谢您的回答和额外的解释!再次表明,当您 know what you are looking for 时,很容易找到东西;)现在就这样做了:rendered_html = render_to_string :download_my_list_as_pdf, layout: false
    猜你喜欢
    • 2014-03-11
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多