Getting PDF from WickedPDF for attachment via Carrierwave

后端 未结 2 2053
时光取名叫无心
时光取名叫无心 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 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
    

提交回复
热议问题