rubypdfprawn

Prawn: Creating a PDF having a header banner and a repeated-header table


The objective is: Creating a PDF having a header banner and a repeated-header table
The problem is: pdf.move_down not work if the table start a new page

CODE:
# repeat drawing in every page
pdf.repeat(:all, :dynamic => true) do
    pdf.font("#{Rails.root}/vendor/pdffonts/ThonburiBold.ttf") do
    pdf.font_size = 8 

    pdf.float { pdf.text "Time: #{tt}", :align => :left }
    pdf.float { pdf.text "Page #{pdf.page_number}", :align => :right }
    pdf.float { pdf.text "Inquiry Name: #{page_title}", :align => :center }

    pdf.move_down 15

    pdf.float { pdf.text "AS OF #{Time.now.to_date}", :align => :center }


    pdf.move_down 40      ## move down to draw the following table
    pdf.stroke_horizontal_rule
end

## ... building big_data_array for table ...

table_config = {
    :header => true,
    :row_colors => ["FFFFFF", "F0F0F0"],
    :cell_style => { :padding => 1 }
}

# draw a long table
pdf.table(big_data_array, table_config) do |t|
    t.before_rendering_page do |c|
      pdf.move_down 40    ## try to add margin-top before render the table in every page
    end
    t.row(0).background_color = "DADADA"
    # style rows and cells ...
end

Solution

  • I decided to modified Prawn::Table method draw to accept my offset value

    module Prawn
      class Table
        def set_before_render_offset(y = 0)
        @user_offset = y
      end
    
      def draw
        ...
        # start a new page or column
        @pdf.bounds.move_past_bottom
        if cell.row > 0 && @header
          header_height = add_header(cells_this_page, @pdf.cursor - @user_offset, cell.row-1)
        else
          header_height = 0
        end
        offset = @pdf.y - cell.y - header_height - @user_offset
        started_new_page_at_row = cell.row
        ...
      end
    end