prawn-table-0.2.1/0000755000004100000410000000000012436072751013765 5ustar www-datawww-dataprawn-table-0.2.1/Gemfile0000644000004100000410000000004712436072751015261 0ustar www-datawww-datasource "https://rubygems.org" gemspec prawn-table-0.2.1/manual/0000755000004100000410000000000012436072751015242 5ustar www-datawww-dataprawn-table-0.2.1/manual/contents.rb0000644000004100000410000000043012436072751017421 0ustar www-datawww-data# encoding: utf-8 # # Generates the Prawn by example manual. require_relative "example_helper" Encoding.default_external = Encoding::UTF_8 Prawn::ManualBuilder::Example.generate("manual.pdf", :skip_page_creation => true, :page_size => "FOLIO") do load_package "table" end prawn-table-0.2.1/manual/example_helper.rb0000644000004100000410000000024312436072751020560 0ustar www-datawww-data# encoding: UTF-8 require "prawn" require_relative "../lib/prawn/table" require "prawn/manual_builder" Prawn::ManualBuilder.manual_dir = File.dirname(__FILE__) prawn-table-0.2.1/manual/table/0000755000004100000410000000000012436072751016331 5ustar www-datawww-dataprawn-table-0.2.1/manual/table/image_cells.rb0000644000004100000410000000273312436072751021127 0ustar www-datawww-data# encoding: utf-8 # # Prawn can insert images into a table. Just pass a hash into # table() with an :image key pointing to the image. # # You can pass the :scale, :fit, # :position, and :vposition arguments in alongside # :image; these will function just as in image(). # # The :image_width and :image_height arguments set # the width/height of the image within the cell, as opposed to the # :width and :height arguments, which set the table # cell's dimensions. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do image = "#{Prawn::DATADIR}/images/prawn.png" table [ ["Standard image cell", {:image => image}], [":scale => 0.5", {:image => image, :scale => 0.5}], [":fit => [100, 200]", {:image => image, :fit => [100, 200]}], [":image_height => 50, :image_width => 100", {:image => image, :image_height => 50, :image_width => 100}], [":position => :center", {:image => image, :position => :center}], [":vposition => :center", {:image => image, :vposition => :center, :height => 200}] ], :width => bounds.width end prawn-table-0.2.1/manual/table/row_colors.rb0000644000004100000410000000120112436072751021040 0ustar www-datawww-data# encoding: utf-8 # # One of the most common table styling techniques is to stripe the rows with # alternating colors. # # There is one helper just for that. Just provide the :row_colors # option an array with color values. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do data = [["This row should have one color"], ["And this row should have another"]] data += [["..."]] * 10 table(data, :row_colors => ["F0F0F0", "FFFFCC"]) end prawn-table-0.2.1/manual/table/style.rb0000644000004100000410000000141112436072751020013 0ustar www-datawww-data# encoding: utf-8 # # We've seen how to apply styles to a selection of cells by setting the # individual properties. Another option is to use the style method # # style lets us define multiple properties at once with a hash. It # also accepts a block that will be called for each cell and can be used for # some complex styling. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do table([[""] * 8] * 8) do cells.style(:width => 24, :height => 24) cells.style do |c| c.background_color = ((c.row + c.column) % 2).zero? ? '000000' : 'ffffff' end end end prawn-table-0.2.1/manual/table/creation.rb0000644000004100000410000000216212436072751020463 0ustar www-datawww-data# encoding: utf-8 # # Creating tables with Prawn is fairly easy. There are two methods that will # create tables for us table and make_table. # # Both are wrappers that create a new Prawn::Table object. The # difference is that table calls the draw method # after creating the table and make_table only returns the created # table, so you have to call the draw method yourself. # # The most simple table can be created by providing only an array of arrays # containing your data where each inner array represents one row. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do t = make_table([ ["this is the first row"], ["this is the second row"] ]) t.draw move_down 20 table([ ["short", "short", "loooooooooooooooooooong"], ["short", "loooooooooooooooooooong", "short"], ["loooooooooooooooooooong", "short", "short"] ]) end prawn-table-0.2.1/manual/table/span.rb0000644000004100000410000000246012436072751017621 0ustar www-datawww-data# encoding: utf-8 # # Table cells can span multiple columns, rows, or both. When building a cell, # use the hash argument constructor with a :colspan and/or # :rowspan argument. Row or column spanning must be specified when # building the data array; you can't set the span in the table's initialization # block. This is because cells are laid out in the grid before that block is # called, so that references to row and column numbers make sense. # # Cells are laid out in the order given, skipping any positions spanned by # previously instantiated cells. Therefore, a cell with rowspan: 2 # will be missing at least one cell in the row below it. See the code and table # below for an example. # # It is illegal to overlap cells via spanning. A # Prawn::Errors::InvalidTableSpan error will be raised if spans # would cause cells to overlap. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do table([ ["A", {:content => "2x1", :colspan => 2}, "B"], [{:content => "1x2", :rowspan => 2}, "C", "D", "E"], [{:content => "2x2", :colspan => 2, :rowspan => 2}, "F"], ["G", "H"] ]) end prawn-table-0.2.1/manual/table/cell_borders_and_bg.rb0000644000004100000410000000205412436072751022610 0ustar www-datawww-data# encoding: utf-8 # # The borders option accepts an array with the border sides that # will be drawn. The default is [:top, :bottom, :left, :right]. # # border_width may be set with a numeric value. # # Both border_color and background_color accept an # HTML like RGB color string ("FF0000") # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do data = [ ["Look at how the cells will look when styled", "", ""], ["They probably won't look the same", "", ""] ] { :borders => [:top, :left], :border_width => 3, :border_color => "FF0000"}.each do |property, value| text "Cell #{property}: #{value.inspect}" table(data, :cell_style => {property => value}) move_down 20 end text "Cell background_color: FFFFCC" table(data, :cell_style => {:background_color => "FFFFCC"}) end prawn-table-0.2.1/manual/table/filtering.rb0000644000004100000410000000203012436072751020634 0ustar www-datawww-data# encoding: utf-8 # # Another way to reduce the number of cells is to filter the table. # # filter is just like Enumerable#select. Pass it a # block and it will iterate through the cells returning a new # Prawn::Table::Cells instance containing only those cells for # which the block was not false. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do data = [ ["Item", "Jan Sales", "Feb Sales"], ["Oven", 17, 89], ["Fridge", 62, 30], ["Microwave", 71, 47] ] table(data) do values = cells.columns(1..-1).rows(1..-1) bad_sales = values.filter do |cell| cell.content.to_i < 40 end bad_sales.background_color = "FFAAAA" good_sales = values.filter do |cell| cell.content.to_i > 70 end good_sales.background_color = "AAFFAA" end end prawn-table-0.2.1/manual/table/table.rb0000644000004100000410000000272412436072751017752 0ustar www-datawww-data# encoding: utf-8 # # Examples for tables. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) Prawn::ManualBuilder::Example.generate("table.pdf", :page_size => "FOLIO") do package "table" do |p| p.name = "Prawn::Table" p.section "Basics" do |s| s.example "creation" s.example "content_and_subtables" s.example "flow_and_header" s.example "position" end p.section "Styling" do |s| s.example "column_widths" s.example "width" s.example "row_colors" s.example "cell_dimensions" s.example "cell_borders_and_bg" s.example "cell_border_lines" s.example "cell_text" s.example "image_cells" s.example "span" s.example "before_rendering_page" end p.section "Initializer Block" do |s| s.example "basic_block" s.example "filtering" s.example "style" end p.intro do prose("Prawn comes with table support out of the box. Tables can be styled in whatever way you see fit. The whole table, rows, columns and cells can be styled independently from each other. The examples show:") list( "How to create tables", "What content can be placed on tables", "Subtables (or tables within tables)", "How to style the whole table", "How to use initializer blocks to style only specific portions of the table" ) end end end prawn-table-0.2.1/manual/table/cell_border_lines.rb0000644000004100000410000000156412436072751022332 0ustar www-datawww-data# encoding: utf-8 # # The border_lines option accepts an array with the styles of the # border sides. The default is [:solid, :solid, :solid, :solid]. # # border_lines must be set to an array. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do data = [ ["Look at how the cell border lines can be mixed", "", ""], ["dotted top border", "", ""], ["solid right border", "", ""], ["dotted bottom border", "", ""], ["dashed left border", "", ""] ] text "Cell :border_lines => [:dotted, :solid, :dotted, :dashed]" table(data, :cell_style => { :border_lines => [:dotted, :solid, :dotted, :dashed] }) end prawn-table-0.2.1/manual/table/position.rb0000644000004100000410000000155012436072751020523 0ustar www-datawww-data# encoding: utf-8 # # The table() method accepts a :position argument to # determine horizontal position of the table within its bounding box. It can be # :left (the default), :center, :right, # or a number specifying a distance in PDF points from the left side. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do data = [["The quick brown fox jumped over the lazy dogs."]] * 2 text "Left:" table data, :position => :left move_down 10 text "Center:" table data, :position => :center move_down 10 text "Right:" table data, :position => :right move_down 10 text "100pt:" table data, :position => 100 end prawn-table-0.2.1/manual/table/basic_block.rb0000644000004100000410000000406712436072751021120 0ustar www-datawww-data# encoding: utf-8 # # All of the previous styling options we've seen deal with all the table cells # at once. # # With initializer blocks we may deal with specific cells. # A block passed to one of the table methods (Prawn::Table.new, # Prawn::Document#table, Prawn::Document#make_table) # will be called after cell setup but before layout. This is a very flexible way # to specify styling and layout constraints. # # Just like the Prawn::Document.generate method, the table # initializer blocks may be used with and without a block argument. # # The table class has three methods that are handy within an initializer block: # cells, rows and columns. All three # return an instance of Prawn::Table::Cells which represents # a selection of cells. # # cells return all the table cells, while rows and # columns accept a number or a range as argument which returns a # single row/column or a range of rows/columns respectively. (rows # and columns are also aliased as row and # column) # # The Prawn::Table::Cells class also defines rows and # columns so they may be chained to narrow the selection of cells. # # All of the cell styling options we've seen on previous examples may be set as # properties of the selection of cells. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do data = [ ["Header", "A " * 5, "B"], ["Data row", "C", "D " * 5], ["Another data row", "E", "F"]] table(data) do cells.padding = 12 cells.borders = [] row(0).borders = [:bottom] row(0).border_width = 2 row(0).font_style = :bold columns(0..1).borders = [:right] row(0).columns(0..1).borders = [:bottom, :right] end end prawn-table-0.2.1/manual/table/flow_and_header.rb0000644000004100000410000000116512436072751021762 0ustar www-datawww-data# encoding: utf-8 # # If the table cannot fit on the current page it will flow to the next page just # like free flowing text. If you would like to have the first row treated as a # header which will be repeated on subsequent pages set the :header # option to true. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do data = [["This row should be repeated on every new page"]] data += [["..."]] * 30 table(data, :header => true) end prawn-table-0.2.1/manual/table/column_widths.rb0000644000004100000410000000214412436072751021536 0ustar www-datawww-data# encoding: utf-8 # # Prawn will make its best attempt to identify the best width for the columns. # If the end result isn't good, we can override it with some styling. # # Individual column widths can be set with the :column_widths # option. Just provide an array with the sequential width values for the columns # or a hash were each key-value pair represents the column 0-based index and its # width. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do data = [ ["this is not quite as long as the others", "here we have a line that is long but with smaller words", "this is so very looooooooooooooooooooooooooooooong"] ] text "Prawn trying to guess the column widths" table(data) move_down 20 text "Manually setting all the column widths" table(data, :column_widths => [100, 200, 240]) move_down 20 text "Setting only the last column width" table(data, :column_widths => {2 => 240}) end prawn-table-0.2.1/manual/table/width.rb0000644000004100000410000000144612436072751020002 0ustar www-datawww-data# encoding: utf-8 # # The default table width depends on the content provided. It will expand up # to the current bounding box width to fit the content. If you want the table to # have a fixed width no matter the content you may use the :width # option to manually set the width. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do text "Normal width:" table [%w[A B C]] move_down 20 text "Fixed width:" table([%w[A B C]], :width => 300) move_down 20 text "Normal width:" table([["A", "Blah " * 20, "C"]]) move_down 20 text "Fixed width:" table([["A", "Blah " * 20, "C"]], :width => 300) end prawn-table-0.2.1/manual/table/before_rendering_page.rb0000644000004100000410000000172712436072751023160 0ustar www-datawww-data# encoding: utf-8 # # Prawn::Table#initialize takes a # :before_rendering_page argument, to adjust the way an entire page # of table cells is styled. This allows you to do things like draw a border # around the entire table as displayed on a page. # # The callback is passed a Cells object that is numbered based on the order of # the cells on the page (e.g., the first row on the page is # cells.row(0)). # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do table([["foo", "bar", "baz"]] * 40) do |t| t.cells.border_width = 1 t.before_rendering_page do |page| page.row(0).border_top_width = 3 page.row(-1).border_bottom_width = 3 page.column(0).border_left_width = 3 page.column(-1).border_right_width = 3 end end end prawn-table-0.2.1/manual/table/cell_text.rb0000644000004100000410000000273412436072751020647 0ustar www-datawww-data# encoding: utf-8 # # Text cells accept the following options: align, # font, font_style, inline_format, # kerning, leading, min_font_size, # overflow, rotate, rotate_around, # single_line, size, text_color, # and valign. # # Most of these style options are direct translations from the text methods # styling options. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do data = [ ["Look at how the cells will look when styled", "", ""], ["They probably won't look the same", "", ""] ] table data, :cell_style => { :font => "Times-Roman", :font_style => :italic } move_down 20 table data, :cell_style => { :size => 18, :text_color => "346842" } move_down 20 table [["Just some inline", "", ""], ["styles being applied here", "", ""]], :cell_style => { :inline_format => true } move_down 20 table [["1", "2", "3", "rotate"]], :cell_style => { :rotate => 30 } move_down 20 table data, :cell_style => { :overflow => :shrink_to_fit, :min_font_size => 8, :width => 60, :height => 30 } end prawn-table-0.2.1/manual/table/cell_dimensions.rb0000644000004100000410000000226412436072751022031 0ustar www-datawww-data# encoding: utf-8 # # To style all the table cells you can use the :cell_style option # with the table methods. It accepts a hash with the cell style options. # # Some straightforward options are width, height, # and padding. All three accept numeric values to set the property. # # padding also accepts a four number array that defines the padding # in a CSS like syntax setting the top, right, bottom, left sequentially. The # default is 5pt for all sides. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do data = [ ["Look at how the cells will look when styled", "", ""], ["They probably won't look the same", "", ""] ] {:width => 160, :height => 50, :padding => 12}.each do |property, value| text "Cell's #{property}: #{value}" table(data, :cell_style => {property => value}) move_down 20 end text "Padding can also be set with an array: [0, 0, 0, 30]" table(data, :cell_style => {:padding => [0, 0, 0, 30]}) end prawn-table-0.2.1/manual/table/content_and_subtables.rb0000644000004100000410000000272012436072751023217 0ustar www-datawww-data# encoding: utf-8 # # There are five kinds of objects which can be put in table cells: # 1. String: produces a text cell (the most common usage) # 2. Prawn::Table::Cell # 3. Prawn::Table # 4. Array # 5. Images # # Whenever a table or an array is provided as a cell, a subtable will be created # (a table within a cell). # # If you'd like to provide a cell or table directly, the best way is to # use the make_cell and make_table methods as they # don't call draw on the created object. # # To insert an image just provide a hash with an with an :image key # pointing to the image path. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do cell_1 = make_cell(:content => "this row content comes directly ") cell_2 = make_cell(:content => "from cell objects") two_dimensional_array = [ ["..."], ["subtable from an array"], ["..."] ] my_table = make_table([ ["..."], ["subtable from another table"], ["..."] ]) image_path = "#{Prawn::DATADIR}/images/stef.jpg" table([ ["just a regular row", "", "", "blah blah blah"], [cell_1, cell_2, "", ""], ["", "", two_dimensional_array, ""], ["just another regular row", "", "", ""], [{:image => image_path}, "", my_table, ""]]) end prawn-table-0.2.1/GPLv20000644000004100000410000004311012436072751014601 0ustar www-datawww-data GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. prawn-table-0.2.1/prawn-table.gemspec0000644000004100000410000000312412436072751017546 0ustar www-datawww-databasedir = File.expand_path(File.dirname(__FILE__)) require "#{basedir}/lib/prawn/table/version" Gem::Specification.new do |spec| spec.name = "prawn-table" spec.version = Prawn::Table::VERSION spec.platform = Gem::Platform::RUBY spec.summary = "Provides tables for PrawnPDF" spec.files = Dir.glob("{examples,lib,spec,manual}/**/**/*") + ["prawn-table.gemspec", "Gemfile", "COPYING", "LICENSE", "GPLv2", "GPLv3"] spec.require_path = "lib" spec.required_ruby_version = '>= 1.9.3' spec.required_rubygems_version = ">= 1.3.6" spec.test_files = Dir[ "spec/*_spec.rb" ] spec.authors = ["Gregory Brown","Brad Ediger","Daniel Nelson","Jonathan Greenberg","James Healy", "Hartwig Brandl"] spec.email = ["gregory.t.brown@gmail.com","brad@bradediger.com","dnelson@bluejade.com","greenberg@entryway.net","jimmy@deefa.com", "mail@hartwigbrandl.at"] spec.rubyforge_project = "prawn" spec.licenses = ['RUBY', 'GPL-2', 'GPL-3'] spec.add_development_dependency('prawn', '>= 1.3.0', '< 3.0.0') spec.add_development_dependency('pdf-inspector', '~> 1.1.0') spec.add_development_dependency('yard') spec.add_development_dependency('rspec', '2.14.1') spec.add_development_dependency('mocha') spec.add_development_dependency('rake') spec.add_development_dependency('simplecov') spec.add_development_dependency('prawn-manual_builder', ">= 0.2.0") spec.add_development_dependency('pdf-reader', '~>1.2') spec.homepage = "https://github.com/prawnpdf/prawn-table" spec.description = < 0) end RSpec::Matchers.define :have_parseable_xobjects do match do |actual| expect { PDF::Inspector::XObject.analyze(actual.render) }.not_to raise_error true end failure_message_for_should do |actual| "expected that #{actual}'s XObjects could be successfully parsed" end end # Make some methods public to assist in testing module Prawn::Graphics public :map_to_absolute end prawn-table-0.2.1/spec/cell_spec.rb0000644000004100000410000004542412436072751017206 0ustar www-datawww-data# encoding: utf-8 require File.join(File.expand_path(File.dirname(__FILE__)), "spec_helper") require_relative "../lib/prawn/table" module CellHelpers # Build, but do not draw, a cell on @pdf. def cell(options={}) at = options[:at] || [0, @pdf.cursor] Prawn::Table::Cell::Text.new(@pdf, at, options) end end describe "Prawn::Table::Cell" do before(:each) do @pdf = Prawn::Document.new end describe "Prawn::Document#cell" do include CellHelpers it "should draw the cell" do Prawn::Table::Cell::Text.any_instance.expects(:draw).once @pdf.cell(:content => "text") end it "should return a Cell" do @pdf.cell(:content => "text").should be_a_kind_of Prawn::Table::Cell end it "accepts :content => nil in a hash" do @pdf.cell(:content => nil).should be_a_kind_of(Prawn::Table::Cell::Text) @pdf.make_cell(:content => nil).should be_a_kind_of(Prawn::Table::Cell::Text) end it "should convert nil, Numeric, and Date values to strings" do [nil, 123, 123.45, Date.today].each do |value| c = @pdf.cell(:content => value) c.should be_a_kind_of Prawn::Table::Cell::Text c.content.should == value.to_s end end it "should allow inline styling with a hash argument" do # used for table([[{:text => "...", :font_style => :bold, ...}, ...]]) c = Prawn::Table::Cell.make(@pdf, {:content => 'hello', :font_style => :bold}) c.should be_a_kind_of Prawn::Table::Cell::Text c.content.should == "hello" c.font.name.should == 'Helvetica-Bold' end it "should draw text at the given point plus padding, with the given " + "size and style" do @pdf.expects(:bounding_box).yields @pdf.expects(:move_down) @pdf.expects(:draw_text!).with { |text, options| text == "hello world" } @pdf.cell(:content => "hello world", :at => [10, 20], :padding => [30, 40], :size => 7, :font_style => :bold) end end describe "Prawn::Document#make_cell" do it "should not draw the cell" do Prawn::Table::Cell::Text.any_instance.expects(:draw).never @pdf.make_cell("text") end it "should return a Cell" do @pdf.make_cell("text", :size => 7).should be_a_kind_of Prawn::Table::Cell end end describe "#style" do include CellHelpers it "should set each property in turn" do c = cell(:content => "text") c.expects(:padding=).with(50) c.expects(:size=).with(7) c.style(:padding => 50, :size => 7) end it "ignores unknown properties" do c = cell(:content => 'text') c.style(:foobarbaz => 'frobnitz') end end describe "cell width" do include CellHelpers it "should be calculated for text" do c = cell(:content => "text") c.width.should == @pdf.width_of("text") + c.padding[1] + c.padding[3] end it "should be overridden by manual :width" do c = cell(:content => "text", :width => 400) c.width.should == 400 end it "should incorporate padding when specified" do c = cell(:content => "text", :padding => [1, 2, 3, 4]) c.width.should be_within(0.01).of(@pdf.width_of("text") + 6) end it "should allow width to be reset after it has been calculated" do # to ensure that if we memoize width, it can still be overridden c = cell(:content => "text") c.width c.width = 400 c.width.should == 400 end it "should return proper width with size set" do text = "text " * 4 c = cell(:content => text, :size => 7) c.width.should == @pdf.width_of(text, :size => 7) + c.padding[1] + c.padding[3] end it "content_width should exclude padding" do c = cell(:content => "text", :padding => 10) c.content_width.should == @pdf.width_of("text") end it "content_width should exclude padding even with manual :width" do c = cell(:content => "text", :padding => 10, :width => 400) c.content_width.should be_within(0.01).of(380) end it "should have a reasonable minimum width that can fit @content" do c = cell(:content => "text", :padding => 10) min_content_width = c.min_width - c.padding[1] - c.padding[3] @pdf.height_of("text", :width => min_content_width).should be < (5 * @pdf.height_of("text")) end it "should defer min_width's evaluation of padding" do c = cell(:content => "text", :padding => 100) c.padding = 0 # Make sure we use the new value of padding in calculating min_width c.min_width.should be < 100 end it "should defer min_width's evaluation of size" do c = cell(:content => "text", :size => 50) c.size = 8 c.padding = 0 c.min_width.should be < 10 end end describe "cell height" do include CellHelpers it "should be calculated for text" do c = cell(:content => "text") c.height.should == @pdf.height_of("text", :width => @pdf.width_of("text")) + c.padding[0] + c.padding[3] end it "should be overridden by manual :height" do c = cell(:content => "text", :height => 400) c.height.should == 400 end it "should incorporate :padding when specified" do c = cell(:content => "text", :padding => [1, 2, 3, 4]) c.height.should be_within(0.01).of(1 + 3 + @pdf.height_of("text", :width => @pdf.width_of("text"))) end it "should allow height to be reset after it has been calculated" do # to ensure that if we memoize height, it can still be overridden c = cell(:content => "text") c.height c.height = 400 c.height.should == 400 end it "should return proper height for blocks of text" do content = "words " * 10 c = cell(:content => content, :width => 100) c.height.should == @pdf.height_of(content, :width => 100) + c.padding[0] + c.padding[2] end it "should return proper height for blocks of text with size set" do content = "words " * 10 c = cell(:content => content, :width => 100, :size => 7) correct_content_height = nil @pdf.font_size(7) do correct_content_height = @pdf.height_of(content, :width => 100) end c.height.should == correct_content_height + c.padding[0] + c.padding[2] end it "content_height should exclude padding" do c = cell(:content => "text", :padding => 10) c.content_height.should == @pdf.height_of("text") end it "content_height should exclude padding even with manual :height" do c = cell(:content => "text", :padding => 10, :height => 400) c.content_height.should be_within(0.01).of(380) end end describe "cell padding" do include CellHelpers it "should default to zero" do c = cell(:content => "text") c.padding.should == [5, 5, 5, 5] end it "should accept a numeric value, setting all padding" do c = cell(:content => "text", :padding => 10) c.padding.should == [10, 10, 10, 10] end it "should accept [v,h]" do c = cell(:content => "text", :padding => [20, 30]) c.padding.should == [20, 30, 20, 30] end it "should accept [t,h,b]" do c = cell(:content => "text", :padding => [10, 20, 30]) c.padding.should == [10, 20, 30, 20] end it "should accept [t,l,b,r]" do c = cell(:content => "text", :padding => [10, 20, 30, 40]) c.padding.should == [10, 20, 30, 40] end it "should reject other formats" do lambda{ cell(:content => "text", :padding => [10]) }.should raise_error(ArgumentError) end end describe "background_color" do include CellHelpers it "should fill a rectangle with the given background color" do @pdf.stubs(:mask).yields @pdf.expects(:mask).with(:fill_color).yields @pdf.stubs(:fill_color) @pdf.expects(:fill_color).with('123456') @pdf.expects(:fill_rectangle).checking do |(x, y), w, h| x.should be_within(0.01).of(0) y.should be_within(0.01).of(@pdf.cursor) w.should be_within(0.01).of(29.344) h.should be_within(0.01).of(23.872) end @pdf.cell(:content => "text", :background_color => '123456') end it "should draw the background in the right place if cell is drawn at a " + "different location" do @pdf.stubs(:mask).yields @pdf.expects(:mask).with(:fill_color).yields @pdf.stubs(:fill_color) @pdf.expects(:fill_color).with('123456') @pdf.expects(:fill_rectangle).checking do |(x, y), w, h| x.should be_within(0.01).of(12.0) y.should be_within(0.01).of(34.0) w.should be_within(0.01).of(29.344) h.should be_within(0.01).of(23.872) end c = @pdf.make_cell(:content => "text", :background_color => '123456') c.draw([12.0, 34.0]) end end describe "color" do it "should set fill color when :text_color is provided" do pdf = Prawn::Document.new pdf.stubs(:fill_color) pdf.expects(:fill_color).with('555555') pdf.cell :content => 'foo', :text_color => '555555' end it "should reset the fill color to the original one" do pdf = Prawn::Document.new pdf.fill_color = '333333' pdf.cell :content => 'foo', :text_color => '555555' pdf.fill_color.should == '333333' end end describe "Borders" do it "should draw all borders by default" do @pdf.expects(:stroke_line).times(4) @pdf.cell(:content => "text") end it "should draw all borders when requested" do @pdf.expects(:stroke_line).times(4) @pdf.cell(:content => "text", :borders => [:top, :right, :bottom, :left]) end # Only roughly verifying the integer coordinates so that we don't have to # do any FP closeness arithmetic. Can plug in that math later if this goes # wrong. it "should draw top border when requested" do @pdf.expects(:stroke_line).checking do |from, to| @pdf.map_to_absolute(from).map{|x| x.round}.should == [36, 756] @pdf.map_to_absolute(to).map{|x| x.round}.should == [65, 756] end @pdf.cell(:content => "text", :borders => [:top]) end it "should draw bottom border when requested" do @pdf.expects(:stroke_line).checking do |from, to| @pdf.map_to_absolute(from).map{|x| x.round}.should == [36, 732] @pdf.map_to_absolute(to).map{|x| x.round}.should == [65, 732] end @pdf.cell(:content => "text", :borders => [:bottom]) end it "should draw left border when requested" do @pdf.expects(:stroke_line).checking do |from, to| @pdf.map_to_absolute(from).map{|x| x.round}.should == [36, 756] @pdf.map_to_absolute(to).map{|x| x.round}.should == [36, 732] end @pdf.cell(:content => "text", :borders => [:left]) end it "should draw right border when requested" do @pdf.expects(:stroke_line).checking do |from, to| @pdf.map_to_absolute(from).map{|x| x.round}.should == [65, 756] @pdf.map_to_absolute(to).map{|x| x.round}.should == [65, 732] end @pdf.cell(:content => "text", :borders => [:right]) end it "should draw borders at the same location when in or out of bbox" do @pdf.expects(:stroke_line).checking do |from, to| @pdf.map_to_absolute(from).map{|x| x.round}.should == [36, 756] @pdf.map_to_absolute(to).map{|x| x.round}.should == [65, 756] end @pdf.bounding_box([0, @pdf.cursor], :width => @pdf.bounds.width) do @pdf.cell(:content => "text", :borders => [:top]) end end it "should set border color with :border_..._color" do @pdf.ignores(:stroke_color=).with("000000") @pdf.expects(:stroke_color=).with("ff0000") c = @pdf.cell(:content => "text", :border_top_color => "ff0000") c.border_top_color.should == "ff0000" c.border_colors[0].should == "ff0000" end it "should set border colors with :border_color" do @pdf.ignores(:stroke_color=).with("000000") @pdf.expects(:stroke_color=).with("ff0000") @pdf.expects(:stroke_color=).with("00ff00") @pdf.expects(:stroke_color=).with("0000ff") @pdf.expects(:stroke_color=).with("ff00ff") c = @pdf.cell(:content => "text", :border_color => %w[ff0000 00ff00 0000ff ff00ff]) c.border_colors.should == %w[ff0000 00ff00 0000ff ff00ff] end it "border_..._width should return 0 if border not selected" do c = @pdf.cell(:content => "text", :borders => [:top]) c.border_bottom_width.should == 0 end it "should set border width with :border_..._width" do @pdf.ignores(:line_width=).with(1) @pdf.expects(:line_width=).with(2) c = @pdf.cell(:content => "text", :border_bottom_width => 2) c.border_bottom_width.should == 2 c.border_widths[2].should == 2 end it "should set border widths with :border_width" do @pdf.ignores(:line_width=).with(1) @pdf.expects(:line_width=).with(2) @pdf.expects(:line_width=).with(3) @pdf.expects(:line_width=).with(4) @pdf.expects(:line_width=).with(5) c = @pdf.cell(:content => "text", :border_width => [2, 3, 4, 5]) c.border_widths.should == [2, 3, 4, 5] end it "should set default border lines to :solid" do c = @pdf.cell(:content => "text") c.border_top_line.should == :solid c.border_right_line.should == :solid c.border_bottom_line.should == :solid c.border_left_line.should == :solid c.border_lines.should == [:solid] * 4 end it "should set border line with :border_..._line" do c = @pdf.cell(:content => "text", :border_bottom_line => :dotted) c.border_bottom_line.should == :dotted c.border_lines[2].should == :dotted end it "should set border lines with :border_lines" do c = @pdf.cell(:content => "text", :border_lines => [:solid, :dotted, :dashed, :solid]) c.border_lines.should == [:solid, :dotted, :dashed, :solid] end end describe "Text cell attributes" do include CellHelpers it "should pass through text options like :align to Text::Box" do c = cell(:content => "text", :align => :right) box = Prawn::Text::Box.new("text", :document => @pdf) Prawn::Text::Box.expects(:new).checking do |text, options| text.should == "text" options[:align].should == :right end.at_least_once.returns(box) c.draw end it "should use font_style for Text::Box#style" do c = cell(:content => "text", :font_style => :bold) box = Prawn::Text::Box.new("text", :document => @pdf) Prawn::Text::Box.expects(:new).checking do |text, options| text.should == "text" options[:style].should == :bold end.at_least_once.returns(box) c.draw end it "supports variant styles of the current font" do @pdf.font "Courier" c = cell(:content => "text", :font_style => :bold) box = Prawn::Text::Box.new("text", :document => @pdf) Prawn::Text::Box.expects(:new).checking do |text, options| text.should == "text" options[:style].should == :bold @pdf.font.family.should == 'Courier' end.at_least_once.returns(box) c.draw end it "uses the style of the current font if none given" do @pdf.font "Courier", :style => :bold c = cell(:content => "text") box = Prawn::Text::Box.new("text", :document => @pdf) Prawn::Text::Box.expects(:new).checking do |text, options| text.should == "text" @pdf.font.family.should == 'Courier' @pdf.font.options[:style].should == :bold end.at_least_once.returns(box) c.draw end it "should allow inline formatting in cells" do c = cell(:content => "foo bar baz", :inline_format => true) box = Prawn::Text::Formatted::Box.new([], :document => @pdf) Prawn::Text::Formatted::Box.expects(:new).checking do |array, options| array[0][:text].should == "foo " array[0][:styles].should == [] array[1][:text].should == "bar" array[1][:styles].should == [:bold] array[2][:text].should == " baz" array[2][:styles].should == [] end.at_least_once.returns(box) c.draw end end describe "Font handling" do include CellHelpers it "should allow only :font_style to be specified, defaulting to the " + "document's font" do c = cell(:content => "text", :font_style => :bold) c.font.name.should == 'Helvetica-Bold' end it "should accept a font name for :font" do c = cell(:content => "text", :font => 'Helvetica-Bold') c.font.name.should == 'Helvetica-Bold' end it "should allow style to be changed after initialize" do c = cell(:content => "text") c.font_style = :bold c.font.name.should == 'Helvetica-Bold' end it "should default to the document's font, if none is specified" do c = cell(:content => "text") c.font.should == @pdf.font end it "should use the metrics of the selected font (even if it is a variant " + "of the document's font) to calculate width" do c = cell(:content => "text", :font_style => :bold) font = @pdf.find_font('Helvetica-Bold') c.content_width.should == font.compute_width_of("text") end it "should properly calculate inline-formatted text" do c = cell(:content => "text", :inline_format => true) font = @pdf.find_font('Helvetica-Bold') c.content_width.should == font.compute_width_of("text") end end end describe "Image cells" do before(:each) do create_pdf end describe "with default options" do before(:each) do @cell = Prawn::Table::Cell.make(@pdf, :image => "#{Prawn::DATADIR}/images/prawn.png") end it "should create a Cell::Image" do @cell.should be_a_kind_of(Prawn::Table::Cell::Image) end it "should pull the natural width and height from the image" do @cell.natural_content_width.should == 141 @cell.natural_content_height.should == 142 end end describe "hash syntax" do before(:each) do @table = @pdf.make_table([[{ :image => "#{Prawn::DATADIR}/images/prawn.png", :scale => 2, :fit => [100, 200], :image_width => 123, :image_height => 456, :position => :center, :vposition => :center }]]) @cell = @table.cells[0, 0] end it "should create a Cell::Image" do @cell.should be_a_kind_of(Prawn::Table::Cell::Image) end it "should pass through image options" do @pdf.expects(:embed_image).checking do |_, _, options| options[:scale].should == 2 options[:fit].should == [100, 200] options[:width].should == 123 options[:height].should == 456 options[:position].should == :center options[:vposition].should == :center end @table.draw end end end prawn-table-0.2.1/spec/table_spec.rb0000644000004100000410000015224612436072751017357 0ustar www-datawww-data# encoding: utf-8 # run rspec -t issue:XYZ to run tests for a specific github issue # or rspec -t unresolved to run tests for all unresolved issues require File.join(File.expand_path(File.dirname(__FILE__)), "spec_helper") require_relative "../lib/prawn/table" require 'set' describe "Prawn::Table" do describe "converting data to Cell objects" do before(:each) do @pdf = Prawn::Document.new @table = @pdf.table([%w[R0C0 R0C1], %w[R1C0 R1C1]]) end it "should return a Prawn::Table" do @table.should be_a_kind_of Prawn::Table end it "should flatten the data into the @cells array in row-major order" do @table.cells.map { |c| c.content }.should == %w[R0C0 R0C1 R1C0 R1C1] end it "should add row and column numbers to each cell" do c = @table.cells.to_a.first c.row.should == 0 c.column.should == 0 end it "should allow empty fields" do lambda { data = [["foo","bar"],["baz",""]] @pdf.table(data) }.should_not raise_error end it "should allow a table with a header but no body" do lambda { @pdf.table([["Header"]], :header => true) }.should_not raise_error end it "should accurately count columns from data" do # First data row may contain colspan which would hide true column count data = [["Name:", {:content => "Some very long name", :colspan => 5}]] pdf = Prawn::Document.new table = Prawn::Table.new data, pdf table.column_widths.length.should == 6 end end describe "headers should allow for rowspan" do it "should remember rowspans accross multiple pages", :issue => 721 do pdf = Prawn::Document.new({:page_size => "A4", :page_layout => :portrait}) rows = [ [{:content=>"The\nNumber", :rowspan=>2}, {:content=>"Prefixed", :colspan=>2} ], ["A's", "B's"] ] (1..50).each do |n| rows.push( ["#{n}", "A#{n}", "B#{n}"] ) end pdf.table( rows, :header=>2 ) do row(0..1).style :background_color=>"FFFFCC" end #ensure that the header on page 1 is identical to the header on page 0 output = PDF::Inspector::Page.analyze(pdf.render) output.pages[0][:strings][0..4].should == output.pages[1][:strings][0..4] end it "should respect an explicit set table with", :issue => 6 do data = [[{ :content => "Current Supplier: BLINKY LIGHTS COMPANY", :colspan => 4 }], ["Current Supplier: BLINKY LIGHTS COMPANY", "611 kWh X $.090041", "$", "55.02"]] pdf = Prawn::Document.new table = Prawn::Table.new data, pdf, :width => pdf.bounds.width table.column_widths.inject{|sum,x| sum + x }.should == pdf.bounds.width end end describe "Text may be longer than the available space in a row on a single page" do it "should not glitch the layout if there is too much text to fit onto a single row on a single page", :unresolved, :issue => 562 do pdf = Prawn::Document.new({:page_size => "A4", :page_layout => :portrait}) table_data = Array.new text = 'This will be a very long text. ' * 5 table_data.push([{:content => text, :rowspan => 2}, 'b', 'c']) table_data.push(['b','c']) column_widths = [50, 60, 400] table = Prawn::Table.new table_data, pdf,:column_widths => column_widths #render the table onto the pdf table.draw #expected behavior would be for the long text to be cut off or an exception to be raised #thus we only expect a single page pdf.page_count.should == 1 end end describe "You can explicitly set the column widths and use a colspan > 1" do it "should tolerate floating point rounding errors < 0.000000001" do data=[["a", "b ", "c ", "d", "e", "f", "g", "h", "i", "j", "k", "l"], [{:content=>"Foobar", :colspan=>12}] ] #we need values with lots of decimals so that arithmetic errors will occur #the values are not arbitrary but where found converting mm to pdf pt column_widths=[137, 40, 40, 54.69291338582678, 54.69291338582678, 54.69291338582678, 54.69291338582678, 54.69291338582678, 54.69291338582678, 54.69291338582678, 54.69291338582678, 54.69291338582678] pdf = Prawn::Document.new({:page_size => 'A4', :page_layout => :landscape}) table = Prawn::Table.new data, pdf, :column_widths => column_widths table.column_widths.should == column_widths end it "should work with two different given colspans", :issue => 628 do data = [ [" ", " ", " "], [{:content=>" ", :colspan=>3}], [" ", {:content=>" ", :colspan=>2}] ] column_widths = [60, 240, 60] pdf = Prawn::Document.new #the next line raised an Prawn::Errors::CannotFit exception before issue 628 was fixed table = Prawn::Table.new data, pdf, :column_widths => column_widths table.column_widths.should == column_widths end it "should work with a colspan > 1 with given column_widths (issue #407)" do #normal entries in line 1 data = [ [ '','',''], [ { :content => "", :colspan => 3 } ], [ "", "", "" ], ] pdf = Prawn::Document.new table = Prawn::Table.new data, pdf, :column_widths => [100 , 200, 240] #colspan entry in line 1 data = [ [ { :content => "", :colspan => 3 } ], [ "", "", "" ], ] pdf = Prawn::Document.new table = Prawn::Table.new data, pdf, :column_widths => [100 , 200, 240] #mixed entries in line 1 data = [ [ { :content => "", :colspan =>2 }, "" ], [ "", "", "" ], ] pdf = Prawn::Document.new table = Prawn::Table.new data, pdf, :column_widths => [100 , 200, 240] data = [['', '', {:content => '', :colspan => 2}, '',''], ['',{:content => '', :colspan => 5}] ] pdf = Prawn::Document.new table = Prawn::Table.new data, pdf, :column_widths => [50 , 100, 50, 50, 50, 50] end it "should not increase column width when rendering a subtable", :unresolved, :issue => 612 do pdf = Prawn::Document.new first = {:content=>"Foooo fo foooooo",:width=>50,:align=>:center} second = {:content=>"Foooo",:colspan=>2,:width=>70,:align=>:center} third = {:content=>"fooooooooooo, fooooooooooooo, fooo, foooooo fooooo",:width=>50,:align=>:center} fourth = {:content=>"Bar",:width=>20,:align=>:center} table_content = [[ first, [[second],[third,fourth]] ]] table = Prawn::Table.new table_content, pdf table.column_widths.should == [50.0, 70.0] end it "illustrates issue #710", :issue => 710 do partial_width = 40 pdf = Prawn::Document.new({page_size: "LETTER", page_layout: :portrait}) col_widths = [ 50, partial_width, partial_width, partial_width, partial_width ] day_header = [{ content: "Monday, August 5th, A.S. XLIX", colspan: 5, }] times = [{ content: "Loc", colspan: 1, }, { content: "8:00", colspan: 4, }] data = [ day_header ] + [ times ] #raised a Prawn::Errors::CannotFit: #Table's width was set larger than its contents' maximum width (max width 210, requested 218.0) table = Prawn::Table.new data, pdf, :column_widths => col_widths end it "illustrate issue #533" do data = [['', '', '', '', '',''], ['',{:content => '', :colspan => 5}]] pdf = Prawn::Document.new table = Prawn::Table.new data, pdf, :column_widths => [50, 200, 40, 40, 50, 50] end it "illustrates issue #502" do pdf = Prawn::Document.new first = {:content=>"Foooo fo foooooo",:width=>50,:align=>:center} second = {:content=>"Foooo",:colspan=>2,:width=>70,:align=>:center} third = {:content=>"fooooooooooo, fooooooooooooo, fooo, foooooo fooooo",:width=>50,:align=>:center} fourth = {:content=>"Bar",:width=>20,:align=>:center} table_content = [[ first, [[second],[third,fourth]] ]] pdf.move_down(20) table = Prawn::Table.new table_content, pdf pdf.table(table_content) end #https://github.com/prawnpdf/prawn/issues/407#issuecomment-28556698 it "correctly computes column widths with empty cells + colspan" do data = [['', ''], [{:content => '', :colspan => 2}] ] pdf = Prawn::Document.new table = Prawn::Table.new data, pdf, :column_widths => [50, 200] table.column_widths.should == [50.0, 200.0] end it "illustrates a variant of problem in issue #407 - comment 28556698" do pdf = Prawn::Document.new table_data = [["a", "b", "c"], [{:content=>"d", :colspan=>3}]] column_widths = [50, 60, 400] # Before we fixed #407, this line incorrectly raise a CannotFit error pdf.table(table_data, :column_widths => column_widths) end it "should not allow oversized subtables when parent column width is constrained" do pdf = Prawn::Document.new child_1 = pdf.make_table([['foo'*100]]) child_2 = pdf.make_table([['foo']]) lambda do pdf.table([[child_1], [child_2]], column_widths: [pdf.bounds.width/2] * 2) end.should raise_error(Prawn::Errors::CannotFit) end end describe "#initialize" do before(:each) do @pdf = Prawn::Document.new end it "should instance_eval a 0-arg block" do initializer = mock() initializer.expects(:kick).once @pdf.table([["a"]]){ initializer.kick } end it "should call a 1-arg block with the document as the argument" do initializer = mock() initializer.expects(:kick).once @pdf.table([["a"]]){ |doc| doc.should be_a_kind_of(Prawn::Table); initializer.kick } end it "should proxy cell methods to #cells" do table = @pdf.table([["a"]], :cell_style => { :padding => 11 }) table.cells[0, 0].padding.should == [11, 11, 11, 11] end it "should set row and column length" do table = @pdf.table([["a", "b", "c"], ["d", "e", "f"]]) table.row_length.should == 2 table.column_length.should == 3 end it "should generate a text cell based on a String" do t = @pdf.table([["foo"]]) t.cells[0,0].should be_a_kind_of(Prawn::Table::Cell::Text) end it "should pass through a text cell" do c = Prawn::Table::Cell::Text.new(@pdf, [0,0], :content => "foo") t = @pdf.table([[c]]) t.cells[0,0].should == c end end describe "cell accessors" do before(:each) do @pdf = Prawn::Document.new @table = @pdf.table([%w[R0C0 R0C1], %w[R1C0 R1C1]]) end it "should select rows by number or range" do Set.new(@table.row(0).map { |c| c.content }).should == Set.new(%w[R0C0 R0C1]) Set.new(@table.rows(0..1).map { |c| c.content }).should == Set.new(%w[R0C0 R0C1 R1C0 R1C1]) end it "should select rows by array" do Set.new(@table.rows([0, 1]).map { |c| c.content }).should == Set.new(%w[R0C0 R0C1 R1C0 R1C1]) end it "should allow negative row selectors" do Set.new(@table.row(-1).map { |c| c.content }).should == Set.new(%w[R1C0 R1C1]) Set.new(@table.rows(-2..-1).map { |c| c.content }).should == Set.new(%w[R0C0 R0C1 R1C0 R1C1]) Set.new(@table.rows(0..-1).map { |c| c.content }).should == Set.new(%w[R0C0 R0C1 R1C0 R1C1]) end it "should select columns by number or range" do Set.new(@table.column(0).map { |c| c.content }).should == Set.new(%w[R0C0 R1C0]) Set.new(@table.columns(0..1).map { |c| c.content }).should == Set.new(%w[R0C0 R0C1 R1C0 R1C1]) end it "should select columns by array" do Set.new(@table.columns([0, 1]).map { |c| c.content }).should == Set.new(%w[R0C0 R0C1 R1C0 R1C1]) end it "should allow negative column selectors" do Set.new(@table.column(-1).map { |c| c.content }).should == Set.new(%w[R0C1 R1C1]) Set.new(@table.columns(-2..-1).map { |c| c.content }).should == Set.new(%w[R0C0 R0C1 R1C0 R1C1]) Set.new(@table.columns(0..-1).map { |c| c.content }).should == Set.new(%w[R0C0 R0C1 R1C0 R1C1]) end it "should allow rows and columns to be combined" do @table.row(0).column(1).map { |c| c.content }.should == ["R0C1"] end it "should accept a filter block, returning a cell proxy" do @table.cells.filter { |c| c.content =~ /R0/ }.column(1).map{ |c| c.content }.should == ["R0C1"] end it "should accept the [] method, returning a Cell or nil" do @table.cells[0, 0].content.should == "R0C0" @table.cells[12, 12].should be_nil end it "should proxy unknown methods to the cells" do @table.cells.height = 200 @table.row(1).height = 100 @table.cells[0, 0].height.should == 200 @table.cells[1, 0].height.should == 100 end it "should ignore non-setter methods" do lambda { @table.cells.content_width }.should raise_error(NoMethodError) end it "skips cells that don't respond to the given method" do table = @pdf.make_table([[{:content => "R0", :colspan => 2}], %w[R1C0 R1C1]]) lambda { table.row(0).font_style = :bold }.should_not raise_error end it "should accept the style method, proxying its calls to the cells" do @table.cells.style(:height => 200, :width => 200) @table.column(0).style(:width => 100) @table.cells[0, 1].width.should == 200 @table.cells[1, 0].height.should == 200 @table.cells[1, 0].width.should == 100 end it "style method should accept a block, passing each cell to be styled" do @table.cells.style { |c| c.height = 200 } @table.cells[0, 1].height.should == 200 end it "should return the width of selected columns for #width" do c0_width = @table.column(0).map{ |c| c.width }.max c1_width = @table.column(1).map{ |c| c.width }.max @table.column(0).width.should == c0_width @table.column(1).width.should == c1_width @table.columns(0..1).width.should == c0_width + c1_width @table.cells.width.should == c0_width + c1_width end it "should return the height of selected rows for #height" do r0_height = @table.row(0).map{ |c| c.height }.max r1_height = @table.row(1).map{ |c| c.height }.max @table.row(0).height.should == r0_height @table.row(1).height.should == r1_height @table.rows(0..1).height.should == r0_height + r1_height @table.cells.height.should == r0_height + r1_height end end describe "layout" do before(:each) do @pdf = Prawn::Document.new @long_text = "The quick brown fox jumped over the lazy dogs. " * 5 end describe "width" do it "should raise_error an error if the given width is outside of range" do lambda do @pdf.table([["foo"]], :width => 1) end.should raise_error(Prawn::Errors::CannotFit) lambda do @pdf.table([[@long_text]], :width => @pdf.bounds.width + 100) end.should raise_error(Prawn::Errors::CannotFit) end it "should accept the natural width for small tables" do pad = 10 # default padding @table = @pdf.table([["a"]]) @table.width.should == @table.cells[0, 0].natural_content_width + pad end it "width should == sum(column_widths)" do table = Prawn::Table.new([%w[ a b c ], %w[d e f]], @pdf) do column(0).width = 50 column(1).width = 100 column(2).width = 150 end table.width.should == 300 end it "should accept Numeric for column_widths" do table = Prawn::Table.new([%w[ a b c ], %w[d e f]], @pdf) do |t| t.column_widths = 50 end table.width.should == 150 end it "should calculate unspecified column widths as "+ "(max(string_width) + 2*horizontal_padding)" do hpad, fs = 3, 12 columns = 2 table = Prawn::Table.new( [%w[ foo b ], %w[d foobar]], @pdf, :cell_style => { :padding => hpad, :size => fs } ) col0_width = @pdf.width_of("foo", :size => fs) col1_width = @pdf.width_of("foobar", :size => fs) table.width.should == col0_width + col1_width + 2*columns*hpad end it "should allow mixing autocalculated and preset"+ "column widths within a single table" do hpad, fs = 10, 6 stretchy_columns = 2 col0_width = 50 col1_width = @pdf.width_of("foo", :size => fs) col2_width = @pdf.width_of("foobar", :size => fs) col3_width = 150 table = Prawn::Table.new( [%w[snake foo b apple], %w[kitten d foobar banana]], @pdf, :cell_style => { :padding => hpad, :size => fs }) do column(0).width = col0_width column(3).width = col3_width end table.width.should == col1_width + col2_width + 2*stretchy_columns*hpad + col0_width + col3_width end it "should preserve all manually requested column widths" do col0_width = 50 col1_width = 20 col3_width = 60 table = Prawn::Table.new( [["snake", "foo", "b", "some long, long text that will wrap"], %w[kitten d foobar banana]], @pdf, :width => 150) do column(0).width = col0_width column(1).width = col1_width column(3).width = col3_width end table.draw table.column(0).width.should == col0_width table.column(1).width.should == col1_width table.column(3).width.should == col3_width end it "should_not exceed the maximum width of the margin_box" do expected_width = @pdf.margin_box.width data = [ ['This is a column with a lot of text that should comfortably exceed '+ 'the width of a normal document margin_box width', 'Some more text', 'and then some more', 'Just a bit more to be extra sure'] ] table = Prawn::Table.new(data, @pdf) table.width.should == expected_width end it "should_not exceed the maximum width of the margin_box even with" + "manual widths specified" do expected_width = @pdf.margin_box.width data = [ ['This is a column with a lot of text that should comfortably exceed '+ 'the width of a normal document margin_box width', 'Some more text', 'and then some more', 'Just a bit more to be extra sure'] ] table = Prawn::Table.new(data, @pdf) { column(1).width = 100 } table.width.should == expected_width end it "scales down only the non-preset column widths when the natural width" + "exceeds the maximum width of the margin_box" do expected_width = @pdf.margin_box.width data = [ ['This is a column with a lot of text that should comfortably exceed '+ 'the width of a normal document margin_box width', 'Some more text', 'and then some more', 'Just a bit more to be extra sure'] ] table = Prawn::Table.new(data, @pdf) { column(1).width = 100; column(3).width = 50 } table.width.should == expected_width table.column_widths[1].should == 100 table.column_widths[3].should == 50 end it "should allow width to be reset even after it has been calculated" do @table = @pdf.table([[@long_text]]) @table.width @table.width = 100 @table.width.should == 100 end it "should shrink columns evenly when two equal columns compete" do @table = @pdf.table([["foo", @long_text], [@long_text, "foo"]]) @table.cells[0, 0].width.should == @table.cells[0, 1].width end it "should grow columns evenly when equal deficient columns compete" do @table = @pdf.table([["foo", "foobar"], ["foobar", "foo"]], :width => 500) @table.cells[0, 0].width.should == @table.cells[0, 1].width end it "should respect manual widths" do @table = @pdf.table([%w[foo bar baz], %w[baz bar foo]], :width => 500) do column(1).width = 60 end @table.column(1).width.should == 60 @table.column(0).width.should == @table.column(2).width end it "should allow table cells to be resized in block" do # if anything goes wrong, a CannotFit error will be raised @pdf.table([%w[1 2 3 4 5]]) do |t| t.width = 40 t.cells.size = 8 t.cells.padding = 0 end end it "should be the width of the :width parameter" do expected_width = 300 table = Prawn::Table.new( [%w[snake foo b apple], %w[kitten d foobar banana]], @pdf, :width => expected_width) table.width.should == expected_width end it "should_not exceed the :width option" do expected_width = 400 data = [ ['This is a column with a lot of text that should comfortably exceed '+ 'the width of a normal document margin_box width', 'Some more text', 'and then some more', 'Just a bit more to be extra sure'] ] table = Prawn::Table.new(data, @pdf, :width => expected_width) table.width.should == expected_width end it "should_not exceed the :width option even with manual widths specified" do expected_width = 400 data = [ ['This is a column with a lot of text that should comfortably exceed '+ 'the width of a normal document margin_box width', 'Some more text', 'and then some more', 'Just a bit more to be extra sure'] ] table = Prawn::Table.new(data, @pdf, :width => expected_width) do column(1).width = 100 end table.width.should == expected_width end it "should calculate unspecified column widths even " + "with colspan cells declared" do pdf = Prawn::Document.new hpad, fs = 3, 5 columns = 3 data = [ [ { :content => 'foo', :colspan => 2 }, "foobar" ], [ "foo", "foo", "foo" ] ] table = Prawn::Table.new( data, pdf, :cell_style => { :padding_left => hpad, :padding_right => hpad, :size => fs }) col0_width = pdf.width_of("foo", :size => fs) # cell 1, 0 col1_width = pdf.width_of("foo", :size => fs) # cell 1, 1 col2_width = pdf.width_of("foobar", :size => fs) # cell 0, 1 (at col 2) table.width.should == col0_width + col1_width + col2_width + 2*columns*hpad end end describe "height" do it "should set all cells in a row to the same height" do @table = @pdf.table([["foo", @long_text]]) @table.cells[0, 0].height.should == @table.cells[0, 1].height end it "should move y-position to the bottom of the table after drawing" do old_y = @pdf.y table = @pdf.table([["foo"]]) @pdf.y.should == old_y - table.height end it "should_not wrap unnecessarily" do # Test for FP errors and glitches t = @pdf.table([["Bender Bending Rodriguez"]]) h = @pdf.height_of("one line") (t.height - 10).should be < h*1.5 end it "should have a height of n rows" do data = [["foo"],["bar"],["baaaz"]] vpad = 4 origin = @pdf.y @pdf.table data, :cell_style => { :padding => vpad } table_height = origin - @pdf.y font_height = @pdf.font.height line_gap = @pdf.font.line_gap num_rows = data.length table_height.should be_within(0.001).of( num_rows * font_height + 2*vpad*num_rows ) end end describe "position" do it "should center tables with :position => :center" do @pdf.expects(:bounding_box).with do |(x, y), opts| expected = (@pdf.bounds.width - 500) / 2.0 (x - expected).abs < 0.001 end @pdf.table([["foo"]], :column_widths => 500, :position => :center) end it "should right-align tables with :position => :right" do @pdf.expects(:bounding_box).with do |(x, y), opts| expected = @pdf.bounds.width - 500 (x - expected).abs < 0.001 end @pdf.table([["foo"]], :column_widths => 500, :position => :right) end it "should accept a Numeric" do @pdf.expects(:bounding_box).with do |(x, y), opts| expected = 123 (x - expected).abs < 0.001 end @pdf.table([["foo"]], :column_widths => 500, :position => 123) end it "should raise_error an ArgumentError on unknown :position" do lambda do @pdf.table([["foo"]], :position => :bratwurst) end.should raise_error(ArgumentError) end end end describe "Multi-page tables" do it "should flow to the next page when hitting the bottom of the bounds" do Prawn::Document.new { table([["foo"]] * 30) }.page_count.should == 1 Prawn::Document.new { table([["foo"]] * 31) }.page_count.should == 2 Prawn::Document.new { table([["foo"]] * 31); table([["foo"]] * 35) }. page_count.should == 3 end it "should respect the containing bounds" do Prawn::Document.new do bounding_box([0, cursor], :width => bounds.width, :height => 72) do table([["foo"]] * 4) end end.page_count.should == 2 end it "should_not start a new page before finishing out a row" do Prawn::Document.new do table([[ (1..80).map{ |i| "Line #{i}" }.join("\n"), "Column 2" ]]) end.page_count.should == 1 end it "should only start new page on long cells if it would gain us height" do Prawn::Document.new do text "Hello" table([[ (1..80).map{ |i| "Line #{i}" }.join("\n"), "Column 2" ]]) end.page_count.should == 2 end it "should_not start a new page to gain height when at the top of " + "a bounding box, even if stretchy" do Prawn::Document.new do bounding_box([bounds.left, bounds.top - 20], :width => 400) do table([[ (1..80).map{ |i| "Line #{i}" }.join("\n"), "Column 2" ]]) end end.page_count.should == 1 end it "should still break to the next page if in a stretchy bounding box " + "but not at the top" do Prawn::Document.new do bounding_box([bounds.left, bounds.top - 20], :width => 400) do text "Hello" table([[ (1..80).map{ |i| "Line #{i}" }.join("\n"), "Column 2" ]]) end end.page_count.should == 2 end it "should only draw first-page header if the first body row fits" do pdf = Prawn::Document.new pdf.y = 60 # not enough room for a table row pdf.table [["Header"], ["Body"]], :header => true output = PDF::Inspector::Page.analyze(pdf.render) # Ensure we only drew the header once, on the second page output.pages[0][:strings].should be_empty output.pages[1][:strings].should == ["Header", "Body"] end it 'should only draw first-page header if the first multi-row fits', :issue => 707 do pdf = Prawn::Document.new pdf.y = 100 # not enough room for the header and multirow cell pdf.table [ [{content: 'Header', colspan: 2}], [{content: 'Multirow cell', rowspan: 3}, 'Line 1'], ] + (2..3).map { |i| ["Line #{i}"] }, :header => true output = PDF::Inspector::Page.analyze(pdf.render) # Ensure we only drew the header once, on the second page output.pages[0][:strings].should == [] output.pages[1][:strings].should == ['Header', 'Multirow cell', 'Line 1', 'Line 2', 'Line 3'] end context 'when the last row of first page of a table has a rowspan > 1' do it 'should move the cells below that rowspan cell to the next page' do pdf = Prawn::Document.new pdf.y = 100 # not enough room for the rowspan cell pdf.table [ ['R0C0', 'R0C1', 'R0C2'], ['R1C0', {content: 'R1C1', rowspan: 2}, 'R1C2'], ['R2C0', 'R2C2'], ] output = PDF::Inspector::Page.analyze(pdf.render) # Ensure we output the cells of row 2 on the new page only output.pages[0][:strings].should == ['R0C0', 'R0C1', 'R0C2'] output.pages[1][:strings].should == ['R1C0', 'R1C1', 'R1C2', 'R2C0', 'R2C2'] end end it "should draw background before borders, but only within pages" do seq = sequence("drawing_order") @pdf = Prawn::Document.new # give enough room for only the first row @pdf.y = @pdf.bounds.absolute_bottom + 30 t = @pdf.make_table([["A", "B"], ["C", "D"]], :cell_style => {:background_color => 'ff0000'}) ca = t.cells[0, 0] cb = t.cells[0, 1] cc = t.cells[1, 0] cd = t.cells[1, 1] # All backgrounds should draw before any borders on page 1... ca.expects(:draw_background).in_sequence(seq) cb.expects(:draw_background).in_sequence(seq) ca.expects(:draw_borders).in_sequence(seq) cb.expects(:draw_borders).in_sequence(seq) # ...and page 2 @pdf.expects(:start_new_page).in_sequence(seq) cc.expects(:draw_background).in_sequence(seq) cd.expects(:draw_background).in_sequence(seq) cc.expects(:draw_borders).in_sequence(seq) cd.expects(:draw_borders).in_sequence(seq) t.draw end describe "before_rendering_page callback" do before(:each) { @pdf = Prawn::Document.new } it "is passed all cells to be rendered on that page" do kicked = 0 @pdf.table([["foo"]] * 100) do |t| t.before_rendering_page do |page| page.row_count.should == ((kicked < 3) ? 30 : 10) page.column_count.should == 1 page.row(0).first.content.should == "foo" page.row(-1).first.content.should == "foo" kicked += 1 end end kicked.should == 4 end it "numbers cells relative to their position on page" do @pdf.table([["foo"]] * 100) do |t| t.before_rendering_page do |page| page[0, 0].content.should == "foo" end end end it "changing cells in the callback affects their rendering" do seq = sequence("render order") t = @pdf.make_table([["foo"]] * 40) do |table| table.before_rendering_page do |page| page[0, 0].background_color = "ff0000" end end t.cells[30, 0].stubs(:draw_background).checking do |xy| t.cells[30, 0].background_color.should == 'ff0000' end t.cells[31, 0].stubs(:draw_background).checking do |xy| t.cells[31, 0].background_color.should == nil end t.draw end it "passes headers on page 2+" do @pdf.table([["header"]] + [["foo"]] * 100, :header => true) do |t| t.before_rendering_page do |page| page[0, 0].content.should == "header" end end end it "updates dummy cell header rows" do header = [[{:content => "header", :colspan => 2}]] data = [["foo", "bar"]] * 31 @pdf.table(header + data, :header => true) do |t| t.before_rendering_page do |page| cell = page[0, 0] cell.dummy_cells.each {|dc| dc.row.should == cell.row } end end end it "allows headers to be changed" do seq = sequence("render order") @pdf.expects(:draw_text!).with { |t, _| t == "hdr1"}.in_sequence(seq) @pdf.expects(:draw_text!).with { |t, _| t == "foo"}.times(29).in_sequence(seq) # Verify that the changed cell doesn't mutate subsequent pages @pdf.expects(:draw_text!).with { |t, _| t == "header"}.in_sequence(seq) @pdf.expects(:draw_text!).with { |t, _| t == "foo"}.times(11).in_sequence(seq) set_first_page_headers = false @pdf.table([["header"]] + [["foo"]] * 40, :header => true) do |t| t.before_rendering_page do |page| # only change first page header page[0, 0].content = "hdr1" unless set_first_page_headers set_first_page_headers = true end end end end end describe "#style" do it "should send #style to its first argument, passing the style hash and" + " block" do stylable = stub() stylable.expects(:style).with(:foo => :bar).once.yields block = stub() block.expects(:kick).once Prawn::Document.new do table([["x"]]) { style(stylable, :foo => :bar) { block.kick } } end end it "should default to {} for the hash argument" do stylable = stub() stylable.expects(:style).with({}).once Prawn::Document.new do table([["x"]]) { style(stylable) } end end it "ignores unknown values on a cell-by-cell basis" do Prawn::Document.new do table([["x", [["y"]]]], :cell_style => {:overflow => :shrink_to_fit}) end end end describe "row_colors" do it "should allow array syntax for :row_colors" do data = [["foo"], ["bar"], ["baz"]] pdf = Prawn::Document.new t = pdf.table(data, :row_colors => ['cccccc', 'ffffff']) t.cells.map{|x| x.background_color}.should == %w[cccccc ffffff cccccc] end it "should ignore headers" do data = [["header"], ["foo"], ["bar"], ["baz"]] pdf = Prawn::Document.new t = pdf.table(data, :header => true, :row_colors => ['cccccc', 'ffffff']) do row(0).background_color = '333333' end t.cells.map{|x| x.background_color}.should == %w[333333 cccccc ffffff cccccc] end it "stripes rows consistently from page to page, skipping header rows" do data = [["header"]] + [["foo"]] * 70 pdf = Prawn::Document.new t = pdf.make_table(data, :header => true, :row_colors => ['cccccc', 'ffffff']) do cells.padding = 0 cells.size = 9 row(0).size = 11 end # page 1: header + 67 cells (odd number -- verifies that the next # page disrupts the even/odd coloring, since both the last data cell # on this page and the first one on the next are colored cccccc) Prawn::Table::Cell.expects(:draw_cells).with do |cells| cells.map { |c, (x, y)| c.background_color } == [nil] + (%w[cccccc ffffff] * 33) + %w[cccccc] end # page 2: header and 3 data cells Prawn::Table::Cell.expects(:draw_cells).with do |cells| cells.map { |c, (x, y)| c.background_color } == [nil] + %w[cccccc ffffff cccccc] end t.draw end it "should_not override an explicit background_color" do data = [["foo"], ["bar"], ["baz"]] pdf = Prawn::Document.new table = pdf.table(data, :row_colors => ['cccccc', 'ffffff']) { |t| t.cells[0, 0].background_color = 'dddddd' } table.cells.map{|x| x.background_color}.should == %w[dddddd ffffff cccccc] end end describe "inking" do before(:each) do @pdf = Prawn::Document.new end it "should set the x-position of each cell based on widths" do @table = @pdf.table([["foo", "bar", "baz"]]) x = 0 (0..2).each do |col| cell = @table.cells[0, col] cell.x.should == x x += cell.width end end it "should set the y-position of each cell based on heights" do y = 0 @table = @pdf.make_table([["foo"], ["bar"], ["baz"]]) (0..2).each do |row| cell = @table.cells[row, 0] cell.y.should be_within(0.01).of(y) y -= cell.height end end it "should output content cell by cell, row by row" do data = [["foo","bar"],["baz","bang"]] @pdf = Prawn::Document.new @pdf.table(data) output = PDF::Inspector::Text.analyze(@pdf.render) output.strings.should == data.flatten end it "should_not cause an error if rendering the very first row causes a " + "page break" do Prawn::Document.new do |pdf| arr = Array(1..5).collect{|i| ["cell #{i}"] } pdf.move_down( pdf.y - (pdf.bounds.absolute_bottom + 3) ) lambda { pdf.table(arr) }.should_not raise_error end end it "should draw all backgrounds before any borders" do # lest backgrounds overlap borders: # https://github.com/sandal/prawn/pull/226 seq = sequence("drawing_order") t = @pdf.make_table([["A", "B"]], :cell_style => {:background_color => 'ff0000'}) ca = t.cells[0, 0] cb = t.cells[0, 1] # XXX Not a perfectly general test, because it would still be acceptable # if we drew B then A ca.expects(:draw_background).in_sequence(seq) cb.expects(:draw_background).in_sequence(seq) ca.expects(:draw_borders).in_sequence(seq) cb.expects(:draw_borders).in_sequence(seq) t.draw end it "should allow multiple inkings of the same table" do pdf = Prawn::Document.new t = Prawn::Table.new([["foo"]], pdf) pdf.expects(:bounding_box).with{|(x, y), options| y.to_i == 495}.yields pdf.expects(:bounding_box).with{|(x, y), options| y.to_i == 395}.yields pdf.expects(:draw_text!).with{ |text, options| text == 'foo' }.twice pdf.move_cursor_to(500) t.draw pdf.move_cursor_to(400) t.draw end describe "in stretchy bounding boxes" do it "should draw all cells on a row at the same y-position" do pdf = Prawn::Document.new text_y = pdf.y.to_i - 5 # text starts 5pt below current y pos (padding) pdf.bounding_box([0, pdf.cursor], :width => pdf.bounds.width) do pdf.expects(:draw_text!).checking { |text, options| pdf.bounds.absolute_top.should == text_y }.times(3) pdf.table([%w[a b c]]) end end end end describe "headers" do context "single row header" do it "should add headers to output when specified" do data = [["a", "b"], ["foo","bar"],["baz","bang"]] @pdf = Prawn::Document.new @pdf.table(data, :header => true) output = PDF::Inspector::Text.analyze(@pdf.render) output.strings.should == data.flatten end it "should repeat headers across pages" do data = [["foo","bar"]] * 30 headers = ["baz","foobar"] @pdf = Prawn::Document.new @pdf.table([headers] + data, :header => true) output = PDF::Inspector::Text.analyze(@pdf.render) output.strings.should == headers + data.flatten[0..-3] + headers + data.flatten[-2..-1] end it "draws headers at the correct position" do data = [["header"]] + [["foo"]] * 40 Prawn::Table::Cell.expects(:draw_cells).times(2).checking do |cells| cells.each do |cell, pt| if cell.content == "header" # Assert that header text is drawn at the same location on each page if @header_location pt.should == @header_location else @header_location = pt end end end end @pdf = Prawn::Document.new @pdf.table(data, :header => true) end it "draws headers at the correct position with column box" do data = [["header"]] + [["foo"]] * 40 Prawn::Table::Cell.expects(:draw_cells).times(2).checking do |cells| cells.each do |cell, pt| if cell.content == "header" pt[0].should == @pdf.bounds.left end end end @pdf = Prawn::Document.new @pdf.column_box [0, @pdf.cursor], :width => @pdf.bounds.width, :columns => 2 do @pdf.table(data, :header => true) end end it "should_not draw header twice when starting new page" do @pdf = Prawn::Document.new @pdf.y = 0 @pdf.table([["Header"], ["Body"]], :header => true) output = PDF::Inspector::Text.analyze(@pdf.render) output.strings.should == ["Header", "Body"] end end context "multiple row header" do it "should add headers to output when specified" do data = [["a", "b"], ["c", "d"], ["foo","bar"],["baz","bang"]] @pdf = Prawn::Document.new @pdf.table(data, :header => 2) output = PDF::Inspector::Text.analyze(@pdf.render) output.strings.should == data.flatten end it "should repeat headers across pages" do data = [["foo","bar"]] * 30 headers = ["baz","foobar"] + ["bas", "foobaz"] @pdf = Prawn::Document.new @pdf.table([headers] + data, :header => 2) output = PDF::Inspector::Text.analyze(@pdf.render) output.strings.should == headers + data.flatten[0..-3] + headers + data.flatten[-4..-1] end it "draws headers at the correct position" do data = [["header"]] + [["header2"]] + [["foo"]] * 40 Prawn::Table::Cell.expects(:draw_cells).times(2).checking do |cells| cells.each do |cell, pt| if cell.content == "header" # Assert that header text is drawn at the same location on each page if @header_location pt.should == @header_location else @header_location = pt end end if cell.content == "header2" # Assert that header text is drawn at the same location on each page if @header2_location pt.should == @header2_location else @header2_location = pt end end end end @pdf = Prawn::Document.new @pdf.table(data, :header => 2) end it "should_not draw header twice when starting new page" do @pdf = Prawn::Document.new @pdf.y = 0 @pdf.table([["Header"], ["Header2"], ["Body"]], :header => 2) output = PDF::Inspector::Text.analyze(@pdf.render) output.strings.should == ["Header", "Header2", "Body"] end end end describe "nested tables" do before(:each) do @pdf = Prawn::Document.new @subtable = Prawn::Table.new([["foo"]], @pdf) @table = @pdf.table([[@subtable, "bar"]]) end it "can be created from an Array" do cell = Prawn::Table::Cell.make(@pdf, [["foo"]]) cell.should be_a_kind_of(Prawn::Table::Cell::Subtable) cell.subtable.should be_a_kind_of(Prawn::Table) end it "defaults its padding to zero" do @table.cells[0, 0].padding.should == [0, 0, 0, 0] end it "has a subtable accessor" do @table.cells[0, 0].subtable.should == @subtable end it "determines its dimensions from the subtable" do @table.cells[0, 0].width.should == @subtable.width @table.cells[0, 0].height.should == @subtable.height end end it "Prints table on one page when using subtable with colspan > 1", :unresolved, issue: 10 do pdf = Prawn::Document.new(margin: [ 30, 71, 55, 71]) lines = "one\ntwo\nthree\nfour" sub_table_lines = lines.split("\n").map do |line| if line == "one" [ { content: "#{line}", colspan: 2, size: 11} ] else [ { content: "\u2022"}, { content: "#{line}"} ] end end sub_table = pdf.make_table(sub_table_lines, cell_style: { border_color: '00ff00'}) #outer table pdf.table [[ { content: "Placeholder text", width: 200 }, { content: sub_table } ]], width: 515, cell_style: { border_width: 1, border_color: 'ff0000' } pdf.render pdf.page_count.should == 1 end describe "An invalid table" do before(:each) do @pdf = Prawn::Document.new @bad_data = ["Single Nested Array"] end it "should raise_error error when invalid table data is given" do lambda { @pdf.table(@bad_data) }.should raise_error(Prawn::Errors::InvalidTableData) end it "should raise_error an EmptyTableError with empty table data" do lambda { data = [] @pdf = Prawn::Document.new @pdf.table(data) }.should raise_error( Prawn::Errors::EmptyTable ) end it "should raise_error an EmptyTableError with nil table data" do lambda { data = nil @pdf = Prawn::Document.new @pdf.table(data) }.should raise_error( Prawn::Errors::EmptyTable ) end end end describe "colspan / rowspan" do before(:each) { create_pdf } it "doesn't raise an error" do lambda { @pdf.table([[{:content => "foo", :colspan => 2, :rowspan => 2}]]) }.should_not raise_error end it "colspan is properly counted" do t = @pdf.make_table([[{:content => "foo", :colspan => 2}]]) t.column_length.should == 2 end it "rowspan is properly counted" do t = @pdf.make_table([[{:content => "foo", :rowspan => 2}]]) t.row_length.should == 2 end it "raises if colspan or rowspan are called after layout" do lambda { @pdf.table([["foo"]]) { cells[0, 0].colspan = 2 } }.should raise_error(Prawn::Errors::InvalidTableSpan) lambda { @pdf.table([["foo"]]) { cells[0, 0].rowspan = 2 } }.should raise_error(Prawn::Errors::InvalidTableSpan) end it "raises when spans overlap" do lambda { @pdf.table([["foo", {:content => "bar", :rowspan => 2}], [{:content => "baz", :colspan => 2}]]) }.should raise_error(Prawn::Errors::InvalidTableSpan) end it "table and cell width account for colspan" do t = @pdf.table([["a", {:content => "b", :colspan => 2}]], :column_widths => [100, 100, 100]) spanned = t.cells[0, 1] spanned.colspan.should == 2 t.width.should == 300 t.cells.min_width.should == 300 t.cells.max_width.should == 300 spanned.width.should == 200 end it "table and cell height account for rowspan" do t = @pdf.table([["a"], [{:content => "b", :rowspan => 2}]]) do row(0..2).height = 100 end spanned = t.cells[1, 0] spanned.rowspan.should == 2 t.height.should == 300 spanned.height.should == 200 end it "provides the full content_width as drawing space" do w = @pdf.make_table([["foo"]]).cells[0, 0].content_width t = @pdf.make_table([[{:content => "foo", :colspan => 2}]]) t.cells[0, 0].spanned_content_width.should == w end it "dummy cells are not drawn" do # make a fake master cell for the dummy cell to slave to t = @pdf.make_table([[{:content => "foo", :colspan => 2}]]) # drawing just a dummy cell should_not ink @pdf.expects(:stroke_line).never @pdf.expects(:draw_text!).never Prawn::Table::Cell.draw_cells([t.cells[0, 1]]) end it "dummy cells do not add any height or width" do t1 = @pdf.table([["foo"]]) t2 = @pdf.table([[{:content => "foo", :colspan => 2}]]) t2.width.should == t1.width t3 = @pdf.table([[{:content => "foo", :rowspan => 2}]]) t3.height.should == t1.height end it "dummy cells ignored by #style" do t = @pdf.table([[{:content => "blah", :colspan => 2}]], :cell_style => { :size => 9 }) t.cells[0, 0].size.should == 9 end context "inheriting master cell styles from dummy cell" do # Relatively full coverage for all these attributes that should be # inherited. [["border_X_width", 20], ["border_X_color", "123456"], ["padding_X", 20]].each do |attribute, val| attribute_right = attribute.sub("X", "right") attribute_left = attribute.sub("X", "left") attribute_bottom = attribute.sub("X", "bottom") attribute_top = attribute.sub("X", "top") specify "#{attribute_right} of right column is inherited" do t = @pdf.table([[{:content => "blah", :colspan => 2}]]) do |table| table.column(1).send("#{attribute_right}=", val) end t.cells[0, 0].send(attribute_right).should == val end specify "#{attribute_bottom} of bottom row is inherited" do t = @pdf.table([[{:content => "blah", :rowspan => 2}]]) do |table| table.row(1).send("#{attribute_bottom}=", val) end t.cells[0, 0].send(attribute_bottom).should == val end specify "#{attribute_left} of right column is not inherited" do t = @pdf.table([[{:content => "blah", :colspan => 2}]]) do |table| table.column(1).send("#{attribute_left}=", val) end t.cells[0, 0].send(attribute_left).should_not == val end specify "#{attribute_right} of interior column is not inherited" do t = @pdf.table([[{:content => "blah", :colspan => 3}]]) do |table| table.column(1).send("#{attribute_right}=", val) end t.cells[0, 0].send(attribute_right).should_not == val end specify "#{attribute_bottom} of interior row is not inherited" do t = @pdf.table([[{:content => "blah", :rowspan => 3}]]) do |table| table.row(1).send("#{attribute_bottom}=", val) end t.cells[0, 0].send(attribute_bottom).should_not == val end specify "#{attribute_top} of bottom row is not inherited" do t = @pdf.table([[{:content => "blah", :rowspan => 2}]]) do |table| table.row(1).send("#{attribute_top}=", val) end t.cells[0, 0].send(attribute_top).should_not == val end end end it "splits natural width between cols in the group" do t = @pdf.table([[{:content => "foo", :colspan => 2}]]) widths = t.column_widths widths[0].should == widths[1] end it "splits natural width between cols when width is increased" do t = @pdf.table([[{:content => "foo", :colspan => 2}]], :width => @pdf.bounds.width) widths = t.column_widths widths[0].should == widths[1] end it "splits min-width between cols in the group" do # Since column_widths, when reducing column widths, reduces proportional to # the remaining width after each column's min width, we must ensure that the # min-width is split proportionally in order to ensure the width is still # split evenly when the width is reduced. (See "splits natural width between # cols when width is reduced".) t = @pdf.table([[{:content => "foo", :colspan => 2}]], :width => 20) t.column(0).min_width.should == t.column(1).min_width end it "splits natural width between cols when width is reduced" do t = @pdf.table([[{:content => "foo", :colspan => 2}]], :width => 20) widths = t.column_widths widths[0].should == widths[1] end it "honors a large, explicitly set table width" do t = @pdf.table([[{:content => "AAAAAAAAAA", :colspan => 3}], ["A", "B", "C"]], :width => 400) t.column_widths.inject(0) { |sum, w| sum + w }. should be_within(0.01).of(400) end it "honors a small, explicitly set table width" do t = @pdf.table([[{:content => "Lorem ipsum dolor sit amet " * 20, :colspan => 3}], ["A", "B", "C"]], :width => 200) t.column_widths.inject(0) { |sum, w| sum + w }. should be_within(0.01).of(200) end it "splits natural_content_height between rows in the group" do t = @pdf.table([[{:content => "foo", :rowspan => 2}]]) heights = t.row_heights heights[0].should == heights[1] end it "skips column numbers that have been col-spanned" do t = @pdf.table([["a", "b", {:content => "c", :colspan => 3}, "d"]]) t.cells[0, 0].content.should == "a" t.cells[0, 1].content.should == "b" t.cells[0, 2].content.should == "c" t.cells[0, 3].should be_a_kind_of(Prawn::Table::Cell::SpanDummy) t.cells[0, 4].should be_a_kind_of(Prawn::Table::Cell::SpanDummy) t.cells[0, 5].content.should == "d" end it "skips row/col positions that have been row-spanned" do t = @pdf.table([["a", {:content => "b", :colspan => 2, :rowspan => 2}, "c"], ["d", "e"], ["f", "g", "h", "i"]]) t.cells[0, 0].content.should == "a" t.cells[0, 1].content.should == "b" t.cells[0, 2].should be_a_kind_of(Prawn::Table::Cell::SpanDummy) t.cells[0, 3].content.should == "c" t.cells[1, 0].content.should == "d" t.cells[1, 1].should be_a_kind_of(Prawn::Table::Cell::SpanDummy) t.cells[1, 2].should be_a_kind_of(Prawn::Table::Cell::SpanDummy) t.cells[1, 3].content.should == "e" t.cells[2, 0].content.should == "f" t.cells[2, 1].content.should == "g" t.cells[2, 2].content.should == "h" t.cells[2, 3].content.should == "i" end it 'illustrates issue #20', issue: 20 do pdf = Prawn::Document.new description = "one\ntwo\nthree" bullets = description.split("\n") bullets.each_with_index do |bullet, ndx| rows = [[]] if ndx < 1 rows << [ { content: "blah blah blah", colspan: 2, font_style: :bold, size: 12, padding_bottom: 1 }] else rows << [ { content: bullet, width: 440, padding_top: 0, align: :justify } ] end pdf.table(rows, header: true, cell_style: { border_width: 0, inline_format: true }) end pdf.render end it 'illustrates issue #20 (2) and #22', issue: 22 do pdf = Prawn::Document.new pdf.table [['one', 'two']], position: :center pdf.table [['three', 'four']], position: :center pdf.render pdf.page_count.should == 1 end end prawn-table-0.2.1/spec/table/0000755000004100000410000000000012436072751016006 5ustar www-datawww-dataprawn-table-0.2.1/spec/table/span_dummy_spec.rb0000644000004100000410000000077212436072751021527 0ustar www-datawww-data# encoding: utf-8 require File.join(File.expand_path(File.dirname(__FILE__)), "..", "spec_helper") require 'set' describe "Prawn::Table::Cell::SpanDummy" do before(:each) do @pdf = Prawn::Document.new @table = @pdf.table([[{:content => "Row", :colspan => 2}]]) @master_cell = @table.cells[0,0] @span_dummy = @master_cell.dummy_cells.first end it "delegates background_color to the master cell" do @span_dummy.background_color.should == @master_cell.background_color end end prawn-table-0.2.1/spec/extensions/0000755000004100000410000000000012436072751017116 5ustar www-datawww-dataprawn-table-0.2.1/spec/extensions/mocha.rb0000644000004100000410000000231112436072751020527 0ustar www-datawww-data# encoding: utf-8 # Allow speccing things when an expectation matcher runs. Similar to #with, but # always succeeds. # # @pdf.expects(:stroke_line).checking do |from, to| # @pdf.map_to_absolute(from).should == [0, 0] # end # # Note that the outer expectation does *not* fail only because the inner one # does; in the above example, the outer expectation would only fail if # stroke_line were not called. class ParameterChecker < Mocha::ParametersMatcher def initialize(&matching_block) @expected_parameters = [Mocha::ParameterMatchers::AnyParameters.new] @matching_block = matching_block end def match?(actual_parameters = []) @matching_block.call(*actual_parameters) true # always succeed end end class Mocha::Expectation def checking(&block) @parameters_matcher = ParameterChecker.new(&block) self end end # Equivalent to expects(method_name).at_least(0). More useful when combined # with parameter matchers to ignore certain calls for the sake of parameter # matching. # # @pdf.ignores(:stroke_color=).with("000000") # @pdf.expects(:stroke_color=).with("ff0000") # module Mocha::ObjectMethods def ignores(method_name) expects(method_name).at_least(0) end end prawn-table-0.2.1/spec/extensions/encoding_helpers.rb0000644000004100000410000000030712436072751022753 0ustar www-datawww-data# encoding: utf-8 module EncodingHelpers def win1252_string(str) str.force_encoding(Encoding::Windows_1252) end def bin_string(str) str.force_encoding(Encoding::ASCII_8BIT) end end prawn-table-0.2.1/lib/0000755000004100000410000000000012436072751014533 5ustar www-datawww-dataprawn-table-0.2.1/lib/prawn/0000755000004100000410000000000012436072751015662 5ustar www-datawww-dataprawn-table-0.2.1/lib/prawn/table.rb0000644000004100000410000006070712436072751017310 0ustar www-datawww-data# encoding: utf-8 # # table.rb: Table drawing functionality. # # Copyright December 2009, Brad Ediger. All rights reserved. # # This is free software. Please see the LICENSE and COPYING files for details. require_relative 'table/column_width_calculator' require_relative 'table/cell' require_relative 'table/cells' require_relative 'table/cell/in_table' require_relative 'table/cell/text' require_relative 'table/cell/subtable' require_relative 'table/cell/image' require_relative 'table/cell/span_dummy' module Prawn module Errors # This error is raised when table data is malformed # InvalidTableData = Class.new(StandardError) # This error is raised when an empty or nil table is rendered # EmptyTable = Class.new(StandardError) end # Next-generation table drawing for Prawn. # # = Data # # Data, for a Prawn table, is a two-dimensional array of objects that can be # converted to cells ("cellable" objects). Cellable objects can be: # # String:: # Produces a text cell. This is the most common usage. # Prawn::Table::Cell:: # If you have already built a Cell or have a custom subclass of Cell you # want to use in a table, you can pass through Cell objects. # Prawn::Table:: # Creates a subtable (a table within a cell). You can use # Prawn::Document#make_table to create a table for use as a subtable # without immediately drawing it. See examples/table/bill.rb for a # somewhat complex use of subtables. # Array:: # Creates a simple subtable. Create a Table object using make_table (see # above) if you need more control over the subtable's styling. # # = Options # # Prawn/Layout provides many options to control style and layout of your # table. These options are implemented with a uniform interface: the +:foo+ # option always sets the +foo=+ accessor. See the accessor and method # documentation for full details on the options you can pass. Some # highlights: # # +cell_style+:: # A hash of style options to style all cells. See the documentation on # Prawn::Table::Cell for all cell style options. # +header+:: # If set to +true+, the first row will be repeated on every page. If set # to an Integer, the first +x+ rows will be repeated on every page. Row # numbering (for styling and other row-specific options) always indexes # based on your data array. Whether or not you have a header, row(n) always # refers to the nth element (starting from 0) of the +data+ array. # +column_widths+:: # Sets widths for individual columns. Manually setting widths can give # better results than letting Prawn guess at them, as Prawn's algorithm # for defaulting widths is currently pretty boneheaded. If you experience # problems like weird column widths or CannotFit errors, try manually # setting widths on more columns. # +position+:: # Either :left (the default), :center, :right, or a number. Specifies the # horizontal position of the table within its bounding box. If a number is # provided, it specifies the distance in points from the left edge. # # = Initializer Block # # If a block is passed to methods that initialize a table # (Prawn::Table.new, Prawn::Document#table, Prawn::Document#make_table), it # will be called after cell setup but before layout. This is a very flexible # way to specify styling and layout constraints. This code sets up a table # where the second through the fourth rows (1-3, indexed from 0) are each one # inch (72 pt) wide: # # pdf.table(data) do |table| # table.rows(1..3).width = 72 # end # # As with Prawn::Document#initialize, if the block has no arguments, it will # be evaluated in the context of the object itself. The above code could be # rewritten as: # # pdf.table(data) do # rows(1..3).width = 72 # end # class Table module Interface # @group Experimental API # Set up and draw a table on this document. A block can be given, which will # be run after cell setup but before layout and drawing. # # See the documentation on Prawn::Table for details on the arguments. # def table(data, options={}, &block) t = Table.new(data, self, options, &block) t.draw t end # Set up, but do not draw, a table. Useful for creating subtables to be # inserted into another Table. Call +draw+ on the resulting Table to ink it. # # See the documentation on Prawn::Table for details on the arguments. # def make_table(data, options={}, &block) Table.new(data, self, options, &block) end end # Set up a table on the given document. Arguments: # # +data+:: # A two-dimensional array of cell-like objects. See the "Data" section # above for the types of objects that can be put in a table. # +document+:: # The Prawn::Document instance on which to draw the table. # +options+:: # A hash of attributes and values for the table. See the "Options" block # above for details on available options. # def initialize(data, document, options={}, &block) @pdf = document @cells = make_cells(data) @header = false options.each { |k, v| send("#{k}=", v) } if block block.arity < 1 ? instance_eval(&block) : block[self] end set_column_widths set_row_heights position_cells end # Number of rows in the table. # attr_reader :row_length # Number of columns in the table. # attr_reader :column_length # Manually set the width of the table. # attr_writer :width # Position (:left, :right, :center, or a number indicating distance in # points from the left edge) of the table within its parent bounds. # attr_writer :position # Returns a Prawn::Table::Cells object representing all of the cells in # this table. # attr_reader :cells # Specify a callback to be called before each page of cells is rendered. # The block is passed a Cells object containing all cells to be rendered on # that page. You can change styling of the cells in this block, but keep in # mind that the cells have already been positioned and sized. # def before_rendering_page(&block) @before_rendering_page = block end # Returns the width of the table in PDF points. # def width @width ||= [natural_width, @pdf.bounds.width].min end # Sets column widths for the table. The argument can be one of the following # types: # # +Array+:: # [w0, w1, w2, ...] (specify a width for each column) # +Hash+:: # {0 => w0, 1 => w1, ...} (keys are column names, values are # widths) # +Numeric+:: # +72+ (sets width for all columns) # def column_widths=(widths) case widths when Array widths.each_with_index { |w, i| column(i).width = w } when Hash widths.each { |i, w| column(i).width = w } when Numeric cells.width = widths else raise ArgumentError, "cannot interpret column widths" end end # Returns the height of the table in PDF points. # def height cells.height end # If +true+, designates the first row as a header row to be repeated on # every page. If an integer, designates the number of rows to be treated # as a header Does not change row numbering -- row numbers always index # into the data array provided, with no modification. # attr_writer :header # Accepts an Array of alternating row colors to stripe the table. # attr_writer :row_colors # Sets styles for all cells. # # pdf.table(data, :cell_style => { :borders => [:left, :right] }) # def cell_style=(style_hash) cells.style(style_hash) end # Allows generic stylable content. This is an alternate syntax that some # prefer to the attribute-based syntax. This code using style: # # pdf.table(data) do # style(row(0), :background_color => 'ff00ff') # style(column(0)) { |c| c.border_width += 1 } # end # # is equivalent to: # # pdf.table(data) do # row(0).style :background_color => 'ff00ff' # column(0).style { |c| c.border_width += 1 } # end # def style(stylable, style_hash={}, &block) stylable.style(style_hash, &block) end # Draws the table onto the document at the document's current y-position. # def draw with_position do # Reference bounds are the non-stretchy bounds used to decide when to # flow to a new column / page. ref_bounds = @pdf.reference_bounds # Determine whether we're at the top of the current bounds (margin box or # bounding box). If we're at the top, we couldn't gain any more room by # breaking to the next page -- this means, in particular, that if the # first row is taller than the margin box, we will only move to the next # page if we're below the top. Some floating-point tolerance is added to # the calculation. # # Note that we use the actual bounds, not the reference bounds. This is # because even if we are in a stretchy bounding box, flowing to the next # page will not buy us any space if we are at the top. # # initial_row_on_initial_page may return 0 (already at the top OR created # a new page) or -1 (enough space) started_new_page_at_row = initial_row_on_initial_page # The cell y-positions are based on an infinitely long canvas. The offset # keeps track of how much we have to add to the original, theoretical # y-position to get to the actual position on the current page. offset = @pdf.y # Duplicate each cell of the header row into @header_row so it can be # modified in before_rendering_page callbacks. @header_row = header_rows if @header # Track cells to be drawn on this page. They will all be drawn when this # page is finished. cells_this_page = [] @cells.each do |cell| if start_new_page?(cell, offset, ref_bounds) # draw cells on the current page and then start a new one # this will also add a header to the new page if a header is set # reset array of cells for the new page cells_this_page, offset = ink_and_draw_cells_and_start_new_page(cells_this_page, cell) # remember the current row for background coloring started_new_page_at_row = cell.row end # Set background color, if any. cell = set_background_color(cell, started_new_page_at_row) # add the current cell to the cells array for the current page cells_this_page << [cell, [cell.relative_x, cell.relative_y(offset)]] end # Draw the last page of cells ink_and_draw_cells(cells_this_page) @pdf.move_cursor_to(@cells.last.relative_y(offset) - @cells.last.height) end end # Calculate and return the constrained column widths, taking into account # each cell's min_width, max_width, and any user-specified constraints on # the table or column size. # # Because the natural widths can be silly, this does not always work so well # at guessing a good size for columns that have vastly different content. If # you see weird problems like CannotFit errors or shockingly bad column # sizes, you should specify more column widths manually. # def column_widths @column_widths ||= begin if width - cells.min_width < -Prawn::FLOAT_PRECISION raise Errors::CannotFit, "Table's width was set too small to contain its contents " + "(min width #{cells.min_width}, requested #{width})" end if width - cells.max_width > Prawn::FLOAT_PRECISION raise Errors::CannotFit, "Table's width was set larger than its contents' maximum width " + "(max width #{cells.max_width}, requested #{width})" end if width - natural_width < -Prawn::FLOAT_PRECISION # Shrink the table to fit the requested width. f = (width - cells.min_width).to_f / (natural_width - cells.min_width) (0...column_length).map do |c| min, nat = column(c).min_width, natural_column_widths[c] (f * (nat - min)) + min end elsif width - natural_width > Prawn::FLOAT_PRECISION # Expand the table to fit the requested width. f = (width - cells.width).to_f / (cells.max_width - cells.width) (0...column_length).map do |c| nat, max = natural_column_widths[c], column(c).max_width (f * (max - nat)) + nat end else natural_column_widths end end end # Returns an array with the height of each row. # def row_heights @natural_row_heights ||= begin heights_by_row = Hash.new(0) cells.each do |cell| next if cell.is_a?(Cell::SpanDummy) # Split the height of row-spanned cells evenly by rows height_per_row = cell.height.to_f / cell.rowspan cell.rowspan.times do |i| heights_by_row[cell.row + i] = [heights_by_row[cell.row + i], height_per_row].max end end heights_by_row.sort_by { |row, _| row }.map { |_, h| h } end end protected # sets the background color (if necessary) for the given cell def set_background_color(cell, started_new_page_at_row) if defined?(@row_colors) && @row_colors && (!@header || cell.row > 0) # Ensure coloring restarts on every page (to make sure the header # and first row of a page are not colored the same way). rows = number_of_header_rows index = cell.row - [started_new_page_at_row, rows].max cell.background_color ||= @row_colors[index % @row_colors.length] end cell end # number of rows of the header # @return [Integer] the number of rows of the header def number_of_header_rows # header may be set to any integer value -> number of rows if @header.is_a? Integer return @header # header may be set to true -> first row is repeated elsif @header return 1 end # defaults to 0 header rows 0 end # should we start a new page? (does the current row fail to fit on this page) def start_new_page?(cell, offset, ref_bounds) # we only need to run this test on the first cell in a row # check if the rows height fails to fit on the page # check if the row is not the first on that page (wouldn't make sense to go to next page in this case) (cell.column == 0 && cell.row > 0 && !row(cell.row).fits_on_current_page?(offset, ref_bounds)) end # ink cells and then draw them def ink_and_draw_cells(cells_this_page, draw_cells = true) ink_cells(cells_this_page) Cell.draw_cells(cells_this_page) if draw_cells end # ink and draw cells, then start a new page def ink_and_draw_cells_and_start_new_page(cells_this_page, cell) # don't draw only a header draw_cells = (@header_row.nil? || cells_this_page.size > @header_row.size) ink_and_draw_cells(cells_this_page, draw_cells) # start a new page or column @pdf.bounds.move_past_bottom offset = (@pdf.y - cell.y) cells_next_page = [] header_height = add_header(cell.row, cells_next_page) # account for header height in newly generated offset offset -= header_height # reset cells_this_page in calling function and return new offset return cells_next_page, offset end # Ink all cells on the current page def ink_cells(cells_this_page) if defined?(@before_rendering_page) && @before_rendering_page c = Cells.new(cells_this_page.map { |ci, _| ci }) @before_rendering_page.call(c) end end # Determine whether we're at the top of the current bounds (margin box or # bounding box). If we're at the top, we couldn't gain any more room by # breaking to the next page -- this means, in particular, that if the # first row is taller than the margin box, we will only move to the next # page if we're below the top. Some floating-point tolerance is added to # the calculation. # # Note that we use the actual bounds, not the reference bounds. This is # because even if we are in a stretchy bounding box, flowing to the next # page will not buy us any space if we are at the top. # @return [Integer] 0 (already at the top OR created a new page) or -1 (enough space) def initial_row_on_initial_page # we're at the top of our bounds return 0 if fits_on_page?(@pdf.bounds.height) needed_height = row(0..number_of_header_rows).height # have we got enough room to fit the first row (including header row(s)) use_reference_bounds = true return -1 if fits_on_page?(needed_height, use_reference_bounds) # If there isn't enough room left on the page to fit the first data row # (including the header), start the table on the next page. @pdf.bounds.move_past_bottom # we are at the top of a new page 0 end # do we have enough room to fit a given height on to the current page? def fits_on_page?(needed_height, use_reference_bounds = false) if use_reference_bounds bounds = @pdf.reference_bounds else bounds = @pdf.bounds end needed_height < @pdf.y - (bounds.absolute_bottom - Prawn::FLOAT_PRECISION) end # return the header rows # @api private def header_rows header_rows = Cells.new number_of_header_rows.times do |r| row(r).each { |cell| header_rows[cell.row, cell.column] = cell.dup } end header_rows end # Converts the array of cellable objects given into instances of # Prawn::Table::Cell, and sets up their in-table properties so that they # know their own position in the table. # def make_cells(data) assert_proper_table_data(data) cells = Cells.new row_number = 0 data.each do |row_cells| column_number = 0 row_cells.each do |cell_data| # If we landed on a spanned cell (from a rowspan above), continue # until we find an empty spot. column_number += 1 until cells[row_number, column_number].nil? # Build the cell and store it in the Cells collection. cell = Cell.make(@pdf, cell_data) cells[row_number, column_number] = cell # Add dummy cells for the rest of the cells in the span group. This # allows Prawn to keep track of the horizontal and vertical space # occupied in each column and row spanned by this cell, while still # leaving the master (top left) cell in the group responsible for # drawing. Dummy cells do not put ink on the page. cell.rowspan.times do |i| cell.colspan.times do |j| next if i == 0 && j == 0 # It is an error to specify spans that overlap; catch this here if cells[row_number + i, column_number + j] raise Prawn::Errors::InvalidTableSpan, "Spans overlap at row #{row_number + i}, " + "column #{column_number + j}." end dummy = Cell::SpanDummy.new(@pdf, cell) cells[row_number + i, column_number + j] = dummy cell.dummy_cells << dummy end end column_number += cell.colspan end row_number += 1 end # Calculate the number of rows and columns in the table, taking into # account that some cells may span past the end of the physical cells we # have. @row_length = cells.map do |cell| cell.row + cell.rowspan end.max @column_length = cells.map do |cell| cell.column + cell.colspan end.max cells end def add_header(row_number, cells_this_page) x_offset = @pdf.bounds.left_side - @pdf.bounds.absolute_left header_height = 0 if row_number > 0 && @header y_coord = @pdf.cursor number_of_header_rows.times do |h| additional_header_height = add_one_header_row(cells_this_page, x_offset, y_coord-header_height, row_number-1, h) header_height += additional_header_height end end header_height end # Add the header row(s) to the given array of cells at the given y-position. # Number the row with the given +row+ index, so that the header appears (in # any Cells built for this page) immediately prior to the first data row on # this page. # # Return the height of the header. # def add_one_header_row(page_of_cells, x_offset, y, row, row_of_header=nil) rows_to_operate_on = @header_row rows_to_operate_on = @header_row.rows(row_of_header) if row_of_header rows_to_operate_on.each do |cell| cell.row = row cell.dummy_cells.each {|c| if cell.rowspan > 1 # be sure to account for cells that span multiple rows # in this case you need multiple row numbers c.row += row else c.row = row end } page_of_cells << [cell, [cell.x + x_offset, y]] end rows_to_operate_on.height end # Raises an error if the data provided cannot be converted into a valid # table. # def assert_proper_table_data(data) if data.nil? || data.empty? raise Prawn::Errors::EmptyTable, "data must be a non-empty, non-nil, two dimensional array " + "of cell-convertible objects" end unless data.all? { |e| Array === e } raise Prawn::Errors::InvalidTableData, "data must be a two dimensional array of cellable objects" end end # Returns an array of each column's natural (unconstrained) width. # def natural_column_widths @natural_column_widths ||= ColumnWidthCalculator.new(cells).natural_widths end # Returns the "natural" (unconstrained) width of the table. This may be # extremely silly; for example, the unconstrained width of a paragraph of # text is the width it would assume if it were not wrapped at all. Could be # a mile long. # def natural_width @natural_width ||= natural_column_widths.inject(0, &:+) end # Assigns the calculated column widths to each cell. This ensures that each # cell in a column is the same width. After this method is called, # subsequent calls to column_widths and width should return the finalized # values that will be used to ink the table. # def set_column_widths column_widths.each_with_index do |w, col_num| column(col_num).width = w end end # Assigns the row heights to each cell. This ensures that every cell in a # row is the same height. # def set_row_heights row_heights.each_with_index { |h, row_num| row(row_num).height = h } end # Set each cell's position based on the widths and heights of cells # preceding it. # def position_cells # Calculate x- and y-positions as running sums of widths / heights. x_positions = column_widths.inject([0]) { |ary, x| ary << (ary.last + x); ary }[0..-2] x_positions.each_with_index { |x, i| column(i).x = x } # y-positions assume an infinitely long canvas starting at zero -- this # is corrected for in Table#draw, and page breaks are properly inserted. y_positions = row_heights.inject([0]) { |ary, y| ary << (ary.last - y); ary}[0..-2] y_positions.each_with_index { |y, i| row(i).y = y } end # Sets up a bounding box to position the table according to the specified # :position option, and yields. # def with_position x = case defined?(@position) && @position || :left when :left then return yield when :center then (@pdf.bounds.width - width) / 2.0 when :right then @pdf.bounds.width - width when Numeric then @position else raise ArgumentError, "unknown position #{@position.inspect}" end dy = @pdf.bounds.absolute_top - @pdf.y final_y = nil @pdf.bounding_box([x, @pdf.bounds.top], :width => width) do @pdf.move_down dy yield final_y = @pdf.y end @pdf.y = final_y end end end Prawn::Document.extensions << Prawn::Table::Interface prawn-table-0.2.1/lib/prawn/table/0000755000004100000410000000000012436072751016751 5ustar www-datawww-dataprawn-table-0.2.1/lib/prawn/table/column_width_calculator.rb0000644000004100000410000001614412436072751024211 0ustar www-datawww-data# encoding: utf-8 module Prawn class Table # @private class ColumnWidthCalculator def initialize(cells) @cells = cells @widths_by_column = Hash.new(0) @rows_with_a_span_dummy = Hash.new(false) #calculate for each row if it includes a Cell:SpanDummy @cells.each do |cell| @rows_with_a_span_dummy[cell.row] = true if cell.is_a?(Cell::SpanDummy) end end # does this row include a Cell:SpanDummy? # # @param row - the row that should be checked for Cell:SpanDummy elements # def has_a_span_dummy?(row) @rows_with_a_span_dummy[row] end # helper method # column widths are stored in the values array # a cell may span cells whose value is only partly given # this function handles this special case # # @param values - The columns widths calculated up until now # @param cell - The current cell # @param index - The current column # @param meth - Meth (min/max); used to calculate values to be filled # def fill_values_if_needed(values, cell, index, meth) #have all spanned indices been filled with a value? #e.g. values[0], values[1] and values[2] don't return nil given a index of 0 and a colspan of 3 number_of_nil_values = 0 cell.colspan.times do |i| number_of_nil_values += 1 if values[index+i].nil? end #nothing to do? because #a) all values are filled return values if number_of_nil_values == 0 #b) no values are filled return values if number_of_nil_values == cell.colspan #c) I am not sure why this line is needed FIXXME #some test cases manage to this line even though there is no dummy cell in the row #I'm not sure if this is a sign for a further underlying bug. return values unless has_a_span_dummy?(cell.row) #fill up the values array #calculate the new sum new_sum = cell.send(meth) * cell.colspan #substract any calculated values cell.colspan.times do |i| new_sum -= values[index+i] unless values[index+i].nil? end #calculate value for the remaining - not yet filled - cells. new_value = new_sum.to_f / number_of_nil_values #fill the not yet filled cells cell.colspan.times do |i| values[index+i] = new_value if values[index+i].nil? end return values end def natural_widths #calculate natural column width for all rows that do not include a span dummy @cells.each do |cell| unless has_a_span_dummy?(cell.row) @widths_by_column[cell.column] = [@widths_by_column[cell.column], cell.width.to_f].max end end #integrate natural column widths for all rows that do include a span dummy @cells.each do |cell| next unless has_a_span_dummy?(cell.row) #the width of a SpanDummy cell will be calculated by the "mother" cell next if cell.is_a?(Cell::SpanDummy) if cell.colspan == 1 @widths_by_column[cell.column] = [@widths_by_column[cell.column], cell.width.to_f].max else #calculate the current with of all cells that will be spanned by the current cell current_width_of_spanned_cells = @widths_by_column.to_a[cell.column..(cell.column + cell.colspan - 1)] .collect{|key, value| value}.inject(0, :+) #update the Hash only if the new with is at least equal to the old one #due to arithmetic errors we need to ignore a small difference in the new and the old sum #the same had to be done in the column_widht_calculator#natural_width update_hash = ((cell.width.to_f - current_width_of_spanned_cells) > Prawn::FLOAT_PRECISION) if update_hash # Split the width of colspanned cells evenly by columns width_per_column = cell.width.to_f / cell.colspan # Update the Hash cell.colspan.times do |i| @widths_by_column[cell.column + i] = width_per_column end end end end @widths_by_column.sort_by { |col, _| col }.map { |_, w| w } end # get column widths (either min or max depending on meth) # used in cells.rb # # @param row_or_column - you may call this on either rows or columns # @param meth - min/max # @param aggregate - functions from cell.rb to be used to aggregate e.g. avg_spanned_min_width # def aggregate_cell_values(row_or_column, meth, aggregate) values = {} #calculate values for all cells that do not span accross multiple cells #this ensures that we don't have a problem if the first line includes #a cell that spans across multiple cells @cells.each do |cell| #don't take spanned cells if cell.colspan == 1 and cell.class != Prawn::Table::Cell::SpanDummy index = cell.send(row_or_column) values[index] = [values[index], cell.send(meth)].compact.send(aggregate) end end # if there are only colspanned or rowspanned cells in a table spanned_width_needs_fixing = true @cells.each do |cell| index = cell.send(row_or_column) if cell.colspan > 1 #special treatment if some but not all spanned indices in the values array have been calculated #only applies to rows values = fill_values_if_needed(values, cell, index, meth) if row_or_column == :column #calculate current (old) return value before we do anything old_sum = 0 cell.colspan.times { |i| old_sum += values[index+i] unless values[index+i].nil? } #calculate future return value new_sum = cell.send(meth) * cell.colspan #due to float rounding errors we need to ignore a small difference in the new #and the old sum the same had to be done in #the column_width_calculator#natural_width spanned_width_needs_fixing = ((new_sum - old_sum) > Prawn::FLOAT_PRECISION) if spanned_width_needs_fixing #not entirely sure why we need this line, but with it the tests pass values[index] = [values[index], cell.send(meth)].compact.send(aggregate) #overwrite the old values with the new ones, but only if all entries existed entries_exist = true cell.colspan.times { |i| entries_exist = false if values[index+i].nil? } cell.colspan.times { |i| values[index+i] = cell.send(meth) if entries_exist } end else if spanned_width_needs_fixing && cell.class == Prawn::Table::Cell::SpanDummy values[index] = [values[index], cell.send(meth)].compact.send(aggregate) end end end return values.values.inject(0, &:+) end end end end prawn-table-0.2.1/lib/prawn/table/cell/0000755000004100000410000000000012436072751017670 5ustar www-datawww-dataprawn-table-0.2.1/lib/prawn/table/cell/text.rb0000644000004100000410000001144212436072751021203 0ustar www-datawww-data# encoding: utf-8 # text.rb: Text table cells. # # Copyright December 2009, Gregory Brown and Brad Ediger. All Rights Reserved. # # This is free software. Please see the LICENSE and COPYING files for details. module Prawn class Table class Cell # A Cell that contains text. Has some limited options to set font family, # size, and style. # # @private class Text < Cell TextOptions = [:inline_format, :kerning, :size, :align, :valign, :rotate, :rotate_around, :leading, :single_line, :skip_encoding, :overflow, :min_font_size] TextOptions.each do |option| define_method("#{option}=") { |v| @text_options[option] = v } define_method(option) { @text_options[option] } end attr_writer :font, :text_color def initialize(pdf, point, options={}) @text_options = {} super end # Returns the font that will be used to draw this cell. # def font with_font { @pdf.font } end # Sets the style of the font in use. Equivalent to the Text::Box # +style+ option, but we already have a style method. # def font_style=(style) @text_options[:style] = style end # Returns the width of this text with no wrapping. This will be far off # from the final width if the text is long. # def natural_content_width @natural_content_width ||= [styled_width_of(@content), @pdf.bounds.width].min end # Returns the natural height of this block of text, wrapped to the # preset width. # def natural_content_height with_font do b = text_box(:width => spanned_content_width + FPTolerance) b.render(:dry_run => true) b.height + b.line_gap end end # Draws the text content into its bounding box. # def draw_content with_font do @pdf.move_down((@pdf.font.line_gap + @pdf.font.descender)/2) with_text_color do text_box(:width => spanned_content_width + FPTolerance, :height => spanned_content_height + FPTolerance, :at => [0, @pdf.cursor]).render end end end def set_width_constraints # Sets a reasonable minimum width. If the cell has any content, make # sure we have enough width to be at least one character wide. This is # a bit of a hack, but it should work well enough. unless defined?(@min_width) && @min_width min_content_width = [natural_content_width, styled_width_of_single_character].min @min_width = padding_left + padding_right + min_content_width super end end protected def with_font @pdf.save_font do options = {} options[:style] = @text_options[:style] if @text_options[:style] options[:style] ||= @pdf.font.options[:style] if @pdf.font.options[:style] @pdf.font(defined?(@font) && @font || @pdf.font.family, options) yield end end def with_text_color if defined?(@text_color) && @text_color begin old_color = @pdf.fill_color || '000000' @pdf.fill_color(@text_color) yield ensure @pdf.fill_color(old_color) end else yield end end def text_box(extra_options={}) if p = @text_options[:inline_format] p = [] unless p.is_a?(Array) options = @text_options.dup options.delete(:inline_format) options.merge!(extra_options) options[:document] = @pdf array = @pdf.text_formatter.format(@content, *p) ::Prawn::Text::Formatted::Box.new(array, options.merge(extra_options).merge(:document => @pdf)) else ::Prawn::Text::Box.new(@content, @text_options.merge(extra_options). merge(:document => @pdf)) end end # Returns the width of +text+ under the given text options. # def styled_width_of(text) @pdf.width_of(text, @text_options) end private # Returns the greatest possible width of any single character # under the given text options. # (We use this to determine the minimum width of a table cell) # (Although we currently determine this by measuring "M", it should really # use whichever character is widest under the current font) # def styled_width_of_single_character styled_width_of("M") end end end end end prawn-table-0.2.1/lib/prawn/table/cell/subtable.rb0000644000004100000410000000243112436072751022016 0ustar www-datawww-data# encoding: utf-8 # subtable.rb: Yo dawg. # # Copyright January 2010, Brad Ediger. All Rights Reserved. # # This is free software. Please see the LICENSE and COPYING files for details. module Prawn class Table class Cell # A Cell that contains another table. # # @private class Subtable < Cell attr_reader :subtable def initialize(pdf, point, options={}) super @subtable = options[:content] # Subtable padding defaults to zero @padding = [0, 0, 0, 0] end # Sets the text color of the entire subtable. # def text_color=(color) @subtable.cells.text_color = color end # Proxied to subtable. # def natural_content_width @subtable.cells.width end # Proxied to subtable. # def min_width @subtable.cells.min_width end # Proxied to subtable. # def max_width @subtable.cells.max_width end # Proxied to subtable. # def natural_content_height @subtable.cells.height end # Draws the subtable. # def draw_content @subtable.draw end end end end end prawn-table-0.2.1/lib/prawn/table/cell/span_dummy.rb0000644000004100000410000000432512436072751022375 0ustar www-datawww-data# encoding: utf-8 # span_dummy.rb: Placeholder for non-master spanned cells. # # Copyright December 2011, Brad Ediger. All Rights Reserved. # # This is free software. Please see the LICENSE and COPYING files for details. module Prawn class Table class Cell # A Cell object used to represent all but the topmost cell in a span # group. # # @private class SpanDummy < Cell def initialize(pdf, master_cell) super(pdf, [0, pdf.cursor]) @master_cell = master_cell @padding = [0, 0, 0, 0] end # By default, a span dummy will never increase the height demand. # def natural_content_height 0 end # By default, a span dummy will never increase the width demand. # def natural_content_width 0 end def avg_spanned_min_width @master_cell.avg_spanned_min_width end # Dummy cells have nothing to draw. # def draw_borders(pt) end # Dummy cells have nothing to draw. # def draw_bounded_content(pt) end def padding_right=(val) @master_cell.padding_right = val if rightmost? end def padding_bottom=(val) @master_cell.padding_bottom = val if bottommost? end def border_right_color=(val) @master_cell.border_right_color = val if rightmost? end def border_bottom_color=(val) @master_cell.border_bottom_color = val if bottommost? end def border_right_width=(val) @master_cell.border_right_width = val if rightmost? end def border_bottom_width=(val) @master_cell.border_bottom_width = val if bottommost? end def background_color @master_cell.background_color end private # Are we on the right border of the span? # def rightmost? @column == @master_cell.column + @master_cell.colspan - 1 end # Are we on the bottom border of the span? # def bottommost? @row == @master_cell.row + @master_cell.rowspan - 1 end end end end end prawn-table-0.2.1/lib/prawn/table/cell/image.rb0000644000004100000410000000260312436072751021300 0ustar www-datawww-data# encoding: utf-8 # image.rb: Table image cells. # # Copyright September 2010, Brad Ediger. All Rights Reserved. # # This is free software. Please see the LICENSE and COPYING files for details. module Prawn class Table class Cell # @private class Image < Cell def initialize(pdf, point, options={}) @image_options = {} super @pdf_object, @image_info = @pdf.build_image_object(@file) @natural_width, @natural_height = @image_info.calc_image_dimensions( @image_options) end def image=(file) @file = file end def scale=(s) @image_options[:scale] = s end def fit=(f) @image_options[:fit] = f end def image_height=(h) @image_options[:height] = h end def image_width=(w) @image_options[:width] = w end def position=(p) @image_options[:position] = p end def vposition=(vp) @image_options[:vposition] = vp end def natural_content_width @natural_width end def natural_content_height @natural_height end # Draw the image on the page. # def draw_content @pdf.embed_image(@pdf_object, @image_info, @image_options) end end end end end prawn-table-0.2.1/lib/prawn/table/cell/in_table.rb0000644000004100000410000000116112436072751021771 0ustar www-datawww-data# encoding: utf-8 # Accessors for using a Cell inside a Table. # # Contributed by Brad Ediger. # # This is free software. Please see the LICENSE and COPYING files for details. module Prawn class Table class Cell # This module extends Cell objects when they are used in a table (as # opposed to standalone). Its properties apply to cells-in-tables but not # cells themselves. # # @private module InTable # Row number (0-based). # attr_accessor :row # Column number (0-based). # attr_accessor :column end end end end prawn-table-0.2.1/lib/prawn/table/version.rb0000644000004100000410000000010212436072751020754 0ustar www-datawww-datamodule Prawn class Table VERSION = '0.2.1'.freeze end end prawn-table-0.2.1/lib/prawn/table/cells.rb0000644000004100000410000002047112436072751020404 0ustar www-datawww-data# encoding: utf-8 # cells.rb: Methods for accessing rows, columns, and cells of a Prawn::Table. # # Copyright December 2009, Brad Ediger. All Rights Reserved. # # This is free software. Please see the LICENSE and COPYING files for details. module Prawn class Table # Selects the given rows (0-based) for styling. Returns a Cells object -- # see the documentation on Cells for things you can do with cells. # def rows(row_spec) cells.rows(row_spec) end alias_method :row, :rows # Selects the given columns (0-based) for styling. Returns a Cells object # -- see the documentation on Cells for things you can do with cells. # def columns(col_spec) cells.columns(col_spec) end alias_method :column, :columns # Represents a selection of cells to be styled. Operations on a CellProxy # can be chained, and cell properties can be set one-for-all on the proxy. # # To set vertical borders only: # # table.cells.borders = [:left, :right] # # To highlight a rectangular area of the table: # # table.rows(1..3).columns(2..4).background_color = 'ff0000' # class Cells < Array def fits_on_current_page?(offset, ref_bounds) # an empty row array means it definitely fits return true if self.empty? height_with_span < (self[0,0].y + offset) - ref_bounds.absolute_bottom end # @group Experimental API # Limits selection to the given row or rows. +row_spec+ can be anything # that responds to the === operator selecting a set of 0-based row # numbers; most commonly a number or a range. # # table.row(0) # selects first row # table.rows(3..4) # selects rows four and five # def rows(row_spec) index_cells unless defined?(@indexed) && @indexed row_spec = transform_spec(row_spec, @first_row, @row_count) Cells.new(@rows[row_spec] ||= select { |c| row_spec.respond_to?(:include?) ? row_spec.include?(c.row) : row_spec === c.row }) end alias_method :row, :rows # Returns the number of rows in the list. # def row_count index_cells unless defined?(@indexed) && @indexed @row_count end # Limits selection to the given column or columns. +col_spec+ can be # anything that responds to the === operator selecting a set of 0-based # column numbers; most commonly a number or a range. # # table.column(0) # selects first column # table.columns(3..4) # selects columns four and five # def columns(col_spec) index_cells unless defined?(@indexed) && @indexed col_spec = transform_spec(col_spec, @first_column, @column_count) Cells.new(@columns[col_spec] ||= select { |c| col_spec.respond_to?(:include?) ? col_spec.include?(c.column) : col_spec === c.column }) end alias_method :column, :columns # Returns the number of columns in the list. # def column_count index_cells unless defined?(@indexed) && @indexed @column_count end # Allows you to filter the given cells by arbitrary properties. # # table.column(4).filter { |cell| cell.content =~ /Yes/ }. # background_color = '00ff00' # def filter(&block) Cells.new(select(&block)) end # Retrieves a cell based on its 0-based row and column. Returns an # individual Cell, not a Cells collection. # # table.cells[0, 0].content # => "First cell content" # def [](row, col) return nil if empty? index_cells unless defined?(@indexed) && @indexed row_array, col_array = @rows[@first_row + row] || [], @columns[@first_column + col] || [] if row_array.length < col_array.length row_array.find { |c| c.column == @first_column + col } else col_array.find { |c| c.row == @first_row + row } end end # Puts a cell in the collection at the given position. Internal use only. # def []=(row, col, cell) # :nodoc: cell.extend(Cell::InTable) cell.row = row cell.column = col if defined?(@indexed) && @indexed (@rows[row] ||= []) << cell (@columns[col] ||= []) << cell @first_row = row if !@first_row || row < @first_row @first_column = col if !@first_column || col < @first_column @row_count = @rows.size @column_count = @columns.size end self << cell end # Supports setting multiple properties at once. # # table.cells.style(:padding => 0, :border_width => 2) # # is the same as: # # table.cells.padding = 0 # table.cells.border_width = 2 # # You can also pass a block, which will be called for each cell in turn. # This allows you to set more complicated properties: # # table.cells.style { |cell| cell.border_width += 12 } # def style(options={}, &block) each do |cell| next if cell.is_a?(Cell::SpanDummy) cell.style(options, &block) end end # Returns the total width of all columns in the selected set. # def width ColumnWidthCalculator.new(self).natural_widths.inject(0, &:+) end # Returns minimum width required to contain cells in the set. # def min_width aggregate_cell_values(:column, :avg_spanned_min_width, :max) end # Returns maximum width that can contain cells in the set. # def max_width aggregate_cell_values(:column, :max_width_ignoring_span, :max) end # Returns the total height of all rows in the selected set. # def height aggregate_cell_values(:row, :height_ignoring_span, :max) end # Returns the total height of all rows in the selected set # including spanned cells if the cell is the master cell # def height_with_span aggregate_cell_values(:row, :height, :max) end # Supports setting arbitrary properties on a group of cells. # # table.cells.row(3..6).background_color = 'cc0000' # def method_missing(id, *args, &block) if id.to_s =~ /=\z/ each { |c| c.send(id, *args, &block) if c.respond_to?(id) } else super end end protected # Defers indexing until rows() or columns() is actually called on the # Cells object. Without this, we would needlessly index the leaf nodes of # the object graph, the ones that are only there to be iterated over. # # Make sure to call this before using @rows or @columns. # def index_cells @rows = {} @columns = {} each do |cell| @rows[cell.row] ||= [] @rows[cell.row] << cell @columns[cell.column] ||= [] @columns[cell.column] << cell end @first_row = @rows.keys.min @first_column = @columns.keys.min @row_count = @rows.size @column_count = @columns.size @indexed = true end # Sum up a min/max value over rows or columns in the cells selected. # Takes the min/max (per +aggregate+) of the result of sending +meth+ to # each cell, grouped by +row_or_column+. # def aggregate_cell_values(row_or_column, meth, aggregate) ColumnWidthCalculator.new(self).aggregate_cell_values(row_or_column, meth, aggregate) end # Transforms +spec+, a column / row specification, into an object that # can be compared against a row or column number using ===. Normalizes # negative indices to be positive, given a total size of +total+. The # first row/column is indicated by +first+; this value is considered row # or column 0. # def transform_spec(spec, first, total) case spec when Range transform_spec(spec.begin, first, total) .. transform_spec(spec.end, first, total) when Integer spec < 0 ? (first + total + spec) : first + spec when Enumerable spec.map { |x| first + x } else # pass through raise "Don't understand spec #{spec.inspect}" end end end end end prawn-table-0.2.1/lib/prawn/table/cell.rb0000644000004100000410000005675312436072751020235 0ustar www-datawww-data# encoding: utf-8 # cell.rb: Table cell drawing. # # Copyright December 2009, Gregory Brown and Brad Ediger. All Rights Reserved. # # This is free software. Please see the LICENSE and COPYING files for details. require 'date' module Prawn class Document # @group Experimental API # Instantiates and draws a cell on the document. # # cell(:content => "Hello world!", :at => [12, 34]) # # See Prawn::Table::Cell.make for full options. # def cell(options={}) cell = Table::Cell.make(self, options.delete(:content), options) cell.draw cell end # Set up, but do not draw, a cell. Useful for creating cells with # formatting options to be inserted into a Table. Call +draw+ on the # resulting Cell to ink it. # # See the documentation on Prawn::Cell for details on the arguments. # def make_cell(content, options={}) Prawn::Table::Cell.make(self, content, options) end end class Table # A Cell is a rectangular area of the page into which content is drawn. It # has a framework for sizing itself and adding padding and simple styling. # There are several standard Cell subclasses that handle things like text, # Tables, and (in the future) stamps, images, and arbitrary content. # # Cells are a basic building block for table support (see Prawn::Table). # # Please subclass me if you want new content types! I'm designed to be very # extensible. See the different standard Cell subclasses in # lib/prawn/table/cell/*.rb for a template. # class Cell # Amount of dead space (in PDF points) inside the borders but outside the # content. Padding defaults to 5pt. # attr_reader :padding # If provided, the minimum width that this cell in its column will permit. # def min_width_ignoring_span set_width_constraints @min_width end # Minimum width of the entire span group this cell controls. # def min_width return min_width_ignoring_span if @colspan == 1 # Sum up the largest min-width from each column, including myself. min_widths = Hash.new(0) dummy_cells.each do |cell| min_widths[cell.column] = [min_widths[cell.column], cell.min_width].max end min_widths[column] = [min_widths[column], min_width_ignoring_span].max min_widths.values.inject(0, &:+) end # Min-width of the span divided by the number of columns. # def avg_spanned_min_width min_width.to_f / colspan end # If provided, the maximum width that this cell can be drawn in, within # its column. # def max_width_ignoring_span set_width_constraints @max_width end # Maximum width of the entire span group this cell controls. # def max_width return max_width_ignoring_span if @colspan == 1 # Sum the smallest max-width from each column in the group, including # myself. max_widths = Hash.new(0) dummy_cells.each do |cell| max_widths[cell.column] = [max_widths[cell.column], cell.max_width].min end max_widths[column] = [max_widths[column], max_width_ignoring_span].min max_widths.values.inject(0, &:+) end # Manually specify the cell's height. # attr_writer :height # Specifies which borders to enable. Must be an array of zero or more of: # [:left, :right, :top, :bottom]. # attr_accessor :borders # Width, in PDF points, of the cell's borders: [top, right, bottom, left]. # attr_reader :border_widths # HTML RGB-format ("ccffff") border colors: [top, right, bottom, left]. # attr_reader :border_colors # Line style # attr_reader :border_lines # Specifies the content for the cell. Must be a "cellable" object. See the # "Data" section of the Prawn::Table documentation for details on cellable # objects. # attr_accessor :content # The background color, if any, for this cell. Specified in HTML RGB # format, e.g., "ccffff". The background is drawn under the whole cell, # including any padding. # attr_accessor :background_color # Number of columns this cell spans. Defaults to 1. # attr_reader :colspan # Number of rows this cell spans. Defaults to 1. # attr_reader :rowspan # Array of SpanDummy cells (if any) that represent the other cells in # this span group. They know their own width / height, but do not draw # anything. # attr_reader :dummy_cells # Instantiates a Cell based on the given options. The particular class of # cell returned depends on the :content argument. See the Prawn::Table # documentation under "Data" for allowable content types. # def self.make(pdf, content, options={}) at = options.delete(:at) || [0, pdf.cursor] content = content.to_s if content.nil? || content.kind_of?(Numeric) || content.kind_of?(Date) if content.is_a?(Hash) if content[:image] return Cell::Image.new(pdf, at, content) end options.update(content) content = options[:content] else options[:content] = content end options[:content] = content = "" if content.nil? case content when Prawn::Table::Cell content when String Cell::Text.new(pdf, at, options) when Prawn::Table Cell::Subtable.new(pdf, at, options) when Array subtable = Prawn::Table.new(options[:content], pdf, {}) Cell::Subtable.new(pdf, at, options.merge(:content => subtable)) else raise Errors::UnrecognizedTableContent end end # A small amount added to the bounding box width to cover over floating- # point errors when round-tripping from content_width to width and back. # This does not change cell positioning; it only slightly expands each # cell's bounding box width so that rounding error does not prevent a cell # from rendering. # FPTolerance = 1 # Sets up a cell on the document +pdf+, at the given x/y location +point+, # with the given +options+. Cell, like Table, follows the "options set # accessors" paradigm (see "Options" under the Table documentation), so # any cell accessor cell.foo = :bar can be set by providing the # option :foo => :bar here. # def initialize(pdf, point, options={}) @pdf = pdf @point = point # Set defaults; these can be changed by options @padding = [5, 5, 5, 5] @borders = [:top, :bottom, :left, :right] @border_widths = [1] * 4 @border_colors = ['000000'] * 4 @border_lines = [:solid] * 4 @colspan = 1 @rowspan = 1 @dummy_cells = [] options.each { |k, v| send("#{k}=", v) } @initializer_run = true end # Supports setting multiple properties at once. # # cell.style(:padding => 0, :border_width => 2) # # is the same as: # # cell.padding = 0 # cell.border_width = 2 # def style(options={}, &block) options.each do |k, v| send("#{k}=", v) if respond_to?("#{k}=") end # The block form supports running a single block for multiple cells, as # in Cells#style. block.call(self) if block end # Returns the width of the cell in its first column alone, ignoring any # colspans. # def width_ignoring_span # We can't ||= here because the FP error accumulates on the round-trip # from #content_width. defined?(@width) && @width || (content_width + padding_left + padding_right) end # Returns the cell's width in points, inclusive of padding. If the cell is # the master cell of a colspan, returns the width of the entire span # group. # def width return width_ignoring_span if @colspan == 1 && @rowspan == 1 # We're in a span group; get the maximum width per column (including # the master cell) and sum each column. column_widths = Hash.new(0) dummy_cells.each do |cell| column_widths[cell.column] = [column_widths[cell.column], cell.width].max end column_widths[column] = [column_widths[column], width_ignoring_span].max column_widths.values.inject(0, &:+) end # Manually sets the cell's width, inclusive of padding. # def width=(w) @width = @min_width = @max_width = w end # Returns the width of the bare content in the cell, excluding padding. # def content_width if defined?(@width) && @width # manually set return @width - padding_left - padding_right end natural_content_width end # Width of the entire span group. # def spanned_content_width width - padding_left - padding_right end # Returns the width this cell would naturally take on, absent other # constraints. Must be implemented in subclasses. # def natural_content_width raise NotImplementedError, "subclasses must implement natural_content_width" end # Returns the cell's height in points, inclusive of padding, in its first # row only. # def height_ignoring_span # We can't ||= here because the FP error accumulates on the round-trip # from #content_height. defined?(@height) && @height || (content_height + padding_top + padding_bottom) end # Returns the cell's height in points, inclusive of padding. If the cell # is the master cell of a rowspan, returns the width of the entire span # group. # def height return height_ignoring_span if @colspan == 1 && @rowspan == 1 # We're in a span group; get the maximum height per row (including the # master cell) and sum each row. row_heights = Hash.new(0) dummy_cells.each do |cell| row_heights[cell.row] = [row_heights[cell.row], cell.height].max end row_heights[row] = [row_heights[row], height_ignoring_span].max row_heights.values.inject(0, &:+) end # Returns the height of the bare content in the cell, excluding padding. # def content_height if defined?(@height) && @height # manually set return @height - padding_top - padding_bottom end natural_content_height end # Height of the entire span group. # def spanned_content_height height - padding_top - padding_bottom end # Returns the height this cell would naturally take on, absent # constraints. Must be implemented in subclasses. # def natural_content_height raise NotImplementedError, "subclasses must implement natural_content_height" end # Indicates the number of columns that this cell is to span. Defaults to # 1. # # This must be provided as part of the table data, like so: # # pdf.table([["foo", {:content => "bar", :colspan => 2}]]) # # Setting colspan from the initializer block is invalid because layout # has already run. For example, this will NOT work: # # pdf.table([["foo", "bar"]]) { cells[0, 1].colspan = 2 } # def colspan=(span) if defined?(@initializer_run) && @initializer_run raise Prawn::Errors::InvalidTableSpan, "colspan must be provided in the table's structure, never in the " + "initialization block. See Prawn's documentation for details." end @colspan = span end # Indicates the number of rows that this cell is to span. Defaults to 1. # # This must be provided as part of the table data, like so: # # pdf.table([["foo", {:content => "bar", :rowspan => 2}], ["baz"]]) # # Setting rowspan from the initializer block is invalid because layout # has already run. For example, this will NOT work: # # pdf.table([["foo", "bar"], ["baz"]]) { cells[0, 1].rowspan = 2 } # def rowspan=(span) if defined?(@initializer_run) && @initializer_run raise Prawn::Errors::InvalidTableSpan, "rowspan must be provided in the table's structure, never in the " + "initialization block. See Prawn's documentation for details." end @rowspan = span end # Draws the cell onto the document. Pass in a point [x,y] to override the # location at which the cell is drawn. # # If drawing a group of cells at known positions, look into # Cell.draw_cells, which ensures that the backgrounds, borders, and # content are all drawn in correct order so as not to overlap. # def draw(pt=[x, y]) Prawn::Table::Cell.draw_cells([[self, pt]]) end # Given an array of pairs [cell, pt], draws each cell at its # corresponding pt, making sure all backgrounds are behind all borders # and content. # def self.draw_cells(cells) cells.each do |cell, pt| cell.set_width_constraints cell.draw_background(pt) end cells.each do |cell, pt| cell.draw_borders(pt) cell.draw_bounded_content(pt) end end # Draws the cell's content at the point provided. # def draw_bounded_content(pt) @pdf.float do @pdf.bounding_box([pt[0] + padding_left, pt[1] - padding_top], :width => spanned_content_width + FPTolerance, :height => spanned_content_height + FPTolerance) do draw_content end end end # x-position of the cell within the parent bounds. # def x @point[0] end # Set the x-position of the cell within the parent bounds. # def x=(val) @point[0] = val end def relative_x # Translate coordinates to the bounds we are in, since drawing is # relative to the cursor, not ref_bounds. x + @pdf.bounds.left_side - @pdf.bounds.absolute_left end # y-position of the cell within the parent bounds. # def y @point[1] end # Set the y-position of the cell within the parent bounds. # def y=(val) @point[1] = val end def relative_y(offset = 0) y + offset - @pdf.bounds.absolute_bottom end # Sets padding on this cell. The argument can be one of: # # * an integer (sets all padding) # * a two-element array [vertical, horizontal] # * a three-element array [top, horizontal, bottom] # * a four-element array [top, right, bottom, left] # def padding=(pad) @padding = case when pad.nil? [0, 0, 0, 0] when Numeric === pad # all padding [pad, pad, pad, pad] when pad.length == 2 # vert, horiz [pad[0], pad[1], pad[0], pad[1]] when pad.length == 3 # top, horiz, bottom [pad[0], pad[1], pad[2], pad[1]] when pad.length == 4 # top, right, bottom, left [pad[0], pad[1], pad[2], pad[3]] else raise ArgumentError, ":padding must be a number or an array [v,h] " + "or [t,r,b,l]" end end def padding_top @padding[0] end def padding_top=(val) @padding[0] = val end def padding_right @padding[1] end def padding_right=(val) @padding[1] = val end def padding_bottom @padding[2] end def padding_bottom=(val) @padding[2] = val end def padding_left @padding[3] end def padding_left=(val) @padding[3] = val end # Sets border colors on this cell. The argument can be one of: # # * an integer (sets all colors) # * a two-element array [vertical, horizontal] # * a three-element array [top, horizontal, bottom] # * a four-element array [top, right, bottom, left] # def border_color=(color) @border_colors = case when color.nil? ["000000"] * 4 when String === color # all colors [color, color, color, color] when color.length == 2 # vert, horiz [color[0], color[1], color[0], color[1]] when color.length == 3 # top, horiz, bottom [color[0], color[1], color[2], color[1]] when color.length == 4 # top, right, bottom, left [color[0], color[1], color[2], color[3]] else raise ArgumentError, ":border_color must be a string " + "or an array [v,h] or [t,r,b,l]" end end alias_method :border_colors=, :border_color= def border_top_color @border_colors[0] end def border_top_color=(val) @border_colors[0] = val end def border_right_color @border_colors[1] end def border_right_color=(val) @border_colors[1] = val end def border_bottom_color @border_colors[2] end def border_bottom_color=(val) @border_colors[2] = val end def border_left_color @border_colors[3] end def border_left_color=(val) @border_colors[3] = val end # Sets border widths on this cell. The argument can be one of: # # * an integer (sets all widths) # * a two-element array [vertical, horizontal] # * a three-element array [top, horizontal, bottom] # * a four-element array [top, right, bottom, left] # def border_width=(width) @border_widths = case when width.nil? ["000000"] * 4 when Numeric === width # all widths [width, width, width, width] when width.length == 2 # vert, horiz [width[0], width[1], width[0], width[1]] when width.length == 3 # top, horiz, bottom [width[0], width[1], width[2], width[1]] when width.length == 4 # top, right, bottom, left [width[0], width[1], width[2], width[3]] else raise ArgumentError, ":border_width must be a string " + "or an array [v,h] or [t,r,b,l]" end end alias_method :border_widths=, :border_width= def border_top_width @borders.include?(:top) ? @border_widths[0] : 0 end def border_top_width=(val) @border_widths[0] = val end def border_right_width @borders.include?(:right) ? @border_widths[1] : 0 end def border_right_width=(val) @border_widths[1] = val end def border_bottom_width @borders.include?(:bottom) ? @border_widths[2] : 0 end def border_bottom_width=(val) @border_widths[2] = val end def border_left_width @borders.include?(:left) ? @border_widths[3] : 0 end def border_left_width=(val) @border_widths[3] = val end # Sets the cell's minimum and maximum width. Deferred until requested # because padding and size can change. # def set_width_constraints @min_width ||= padding_left + padding_right @max_width ||= @pdf.bounds.width end # Sets border line style on this cell. The argument can be one of: # # Possible values are: :solid, :dashed, :dotted # # * one value (sets all lines) # * a two-element array [vertical, horizontal] # * a three-element array [top, horizontal, bottom] # * a four-element array [top, right, bottom, left] # def border_line=(line) @border_lines = case when line.nil? [:solid] * 4 when line.length == 1 # all lines [line[0]] * 4 when line.length == 2 [line[0], line[1], line[0], line[1]] when line.length == 3 [line[0], line[1], line[2], line[1]] when line.length == 4 [line[0], line[1], line[2], line[3]] else raise ArgumentError, "border_line must be one of :solid, :dashed, " ":dotted or an array [v,h] or [t,r,b,l]" end end alias_method :border_lines=, :border_line= def border_top_line @borders.include?(:top) ? @border_lines[0] : 0 end def border_top_line=(val) @border_lines[0] = val end def border_right_line @borders.include?(:right) ? @border_lines[1] : 0 end def border_right_line=(val) @border_lines[1] = val end def border_bottom_line @borders.include?(:bottom) ? @border_lines[2] : 0 end def border_bottom_line=(val) @border_lines[2] = val end def border_left_line @borders.include?(:left) ? @border_lines[3] : 0 end def border_left_line=(val) @border_lines[3] = val end # Draws the cell's background color. # def draw_background(pt) if defined?(@background_color) && @background_color @pdf.mask(:fill_color) do @pdf.fill_color @background_color @pdf.fill_rectangle pt, width, height end end end # Draws borders around the cell. Borders are centered on the bounds of # the cell outside of any padding, so the caller is responsible for # setting appropriate padding to ensure the border does not overlap with # cell content. # def draw_borders(pt) x, y = pt @pdf.mask(:line_width, :stroke_color) do @borders.each do |border| idx = {:top => 0, :right => 1, :bottom => 2, :left => 3}[border] border_color = @border_colors[idx] border_width = @border_widths[idx] border_line = @border_lines[idx] next if border_width <= 0 # Left and right borders are drawn one-half border beyond the center # of the corner, so that the corners end up square. from, to = case border when :top [[x, y], [x+width, y]] when :bottom [[x, y-height], [x+width, y-height]] when :left [[x, y + (border_top_width / 2.0)], [x, y - height - (border_bottom_width / 2.0)]] when :right [[x+width, y + (border_top_width / 2.0)], [x+width, y - height - (border_bottom_width / 2.0)]] end case border_line when :dashed @pdf.dash border_width * 4 when :dotted @pdf.dash border_width, :space => border_width * 2 when :solid # normal line style else raise ArgumentError, "border_line must be :solid, :dotted or" + " :dashed" end @pdf.line_width = border_width @pdf.stroke_color = border_color @pdf.stroke_line(from, to) @pdf.undash end end end # Draws cell content within the cell's bounding box. Must be implemented # in subclasses. # def draw_content raise NotImplementedError, "subclasses must implement draw_content" end end end end prawn-table-0.2.1/metadata.yml0000644000004100000410000001322312436072751016271 0ustar www-datawww-data--- !ruby/object:Gem::Specification name: prawn-table version: !ruby/object:Gem::Version version: 0.2.1 platform: ruby authors: - Gregory Brown - Brad Ediger - Daniel Nelson - Jonathan Greenberg - James Healy - Hartwig Brandl autorequire: bindir: bin cert_chain: [] date: 2014-10-31 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: prawn requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 1.3.0 - - "<" - !ruby/object:Gem::Version version: 3.0.0 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 1.3.0 - - "<" - !ruby/object:Gem::Version version: 3.0.0 - !ruby/object:Gem::Dependency name: pdf-inspector requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: 1.1.0 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: 1.1.0 - !ruby/object:Gem::Dependency name: yard requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: rspec requirement: !ruby/object:Gem::Requirement requirements: - - '=' - !ruby/object:Gem::Version version: 2.14.1 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - '=' - !ruby/object:Gem::Version version: 2.14.1 - !ruby/object:Gem::Dependency name: mocha requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: rake requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: simplecov requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: prawn-manual_builder requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 0.2.0 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 0.2.0 - !ruby/object:Gem::Dependency name: pdf-reader requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '1.2' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '1.2' description: |2 Prawn::Table provides tables for the Prawn PDF toolkit email: - gregory.t.brown@gmail.com - brad@bradediger.com - dnelson@bluejade.com - greenberg@entryway.net - jimmy@deefa.com - mail@hartwigbrandl.at executables: [] extensions: [] extra_rdoc_files: [] files: - COPYING - GPLv2 - GPLv3 - Gemfile - LICENSE - lib/prawn/table.rb - lib/prawn/table/cell.rb - lib/prawn/table/cell/image.rb - lib/prawn/table/cell/in_table.rb - lib/prawn/table/cell/span_dummy.rb - lib/prawn/table/cell/subtable.rb - lib/prawn/table/cell/text.rb - lib/prawn/table/cells.rb - lib/prawn/table/column_width_calculator.rb - lib/prawn/table/version.rb - manual/contents.rb - manual/example_helper.rb - manual/table/basic_block.rb - manual/table/before_rendering_page.rb - manual/table/cell_border_lines.rb - manual/table/cell_borders_and_bg.rb - manual/table/cell_dimensions.rb - manual/table/cell_text.rb - manual/table/column_widths.rb - manual/table/content_and_subtables.rb - manual/table/creation.rb - manual/table/filtering.rb - manual/table/flow_and_header.rb - manual/table/image_cells.rb - manual/table/position.rb - manual/table/row_colors.rb - manual/table/span.rb - manual/table/style.rb - manual/table/table.rb - manual/table/width.rb - prawn-table.gemspec - spec/cell_spec.rb - spec/extensions/encoding_helpers.rb - spec/extensions/mocha.rb - spec/spec_helper.rb - spec/table/span_dummy_spec.rb - spec/table_spec.rb homepage: https://github.com/prawnpdf/prawn-table licenses: - RUBY - GPL-2 - GPL-3 metadata: {} post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 1.9.3 required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 1.3.6 requirements: [] rubyforge_project: prawn rubygems_version: 2.2.2 signing_key: specification_version: 4 summary: Provides tables for PrawnPDF test_files: - spec/cell_spec.rb - spec/table_spec.rb has_rdoc: prawn-table-0.2.1/GPLv30000644000004100000410000010451312436072751014607 0ustar www-datawww-data GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . prawn-table-0.2.1/LICENSE0000644000004100000410000000456412436072751015003 0ustar www-datawww-dataPrawn is copyrighted free software produced by Gregory Brown along with community contributions. See git log for authorship information. Licensing terms follow: You can redistribute Prawn and/or modify it under either the terms of the GPLv2 or GPLv3 (see GPLv2 and GPLv3 files), or the conditions below: 1. You may make and give away verbatim copies of the source form of the software without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may modify your copy of the software in any way, provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or by allowing the author to include your modifications in the software. b) use the modified software only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided. d) make other distribution arrangements with the author. 3. You may distribute the software in object code or executable form, provided that you do at least ONE of the following: a) distribute the executables and library files of the software, together with instructions (in the manual page or equivalent) on where to get the original distribution. b) accompany the distribution with the machine-readable source of the software. c) give non-standard executables non-standard names, with instructions on where to get the original software distribution. d) make other distribution arrangements with the author. 4. You may modify and include the part of the software into any other software (possibly commercial). 5. The scripts and library files supplied as input to or produced as output from the software do not automatically fall under the copyright of the software, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this software. 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. prawn-table-0.2.1/COPYING0000644000004100000410000000021612436072751015017 0ustar www-datawww-dataPrawn may be used under Matz's original licensing terms for Ruby, or GPLv2 or GPLv3. See LICENSE for Matz's terms, or GPLv2 and GPLv3 files.