Getting PDF from WickedPDF for attachment via Carrierwave

后端 未结 2 2045
时光取名叫无心
时光取名叫无心 2021-02-13 03:38

In Rails3, I am using the WickedPDF gem to render a PDF format of one of my models. This is working fine: /invoices/123 returns HTML, /invoices/1

相关标签:
2条回答
  • 2021-02-13 03:53

    There's a better way: PDF in Rails without controllers.

    0 讨论(0)
  • 2021-02-13 04:08

    Solution:

    def create_pdf_copy
    
        wicked = WickedPdf.new
    
        # Make a PDF in memory
        pdf_file = wicked.pdf_from_string( 
            ActionController::Base.new().render_to_string(
                :template   => 'aggregations/show.pdf.haml', 
                :layout     => 'layouts/pdf.html.haml',
                :locals     => { 
                    :aggregation => self
                } 
            ),
            :pdf => "#{self.type}-#{self}",
            :layout => 'pdf.html',
            :page_size => 'Letter',
            :wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
            :margin => {
                :top      => '0.5in',
                :bottom   => '1in',
                :left     => '0in',
                :right    => '0in'
            },
            :footer => {
                :content => ActionController::Base.new().render_to_string({
                    :template => 'aggregations/footer.pdf.haml', 
                    :layout => false
                })
            },
            :header => {
                :content => ActionController::Base.new().render_to_string({
                    :template => 'aggregations/header.pdf.haml', 
                    :layout => false
                })
            }
        )
    
        # Write it to tempfile
        tempfile = Tempfile.new(['invoice', '.pdf'], Rails.root.join('tmp'))
        tempfile.binmode
        tempfile.write pdf_file
        tempfile.close
    
        # Attach that tempfile to the invoice
        unless pdf_file.blank?
            self.uploads.clear
            self.uploads.create(:fileinfo => File.open(tempfile.path), :job_id => self.job.id)
            tempfile.unlink
        end
    
    end
    
    0 讨论(0)
提交回复
热议问题