【问题标题】:How to Specify the Layout When Attaching a PDF to an Email Using Wicked PDF使用 Wicked PDF 将 PDF 附加到电子邮件时如何指定布局
【发布时间】:2014-12-05 04:02:20
【问题描述】:

当我尝试为要使用 Wicked PDF 附加到电子邮件的 pdf 指定布局时,我无法生成电子邮件。这是一个 Rails 4 应用程序。

当我使用以下代码时,应用程序成功发送了带有 pdf 附件的电子邮件,但没有所需的样式:

def invoice_created(invoice_id)
  @invoice = Invoice.find(invoice_id)
  @subscription = Subscription.find(@invoice.subscription_id)
  attachments['invoice.pdf'] = WickedPdf.new.pdf_from_string(
    render_to_string(:pdf => "invoice", :template => 'invoices/show.pdf.erb'))
  mail(to: 'you@example.com', subject: "Your Invoice is Ready")
end

但是当我添加布局时,什么都没有生成。

def invoice_created(invoice_id)
  @invoice = Invoice.find(invoice_id)
  @subscription = Subscription.find(@invoice.subscription_id)
  attachments['invoice.pdf'] = WickedPdf.new.pdf_from_string(
    render_to_string(:pdf => "invoice", 
                     :template => 'invoices/show.pdf.erb', 
                     :layout => 'pdf.html.erb'))
  mail(to: 'you@example.com', subject: "Your Invoice is Ready")
end

在我的控制器中,我在浏览器中显示 pdf,它正确使用了 pdf.html.erb 布局:

def show
  @invoice = current_account.invoices.find(params[:id])
  respond_to do |format|
    format.html
    format.pdf do
      render :pdf => 'file_name',
      :template => 'invoices/show.pdf.erb',
      :layout => 'pdf.html.erb'
    end
  end
end

我在开发日志中没有看到任何明显的错误,除了没有创建电子邮件文件。

我看到以下内容,因此它看起来像是看到了布局但不会显示它。

Rendered invoices/show.pdf.erb within layouts/pdf.html.erb (13.7ms)

会不会出现布局冲突的问题?

如果我尝试使用指定的布局生成几封电子邮件,然后从邮件程序中删除布局代码,重新启动服务器,请求新电子邮件,然后我之前请求的电子邮件将被发送。

我尝试添加

:show_as_html => params[:debug].present?

给邮件发送者看看它是否会有所帮助,但这也会导致电子邮件无法发送。

【问题讨论】:

  • 这很奇怪。特别是它在最后发送邮件的事情。 idk,没有正确关闭 io 流的东西?你可以用edgeguides.rubyonrails.org/…查看生成的邮件你想在github上提交一些演示代码吗?我们可以检查问题是否可以重现并向 rails 或 wicked_pdf 提交错误报告
  • 使用render_to_string github.com/mileszs/wicked_pdf#super-advanced-usage检查pdf是否可以保存到文件系统也很有趣
  • 感谢您将示例发布到 github。由于某种原因,我的配置中没有出现错误。我构建的基本应用程序提出了问题,并立即给出了解决方案。 github.com/stevejc/WickedPDF-Example

标签: ruby-on-rails ruby pdf actionmailer wicked-pdf


【解决方案1】:

问题代码在 pdf 布局中:

<%= csrf_meta_tags %>

不知道为什么我的应用没有收到任何错误消息。我已将我的应用程序设置为显示带有 gem 'better_errors' 的错误,但未显示任何错误。我设置了一个新应用程序只是为了玩 wicked_pdf,但没有将 better_errors 添加到 gem 文件中。

现在我收到以下错误消息:

undefined method `protect_against_forgery?'

layouts/pdf/html.erb 文件中删除此行后,应用程序会正确附加样式化的 pdf。

这是我用来找到解决方案的示例 wicked_pdf 示例的链接:https://github.com/stevejc/WickedPDF-Example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 2020-11-21
    • 2016-06-13
    • 1970-01-01
    • 2014-09-26
    相关资源
    最近更新 更多