How to check if a boundbox fits the current page in Prawn

Viewed 837

Using Ruby 2.4 and Prawn 2.2.0, I would like to place a block of content into the next page, if it doesn't fit the current page. I've attempted with bounding boxes, because this way the inner content can be whatever I want, but I'm not achieving it.

I have the following document:

require 'prawn'

class Doc < Prawn::Document
  def initialize(options: {})
    super(options.merge(**page_options))
    setup_page
    header
    body
    footer
  end

  def header
    bounding_box([0, cursor], width: bounds.width) do
      bounding_box([0, bounds.top], width: bounds.width / 2) do
        text 'Left Header', size: 36
      end

      bounding_box([bounds.width / 2, bounds.top], width: bounds.width / 2) do
        text 'Right Header', size: 36
      end
      stroke_bounds
    end
  end

  def body
    bounding_box([0, cursor], width: bounds.width / 2) do
      text 'The stack has overflowed over the overflow' * 12, size: 24
    end
  end

  def footer
    bounding_box([0, cursor], width: bounds.width) do
      bounding_box([0, bounds.top], width: bounds.width / 2) do
        text 'Left Footer' * 3, size: 36, color: '0000FF'
        stroke_bounds
      end

      bounding_box([bounds.width / 2, bounds.top], width: bounds.width / 2) do
        text 'Right Footer' * 3, size: 36, color: '0000FF'
        stroke_bounds
      end
    end
  end

  def setup_page
    define_grid(columns: 12, rows: 8, gutter: 10)
  end

  def page_options
    {
      page_size: ::PDF::Core::PageGeometry::SIZES['A4'],
      page_layout: :portrait
    }
  end
end

Doc.new.render_file 'doc.pdf'

Since I want to have the footer on the same page, ie without page break, I need to check the heigh and see if it fits the current page, if not insert a page break.

The problem is I don't have a way to create a bounding box for inspection and later draw it.

Or there is another way to ensure the content is not split, ensuring it's all on the same page?

0 Answers
Related