【问题标题】:Convert a PDF view with Wicked_pdf to a file and saving it to S3将带有 Wicked_pdf 的 PDF 视图转换为文件并将其保存到 S3
【发布时间】:2017-11-07 22:31:57
【问题描述】:

我目前有一个带有特定控制器方法的模型来呈现 PDF 视图。

假设这个模型是photographer_quote 我在photographer_quote 控制器中有一个名为print_quote 的方法来完成这项工作。

代码如下:

      @quote= Photographer_quote.find(params[:id])
      respond_to do |format|
      format.pdf do
        render pdf: 'quote'+@quote.id.to_s
      end

一切都很好,当针对这个控制器方法的链接被操作时,它会动态创建 PDF 并在浏览器中呈现它。 (当然,我有所有格式的视图......)

不过,现在我想将此 PDF 创建放入队列 (Sidekiq) 并将其作为 PDF 文件保存到具有单个 PDF 回形针附件的另一个模型中(我们称之为 PDF_quotes)。

虽然我很难通过 Paperclip 将 PDF 保存在 S3 上。

Wicked pdf 提到了这一点:

# or from your controller, using views & templates and all wicked_pdf options as normal
pdf = render_to_string pdf: "some_file_name", template: "templates/pdf", encoding: "UTF-8"

# then save to a file
save_path = Rails.root.join('pdfs','filename.pdf')
File.open(save_path, 'wb') do |file|
  file << pdf
end

我必须首先在本地创建文件吗?以及如何使用名为quote 的回形针附件将文件写入模型PDF_quotes

【问题讨论】:

标签: ruby-on-rails paperclip ruby-on-rails-5 wicked-pdf


【解决方案1】:

也许这会让你朝着正确的方向前进,关于:

“我必须首先在本地创建文件吗?如何将文件写入模型 PDF_quotes 并带有名为 quote 的回形针附件”

您可以在内存中创建一个 WickedPdf,然后像这样直接通过管道传输到回形针模型。

模型 PDF_quote 具有标准回形针“has_attached_file :quote”

例如在控制器中你可以这样做:

        # Generate PDF
        pdf = WickedPdf.new.pdf_from_string(
          render_to_string('your-pdf-template-in-html.pdf') # This is a view
        )

        # Stream PDF from WickedPdf to Paperclip PDF_quote.quote
        # Content Type is automatically read by Paperclip (at least for application/pdf in my testing)
        pdf_quote = PDF_quote.new(
          # Other attributes here as well.....
          quote: StringIO.new(pdf) # Pipe pdf to quote
        )
        pdf_quote.quote_file_name = "your_quote_file_name.pdf"
        pdf_quote.save

您可以向 .pdf_from_string 添加更多选项,请参阅 Paperclip GitHub。布局、页脚、页眉等...

我希望这会有所帮助!

【讨论】:

  • PDF_quote 是一个多态操作系统,我不得不稍微调整一下,但你的答案是完美的。谢谢
猜你喜欢
  • 1970-01-01
  • 2018-02-04
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
  • 2017-07-11
  • 2013-03-02
  • 1970-01-01
相关资源
最近更新 更多