Python:FPDF中的单元格着色无效?

7

我正在使用FPDF库创建PDF文档,想要给我的文档上的单元格添加颜色。我查看了API文档并找到了如下方法:

fpdf.set_fill_color(r: int, g: int = -1, b: int = -1)

于是我在我的脚本中这样做:

pdf = FPDF()

pdf.add_page()

pdf.set_font('Arial', 'B', 7)
pdf.set_fill_color(0, 0, 255)
pdf.cell(190, 6, 'Testing...', 1, 1, 'L')

pdf.output('Color.pdf', 'F')

颜色没有改变。其他的一切都正常,但是我得到的是一个白色的单元格而不是蓝色的。也没有抛出任何错误。是我做错了还是PyFPDF出现了故障?

编辑:在这个问题中添加了pdf.add_page()pdf.output('Color.pdf', 'F')(忘记在此处添加,在我的脚本中已经添加了)。


@eyllanesc,没错,谢谢!我很抱歉没有早点回复你,我忘了。 - secretagentmango
2个回答

14
根据文档,您必须将fill设置为True

[...]

fill:

指示单元格背景是否应该被涂上(True)或是透明的(False)。默认值:False

[...]


from fpdf import FPDF

pdf = FPDF()

pdf.add_page()

pdf.set_font('Arial', 'B', 7)
pdf.set_fill_color(0, 0, 255)
pdf.cell(190, 6, 'Testing...', 1, 1, 'L', fill=True)

pdf.output('Color.pdf', 'F')

1
如何根据单元格中存储的值对单元格进行着色? - Mainland
@大陆,检查单元格上的值,进行逻辑判断,选择一种颜色,然后调用set_fill_color()函数,再调用cell()函数,最后根据喜好重新设置颜色(或者fill=False)。 - undefined

0
这篇帖子帮助我给我的单元格上色,谢谢 :)
然而,我后来发现它只支持RGB而不支持RGBA来实现透明/不透明的上色。在浏览了一些资料(主要是这里这里)之后,我通过使用local_context()方法以及rect()cell()方法,成功实现了RGBA颜色的单元格。以下是一小段代码示例:
# set your desired Alpha here, both fill and stroke supported
with pdf.local_context(fill_opacity=0.5, stroke_opacity=0.2):
    # set the desired color in RGB
    pdf.set_fill_color(250, 0, 250)
    # get current cursor position and draw rect there
    # use same dimensions as the cell, F for filled
    curr_x = pdf.get_x()
    curr_y = pdf.get_y()
    pdf.rect(curr_x, curr_y, 45, 15, 'F')

# finally, draw cell over the colored rect OUTSIDE the with    
pdf.cell(45, 15, "This is a RGBA Cell", 1, 0, 'C')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接