带有 PDFKit 和 Rails 的 ERB 模板的 PDF

PDF from ERB template with PDFKit and Rails

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

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

render_to_string(*args, &block)

Raw rendering of a template to a string.

It is similar to render, except that it does not set the response_body and it should be guaranteed to always return a string.

render 不是 return 字符串,它设置响应的 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 用于创建有关文件下载的通知。但首先要考虑它是否真的需要它,因为它对用户来说非常烦人,因为浏览器通常会告诉你你下载了一个文件。