如何在Prawn中调整表格尺寸?Ruby报表开发技术问询
嘿,我来帮你搞定Prawn报表里表格尺寸调整的问题!先把你没写完的代码补全,再给你演示几种常用的调整方式,直接套用就行~
完整示例代码(带尺寸调整)
require "prawn" require "prawn/table" logo = Dir.pwd + "/logo.jpg" arr = ['a', 'aa', 'aaa', 'ddd', 'eee', 'fff'] arr2 = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff'] arr3 = ['a', 'b', 'c', 'd', 'e', 'f'] # 把数组组合成标准表格数据(表头+内容行) table_data = [ ["列1", "列2", "列3"], # 表头行 arr, arr2, arr3 ] Prawn::Document.generate("rapportino.pdf") do move_down 10 image logo, :width => 540, :height => 60 move_down 30 text "Ragione Sociale: " + ARGV[0] move_down 30 text "Nome Cantiere: " + ARGV[1] move_down 30 text "Note: 这里可以填写你的备注内容" move_down 20 # 表格和上方内容留间距 # 方法1:让表格适配页面宽度(左右各留20px边距) table(table_data, width: bounds.width - 40) do header = true # 标记第一行为表头 row(0).font_style = :bold # 表头加粗 row_height = 20 # 设置统一行高 end # 方法2:精准自定义每列宽度 move_down 30 table(table_data, column_widths: [80, 150, 220], width: bounds.width - 40) do header = true row(0).background_color = "#eeeeee" # 表头加灰色背景 end # 方法3:让长内容自动换行适配列宽 move_down 30 table(table_data, width: bounds.width - 40, wrap_content: true) do header = true columns(1).width = 200 # 单独给第二列设置宽度 rows(1..-1).height = 30 # 给内容行设置更大行高,方便换行显示 end end
常用的表格尺寸调整技巧
- 设置整体宽度:用
width参数,比如width: bounds.width - 40,意思是表格宽度等于页面宽度减去40px(左右各留20px边距),避免表格贴到页面边缘。 - 自定义列宽:通过
column_widths参数,可以给每列指定固定宽度(比如[80,150,220]),或者按比例分配(比如{0 => 20%, 1 => 30%, 2 => 50%}),灵活控制每列占比。 - 调整行高:用
row_height设置统一行高,或者针对特定行(比如rows(1..-1).height = 30)设置不同高度,适合内容较多的行。 - 自动换行适配:加上
wrap_content: true,表格里的长文本会自动换行,配合列宽设置,能避免内容溢出表格边界。
内容的提问来源于stack exchange,提问作者riki
相关产品推荐
相关产品推荐

