我在 python 2.7 中使用 reportlab 3.1.44 下面是在表格中使用段落的代码。
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import inch
from reportlab.lib.styles import ParagraphStyle
from reportlab.platypus.tables import Table, TableStyle
from reportlab.lib import colors
from reportlab.lib.colors import Color
styles = getSampleStyleSheet()
def make_report():
doc = SimpleDocTemplate("hello.pdf")
story = []
style = styles["Normal"]
ps = ParagraphStyle('title', fontSize=20)
p1 = "here is some paragraph to see in large font"
data = []
table_row = [Paragraph(p1, ps),\
Paragraph(p1, ps)\
]
data.append(table_row)
t1 = Table(data)
t1.setStyle(TableStyle([\
('GRID', (0,0), (-1,-1), 0.25, colors.red, None, (2,2,1)),\
]))
story.append(t1)
doc.build(story)
if __name__ == "__main__":
make_report()
当字体较大时,有两个问题。
- 文本比单元格大,因此超出了边界
- 行距太小
我该如何解决这个问题?
请您参考如下方法:
这2个问题实际上是由同一个问题引起的,即Paragraph的高度。表格单元格由决定行高的行距决定。同时缺少空白也是由行距引起的。
在 Reportlab 中,行距是根据文档使用 leading 样式属性设置的。
Interline spacing (Leading)
The vertical offset between the point at which one line starts and where the next starts is called the leading offset.
因此您的代码的正确版本将使用:
ps = ParagraphStyle('title', fontSize=20, leading=24)
