我使用FPDF通过python生成pdf。我有一个问题正在寻找解决方案。在“图像”文件夹中,我想在一页上显示每张图片。我就是这么做的——也许并不优雅。不幸的是我无法将图片移到右侧。看起来 pdf_set_y 在循环中不起作用。
from fpdf import FPDF
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir('../images') if isfile(join('../images', f))]
pdf = FPDF('L')
pdf.add_page()
pdf.set_font('Arial', 'B', 16)
onlyfiles = ['VI 1.png', 'VI 2.png', 'VI 3.png']
y = 10
for image in onlyfiles:
pdf.set_x(10)
pdf.set_y(y)
pdf.cell(10, 10, 'please help me' + image, 0, 0, 'L')
y = y + 210 #to got to the next page
pdf.set_x(120)
pdf.set_y(50)
pdf.image('../images/' + image, w=pdf.w/2.0, h=pdf.h/2.0)
pdf.output('problem.pdf', 'F')
如果您能为我提供解决方案/帮助,那就太好了。多谢 问候亚历克斯
我看到了这个问题。您想要在对
x
的调用中指定 y
和 pdf.image()
位置。该评估基于此处的 image
文档:https://pyfpdf.readthedocs.io/en/latest/reference/image/index.html
所以你可以这样做(这里只显示
for
循环):
for image in onlyfiles:
pdf.set_x(10)
pdf.set_y(y)
pdf.cell(10, 10, 'please help me' + image, 0, 0, 'L')
y = y + 210 # to go to the next page
# increase `x` from 120 to, say, 150 to move the image to the right
pdf.image('../images/' + image, x=120, y=50, w=pdf.w/2.0, h=pdf.h/2.0)
# new -> ^^^^^ ^^^^
免责声明:我是
pText
我将在此解决方案中使用的库的作者。
让我们从创建一个空的
Document
开始:
pdf: Document = Document()
# create empty page
page: Page = Page()
# add page to document
pdf.append_page(page)
接下来我们将使用
Image
加载
Pillow
import requests
from PIL import Image as PILImage
im = PILImage.open(
requests.get(
"https://365psd.com/images/listing/fbe/ups-logo-49752.jpg", stream=True
).raw
)
现在我们可以创建一个
LayoutElement
Image
并使用它的 layout
方法
Image(im).layout(
page,
bounding_box=Rectangle(Decimal(20), Decimal(724), Decimal(64), Decimal(64)),
)
请记住原点(在 PDF 空间中)位于左下角。
最后,我们需要存储
Document
# attempt to store PDF
with open("output.pdf", "wb") as out_file_handle:
PDF.dumps(out_file_handle, pdf)