是否可以在python FPDF中更改PDF的背景颜色?

Ull*_*okk 4 python fpdf

我正在尝试使用 FPDF 在 python 中创建一个带有彩色背景的 pdf。

有没有办法将背景颜色从白色更改为其他颜色?或者我是否必须插入彩色单元格才能填充整个 pdf?

from fpdf import FPDF

pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.set_fill_color(248,245,235)
pdf.cell(200, 40,'Colored cell', 0, 1, 'C', fill=True)
pdf.output("test.pdf")
Run Code Online (Sandbox Code Playgroud)

小智 6

您可以将彩色图像文件添加到您创建的 pdf 页面上,然后将文本添加到同一页面上。

例如:使用 Pillow 包创建一个新的图像文件。

from fpdf import FPDF
from PIL import Image

pdf = FPDF()
pdf.add_page()

# creating a new image file with light blue color with A4 size dimensions using PIL
img = Image.new('RGB', (210,297), "#afeafe" )
img.save('blue_colored.png')

# adding image to pdf page that e created using fpdf
pdf.image('blue_colored.png', x = 0, y = 0, w = 210, h = 297, type = '', link = '')

# setting font and size and writing text to cell
pdf.set_font("Arial", size=12)
pdf.cell(ln=200, h=40, align='L', w=0, txt="Hello World", border=0,fill = False)
pdf.output("test.pdf", 'F')
Run Code Online (Sandbox Code Playgroud)

谢谢你!