1
votes

I'm using Prawn in a Rails app to produce a PDF of tiled objects - something like a page of mail merged labels.

I've set up a grid in the pdf document, but am having trouble working out how to iterate through this grid with my collection.

My pdf class looks something like this.

class MyPdf < Prawn::Document
  def initialize(vessels, view)
    super(page_layout: :landscape)
    @objects = objects

    define_grid columns: 2, rows: 3, gutter: 10

    build_page
  end

  def build_page
    @objects.each do |object|
      [0,1].each do |col|
        [0,1,2].each do |row|
          grid(row,col).bounding_box do
            text object.name
          end
        end
      end
    end
  end
end

This code is obviously not working, and not placing each object in a new grid square and creating new pages as required.

How do I iterate through my objects, and place each one in its own grid square?

(NB. I'm aware of the prawn-labels gem, but it has some limitations so not suitable for my needs. )

1

1 Answers

2
votes

The problem is you're writing to each grid location for each item. Try this instead, this should only write once per object, and create a new page + grid when it needs to.

def build_page
  define_grid columns: 2, rows: 3, gutter: 10
  col = 0
  row = 0
  @objects.each do |object|
    grid(row,col).bounding_box do
      text object.name
      if row == 2 && col == 1
        start_new_page
        define_grid columns: 2, rows: 3, gutter: 10
        col = 0
        row = 0
      else 
        if col == 1
          row += 1
          col = 0
        else
          col += 1
        end
      end
    end
  end
end