2013-03-12 94 views
3

在我的發票系統中,我希望有一個備份功能可以在一個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

回答

2

我認爲什麼是錯在你的代碼是你個人有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