在Python中使用fpdf创建pdf。无法循环向右移动图像

问题描述 投票:0回答:3

我使用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')

如果您能为我提供解决方案/帮助,那就太好了。多谢 问候亚历克斯

python fpdf
3个回答
5
投票

我看到了这个问题。您想要在对

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 -> ^^^^^  ^^^^

1
投票

您可以查看pdfme库。它是一个强大的 python 库,用于创建 PDF 文档。您可以添加网址、脚注、页眉和页脚、表格以及 PDF 文档中所需的任何内容。

我看到的唯一问题是目前 pdfme 仅支持 jpg 格式的图像。但如果这不是问题,它将帮助您完成任务。

查看文档此处


0
投票

免责声明:我是

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)

您可以在 GitHub 上获取 pText,或者使用 PyPi 还有大量示例,请查看它们以了解有关使用图像的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.