Nori
Nori

Reputation: 2972

How to convert multi image TIFF to PDF in python?

I'd like to convert multi image TIFF to PDF in python.

I wrote like this code. How ever this code dose not work. How should I change it?


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:])

Upvotes: 3

Views: 9959

Answers (1)

Nori
Nori

Reputation: 2972

I solved this problem. You can convert tiff to pdf easily by this function.

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

You need install Pillow, when you use this function.

Upvotes: 10

Related Questions