如何在 python 中将多图像 TIFF 转换为 PDF?

Nor*_*ori 2 python python-imaging-library

我想在 python 中将多图像 TIFF 转换为 PDF。

我是这样写的代码。然而这段代码不起作用。我应该如何改变它?


images = []
img = Image.open('multipage.tif')

for i in range(4):
    try:
        img.seek(i)
        images.append(img)
    except EOFError:
        # Not enough frames in img
        break
images[0].save('multipage.pdf',save_all=True,append_images=images[1:])
Run Code Online (Sandbox Code Playgroud)

Nor*_*ori 9

我解决了这个问题。您可以通过此功能轻松将 tiff 转换为 pdf。

from PIL import Image, ImageSequence
import os

def tiff_to_pdf(tiff_path: str) -> str:
 
    pdf_path = tiff_path.replace('.tiff', '.pdf')
    if not os.path.exists(tiff_path): raise Exception(f'{tiff_path} does not find.')
    image = Image.open(tiff_path)

    images = []
    for i, page in enumerate(ImageSequence.Iterator(image)):
        page = page.convert("RGB")
        images.append(page)
    if len(images) == 1:
        images[0].save(pdf_path)
    else:
        images[0].save(pdf_path, save_all=True,append_images=images[1:])
    return pdf_path
Run Code Online (Sandbox Code Playgroud)

Pillow使用此功能时需要安装。