来自ERB模板的PDF与PDFKit和Rails

时间:2017-03-10 11:45:12

标签: ruby-on-rails ruby pdfkit

在我的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

我还没有找到这个问题的答案,非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

  

render_to_string(*args, &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用于创建有关文件下载的通知。但首先要考虑它是否真的需要用户,因为浏览器通常会告诉你,无论如何都要下载文件。