我正在尝试设置一个段落样式来报告实验室,我在这里定义了一个样式:
def stylesheet():
styles= {
'default': ParagraphStyle(
'default',
fontName='Arial',
fontSize=16,
leading=12,
leftIndent=0,
rightIndent=0,
firstLineIndent=0,
alignment=TA_LEFT,
spaceBefore=0,
spaceAfter=0,
bulletFontName='Arial',
bulletFontSize=10,
bulletIndent=0,
textColor= black,
backColor=None,
wordWrap=None,
borderWidth= 0,
borderPadding= 0,
borderColor= None,
borderRadius= None,
allowWidows= 1,
allowOrphans= 0,
textTransform=None, # 'uppercase' | 'lowercase' | None
endDots=None,
splitLongWords=1,
),
}
Run Code Online (Sandbox Code Playgroud)
然后我就这样打印
pdf = PDFDocument(carte)
pdf.init_report()
pdf.p(str(row))
pdf.generate()
Run Code Online (Sandbox Code Playgroud)
这给出了一个未格式化的输出
当我尝试
pdf = PDFDocument(carte)
pdf.init_report()
pdf.p(str(row), default)
pdf.generate()
Run Code Online (Sandbox Code Playgroud)
要将默认样式应用于我的文本,它会给我 'NameError: name 'styles' is not defined'
有什么线索吗?
使用reportlab 尝试此操作,添加到您现有的代码中:
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.enums import TA_LEFT
from reportlab.lib.colors import black
styles = getSampleStyleSheet()
styles['small'] = ParagraphStyle(
'small',
parent=styles['default'],
fontSize=8,
leading=8,
)
paragraphs.append(Paragraph('Text with default style<br/>', styles['default']))
paragraphs.append(Paragraph('Text with small style', styles['small']))
Run Code Online (Sandbox Code Playgroud)
I've been struggling with this for a few hours, as of today the solution provided didn't work for me. I found another on programcreek that almost did. After a little retouch this one did the trick:
#First you need to instantiate 'getSampleStyleSheet()'
from reportlab.lib.styles import (ParagraphStyle, getSampleStyleSheet)
style = getSampleStyleSheet()
yourStyle = ParagraphStyle('yourtitle',
fontName="Helvetica-Bold",
fontSize=16,
parent=style['Heading2'],
alignment=1,
spaceAfter=14)
Run Code Online (Sandbox Code Playgroud)
To use it just call yourStyle like this:
Story.append(Paragraph("Whatever printed with yourStyle", yourStyle))
Run Code Online (Sandbox Code Playgroud)
Alignment must be given with a number as indicated in the docs:
There are four possible values of alignment, defined as constants in the module reportlab.lib.enums. These are TA_LEFT, TA_CENTER or TA_CENTRE, TA_RIGHT and TA_JUSTIFY, with values of 0, 1, 2 and 4 respectively. These do exactly what you would expect.
I'm posting the answer because I couldn't find a precise answer anywhere in the hope that it might help other people.