使用 wicked_pdf 从生成的 PDF 生成 ZIP

2024-03-18

在我的发票系统中,我需要一个备份功能来一次性下载所有发票到一个 zip 文件中。 该系统在 Heroku 上运行 - 因此只能临时保存 pdf。

我安装了 ruby​​zip 和 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#zip_all_bills 关闭流中的 IOError


我认为你的代码中的错误是你的 zip 没有 t 但你也将它用于单独的 pdf。所以我认为当你尝试将临时文件用于 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 wicked_pdf 从生成的 PDF 生成 ZIP 的相关文章

随机推荐