使用wicked_pdf从生成的PDF生成ZIP

时间:2013-03-12 11:34:10

标签: ruby-on-rails-3 heroku wicked-pdf rubyzip

在我的发票系统中,我想要一个备份功能,在一个zip文件中一次下载所有发票。 该系统在heroku上运行 - 因此只能暂时保存pdfs。

我安装了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

这以消息结束 BillsController中的IOError#zip_all_bills关闭流

1 个答案:

答案 0 :(得分:3)

我认为您的代码中出现的问题是您的zip已经存在,但您也可以将其用于个人pdf。所以我认为当你尝试将tempfile用于pdf时,这是一个问题,因为你已经将它用于zip。

但我认为你根本不需要使用临时文件(而且我从来没有真正得到一个使用Heroku的临时文件解决方案)

这是一个适用于我的控制器方法 - 也在heroku上使用wickedpdf和rubyzip。请注意,我没有使用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
相关问题