'Add text between images in PIL
In the code below, I would like to add some text between each image. It looks like the final line is just appending them together so I am struggling to add the text between each image (in a loop). Thanks.
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)
Solution 1:[1]
Pillow doesn't support writing text to PDFs, only images. So, you need to resort to using other libraries. The simplest approach is using FPDF and 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")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
