Reportlab文本背景大小与字体大小不匹配

2024-05-15 16:22:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在一个简单的黑色条上有一个白色文本的标题(包含来自页面的内容,所以做一个真正的标题是非常复杂的)。问题是文本的背景似乎与文本不符,正如我在MWI中看到的:

from reportlab.lib import colors
from reportlab.lib.enums import TA_JUSTIFY, TA_RIGHT, TA_CENTER, TA_LEFT
from reportlab.lib.pagesizes import letter, landscape
from reportlab.platypus import PageTemplate, Frame, NextPageTemplate, BaseDocTemplate, SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle, PageBreak
from reportlab.platypus import ListFlowable, ListItem
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.rl_config import defaultPageSize
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.pdfgen import canvas

#c = canvas.Canvas("tables.pdf")
doc = SimpleDocTemplate("mwi.pdf",pagesize=letter,
                        rightMargin=72,leftMargin=72,
                        topMargin=72,bottomMargin=60)

styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='Table Top Black Back', fontName ='Helvetica',fontSize=14, backColor = colors.black, textColor=colors.white, alignment=TA_LEFT))
styles.add(ParagraphStyle(name='Table Top Red Back', fontName ='Helvetica',fontSize=9, backColor = colors.red, textColor=colors.black, alignment=TA_LEFT))

styleN = styles["BodyText"]

# Header
# report: topic/subtopic overview
report = []
ptext = 'Test' 
report.append(Paragraph(ptext, styles["Table Top Black Back"]))
report.append(Spacer(1, 24))

ptext = 'Test' 
report.append(Paragraph(ptext, styles["Table Top Black Back"]))
report.append(Spacer(1, 24))

ptext = 'Test' 
report.append(Paragraph(ptext, styles["Table Top Red Back"]))
report.append(Spacer(1, 48))


# Build Document
doc.build(report)

Tags: fromimportreportlibtoptablebackcolors
1条回答
网友
1楼 · 发布于 2024-05-15 16:22:04

首先,从你的代码来看,它不会因为出错而编译。在

ImportError: cannot import name ListFlowable
ImportError: cannot import name ListItem

因为我不需要把这些东西拿走。在

背景大小不匹配的原因是您没有在段落中指定“前导”属性,您更改了“fontSize”,但没有更改“leading”属性。在

这是什么“领导”? 这是相邻文本行之间的间距;一个好的经验法则是使其比点大小大20%。要获得两倍行距的文本,请使用大行距。在

默认情况下,fontSize设置为10,前导设置为12。在

所以在上面的例子中,只要将fontSize设置为14,但是行距仍然是12,这就是文本大小不合适的原因。在

解决方法是在上面的例子中定义一个稍微大一点的前导。在

我不认为这是一个bug,而是一个非最佳设计考虑。这是一个非常主观的话题,不确定reportlab开发人员那段时间经历了什么。在

^{pr2}$

希望这有帮助。快乐的reportlab编码。在

相关问题 更多 >