Ruby on rails 是否将对虾PDF保存为回形针附件?

Ruby on rails 是否将对虾PDF保存为回形针附件?,ruby-on-rails,ruby-on-rails-3,paperclip,prawn,prawnto,Ruby On Rails,Ruby On Rails 3,Paperclip,Prawn,Prawnto,我使用Prawn和Prawnto向用户显示基于PDF的报告,但在某些情况下,我还希望将PDF保存为我的一个模型的附件。我所有的附件都用回形针。有人对此有什么建议吗 谢谢 如果您只需将该PDF的文件引用传递给曲别针,它应该可以工作 require 'prawn' pdf = Prawn::Document.new pdf.text("Prawn Rocks") pdf.render_file('/path/to/prawn.pdf') pdf_file = File.open('/path/to

我使用Prawn和Prawnto向用户显示基于PDF的报告,但在某些情况下,我还希望将PDF保存为我的一个模型的附件。我所有的附件都用回形针。有人对此有什么建议吗


谢谢

如果您只需将该PDF的文件引用传递给曲别针,它应该可以工作

require 'prawn'
pdf = Prawn::Document.new
pdf.text("Prawn Rocks")
pdf.render_file('/path/to/prawn.pdf')

pdf_file = File.open('/path/to/prawn.pdf')

# assuming your Paperclip association is named "pdf_attachment"
my_model.pdf_attachment = pdf_file

使用prawnto时,您需要评估.pdf.prawn模板中的变量。 第二步是模仿回形针的真实文件

  • 生成PDF:

    #find the prawwnto template you want
    template = File.read("#{RAILS_ROOT}/app/views/reports/your_report.pdf.prawn")
    
    pdf = Prawn::Document.new(:page_size => 'A4', :your_options => :etc)
    
    pdf.instance_eval do
      @report = find_report #put here, all local variables that the pdf template needs
      eval(template) #this evaluates the template with your variables
    end
    
    attachment = pdf.render
    
  • 使用回形针保存PDF:

    file = StringIO.new(attachment) #mimic a real upload file
    file.class.class_eval { attr_accessor :original_filename, :content_type } #add attr's that paperclip needs
    file.original_filename = "your_report.pdf"
    file.content_type = "application/pdf"
    
    
    #now just use the file object to save to the Paperclip association.
    
    
    # assuming your Paperclip association is named "pdf_report"
    @report_store.pdf_report = file
    @report_store.save!
    

  • 希望这能有所帮助。

    我将其转换为另一种方式:在模型中生成PDF并在控制器中渲染,从而使其在没有实例评估的情况下工作

    在模型中:

      def generate_pdf
        Prawn::Document.new(:page_size => 'A4', :top_margin => 0, :left_margin => 0) do |pdf|
            <your pdf code here>
            <copy paste from your template>
        end.render
      end
    
    或在控制器的浏览器窗口中渲染:

    send_data your_model.generate_pdf, :type => "application/pdf", :disposition => 'inline'
    
    这对我有用

    pdf = Prawn::Document.new(:page_size => "LETTER", :page_layout => :landscape)
    pdf.render_file File.join(Rails.root, "app/pdfs", "x.pdf")
    current_user.certificate = File.open("#{Rails.root}/app/pdfs/x.pdf")
    current_user.save!
    
    其中,
    证书
    是我的回形针附件在模型中保存的内容:

    class User < ActiveRecord::Base
      has_attached_file :certificate
    
    class用户
    @Adam Albrecht,您将图像保存为附件,但要将pdf保存为附件,您需要再添加一次验证-


    ****验证附件:文档,内容类型:{content\u type:'application/pdf'}****

    我发现这对于从模型方法生成pdf非常有用。我遇到的一个错误是,如果您的prawnto模板使用pdf.method\u name样式,则必须将Prawn::Document.new的输出命名为“pdf”。谢谢^这是一个关于如何使用普通对虾生成例程并呈现屏幕或电子邮件的完美答案。谢谢
    class User < ActiveRecord::Base
      has_attached_file :certificate