在 PIL 中的图像之间添加文本

Add text between images in PIL

在下面的代码中,我想在每张图片之间添加一些文字。看起来最后一行只是将它们附加在一起,所以我很难在每个图像之间添加文本(在一个循环中)。谢谢

def merge_into_pdf(paths, name):    
    list_image = []
    # Create list of images from list of path
    for i in paths:
        list_image.append(Image.open(f'''Images/{i}''').convert("RGB"))
    # merge into one pdf
    if len(list_image) == 0:
        return
    # get first element of list and pop it from list
    img1 = list_image[0]
    list_image.pop(0)
    # append all images and save as pdf
    img1.save(f"{name}.pdf",save_all=True, append_images=list_image)

Pillow 不支持将文本写入 PDF,仅支持图像。因此,您需要求助于使用其他库。最简单的方法是使用 FPDF 和 PyPDF2:

from PIL import Image
from fpdf import FPDF
from PyPDF2 import PdfFileReader, PdfFileWriter
from os import system


def merge_into_pdf(paths, captions, name):
    list_image = []
    # Create list of images from list of path
    for i in paths:
        list_image.append(Image.open(f'''Images/{i}''').convert("RGB"))
    # merge into one pdf
    if len(list_image) == 0:
        return
    # get first element of list and pop it from list
    img1 = list_image[0]
    list_image.pop(0)
    # append all images and save as pdf
    img1.save("images.pdf",save_all=True, append_images=list_image)

    #Save captions to a new file using FPDF
    pdf = FPDF()
    pdf.set_font("Times", size = 50)

    for caption in captions:
        pdf.add_page()
        pdf.cell(500, 0, txt = caption,
        ln = 2, align = 'L')

    pdf.output("captions.pdf")

    #Merge the two files using PyPDF2
    pdfWriter = PdfFileWriter()
    image_pdf = PdfFileReader(open("images.pdf", "rb"))
    caption_pdf = PdfFileReader(open("captions.pdf","rb"))

    for index,page in enumerate(paths):
        page = image_pdf.getPage(index)
        page.mergePage(caption_pdf.getPage(index))
        pdfWriter.addPage(page)


    with open(f"{name}.pdf", "wb") as outputPdf:
        pdfWriter.write(outputPdf)

    system("rm images.pdf")
    system("rm captions.pdf")