使用wicked_pdf从生成的PDF生成ZIP

问题描述:

在我的发票系统中,我希望有一个备份功能可以在一个zip文件中一次下载所有发票。 此系统在heroku上运行 - 因此只能暂时保存pdf。使用wicked_pdf从生成的PDF生成ZIP

我已经安装了rubyzip和wicked_pdf gem。

我当前的代码在控制器:

def zip_all_bills 
    @bill = Bill.all 
    if @bill.count > 0 
     t = Tempfile.new("bill_tmp_#{Time.now}") 
     Zip::ZipOutputStream.open(t.path) do |z| 
     @bill.each do |bill| 
      @bills = bill 
      @customer = @bills.customer 
      @customer_name = @customer.name_company_id 
      t = WickedPdf.new.pdf_from_string(
       render :template => '/bills/printing.html.erb', 
        :disposition => "attachment", 
        :margin => { :bottom => 23 }, 
        :footer => { :html => { :template => 'pdf/footer.pdf.erb' } } 
     ) 

      z.puts("invoice_#{bill.id}") 
      z.print IO.read(t.path) 
     end 
     end 

     send_file t.path, :type => "application/zip", 
         :disposition => "attachment", 
         :filename => "bills_backup" 

     t.close 
    end 

    respond_to do |format| 
     format.html { redirect_to bills_url } 
    end 
    end 

这结束与消息 的IOError在BillsController#zip_all_bills关闭流

+0

嗨,我有和你一样的问题。我有一个invocing应用程序,我想用生成的PDF与wicked_pdf生成ZIP。我无法找到适合此问题的解决方案。我会很感激任何意见。 – 2014-09-05 05:42:58

我认为什么是错在你的代码是你个人有T为您的邮编,但你也可以使用它的个人PDF文件。所以我想当你尝试使用pdf文件的时候,这是一个问题,因为你已经在使用它作为zip。

但我不认为你需要在所有使用临时文件(我从来没有真正得到一个临时文件的解决方案在Heroku上工作)

这里是一个控制器方法为我的作品 - 也使用wickedpdf和rubyzip在heroku上。请注意,我没有使用Tempfile,而是使用StringIO做了所有事情(至少我认为这是潜在的技术)。

def dec_zip 
    require 'zip' 
    #grab some test records 
    @coverages = Coverage.all.limit(10) 
    stringio = Zip::OutputStream.write_buffer do |zio| 
     @coverages.each do |coverage| 
     #create and add a text file for this record 
     zio.put_next_entry("#{coverage.id}_test.txt") 
     zio.write "Hello #{coverage.agency_name}!" 
     #create and add a pdf file for this record 
     dec_pdf = render_to_string :pdf => "#{coverage.id}_dec.pdf", :template => 'coverages/dec_page', :locals => {coverage: coverage}, :layout => 'print' 
     zio.put_next_entry("#{coverage.id}_dec.pdf") 
     zio << dec_pdf 
     end 
    end 
    # This is needed because we are at the end of the stream and 
    # will send zero bytes otherwise 
    stringio.rewind 
    #just using variable assignment for clarity here 
    binary_data = stringio.sysread 
    send_data(binary_data, :type => 'application/zip', :filename => "test_dec_page.zip") 
end