Ruby: Prawn PDF from memory using group method

I have a large number of products that I want to display in pdf, with category headings. If the category is not suitable for the current page, I want to move it to another. For this, I use the Prawn group method.

Product.all.group_by(&:category).each do |category, products|
  pdf.group do
    # Simplified the data a bit for this example
    pdf.text category
    pdf.table products.map{ |p| [p.title, p.price] }
  end
end

This works very well for a small number of products, but when I add more than 100 or so, it takes a very long time and then ends up like this: "memory allocation failed." If I do not use the group method, it takes about 30 seconds.

Obviously, the group method does not use memory very well. Any suggestions on workarounds would be appreciated.

+3
2

---------- --------

, git repo, /, : https://github.com/sandal/prawn/wiki/Using-Prawn-in-Rails

, / . PDF.

, git Rails . .

---------- --------

, , , :

  • Prawn:: Document 'group'
  • "" ( github.com).

, /lib Rails. mime PDF:

class PdfPrawn
  require 'prawn'
  require 'prawn/core'
  require 'prawn/table'
  MIME_TYPE = "application/pdf"
end
class Prawn::Document
  def group(second_attempt=false)
    old_bounding_box = @bounding_box
    @bounding_box = SimpleDelegator.new(@bounding_box)

    def @bounding_box.move_past_bottom
      raise RollbackTransaction
    end

    success = transaction { yield }

    @bounding_box = old_bounding_box

    unless success
      raise Prawn::Errors::CannotGroup if second_attempt
      old_bounding_box.move_past_bottom
      group(second_attempt=true) { yield }
    end

    success
  end
end

PDF - :

def to_pdf
  require "#{File.expand_path(RAILS_ROOT)}/lib/pdf_prawn"
  pdf = Prawn::Document.new
  # code to add stuff to PDF
  pdf.render
end
+1

, , , wicked pdf. , .

+2

All Articles