Python中将PNG图像合并成一个PDF文件

9
我有一组.png格式的图片,需要将它们转换为一个pdf文件,每页9张图片,但不是按垂直顺序依次排列,而是横向填充整个页面宽度,然后再继续下一行。每次图片数量可能不同(如12、15张等)。
我尝试使用了fpdf工具。
from fpdf import FPDF

list_of_images = [1.png, 2.png, ... 15.png]
w = 70
h = 60
pdf = FPDF(orientation = 'L')
for image in list_of_images:
    pdf.image(image, w=sizew, h=sizeh)
pdf.output("Memory_usage.pdf", "F")

还有 wkhtmltopdf

template = Template('''<!doctype html>
<html>
<body>
        <div style="display: flex; flex-direction: row">
        {% for image in images %}
            <img src="{{ image }}" />
        {% endfor %}
        </div>
</body>
</html>''')
list_of_images = [1.png, 2.png, ... 15.png]
html = template.render(images=list_of_pict)
with open("my_new_file.html", "wb") as fh:
    fh.write(html)

p = subprocess.Popen(['wkhtmltopdf', '-', 'Memory_usage.pdf'], stdin=subprocess.PIPE, universal_newlines=True)
p.communicate(html)
p.wait()

但两者都将每张图片放在另一张下面。
3个回答

9
只需使用FPDF将每个图像放置在所需的坐标即可:
pdf.image(image, x=50, y=100, w=sizew, h=sizeh)

更多有关FPDF文档的信息: 图像


0

免责声明:我是本回答中使用的库borb的作者。

borb具有可能对您有所帮助的布局系统。 如果您想向页面添加内容,可以使用PageLayout,但是Image对象的默认设置始终是将它们放在下一行。

您可以使用InlineFlow对象将对象聚合成组(然后将该InlineFlow对象添加到某个东西中,例如PageLayout)。

from borb.pdf import Document
from borb.pdf import Page
from borb.pdf import PageLayout, SingleColumnLayout
from borb.pdf import InlineFlow
from borb.pdf import Image
from borb.pdf import PDF

from pathlib import Path

# create a new Document
d: Document = Document()

# add a new Page
p: Page = Page()
d.add_page(p)

# create a PageLayout to handle content-coordinates/margin/padding
l: PageLayout = SingleColumnLayout(p)

# build an InlineFlow (which will attempt to flow items that are added to it)
f: InlineFlow = InlineFlow()

# add all Images to the InlineFlow
for img_path in [Path("a"), Path("b"), Path("c")]:
    f.add(Image(img_path))

# add the InlineFlow object to the PageLayout
l.add(f)

# store the PDF
with open("output.pdf", "wb") as fh:
    PDF.dumps(fh, d)


0
这是将图像列表转换为PDF的代码。您也可以使用以下方式保留for循环,而不是使用image_1、image_2等。
from PIL import Image

image_1 = Image.open(r'C:\Users\Ron\Desktop\Test\view_1.png')
image_2 = Image.open(r'C:\Users\Ron\Desktop\Test\view_2.png')
image_3 = Image.open(r'C:\Users\Ron\Desktop\Test\view_3.png')
image_4 = Image.open(r'C:\Users\Ron\Desktop\Test\view_4.png')

im_1 = image_1.convert('RGB')
im_2 = image_2.convert('RGB')
im_3 = image_3.convert('RGB')
im_4 = image_4.convert('RGB')

image_list = [im_2, im_3, im_4]

im_1.save(r'C:\Users\Ron\Desktop\Test\my_images.pdf', save_all=True, append_images=image_list)

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