问题描述
我自愿为一个组织创建 ID 卡。使用 Python 中的各种资源编写了一个脚本并创建了图像。现在我将这些图像转换为包含身份证正面和背面的 pdf 文件,作为一个带有持卡人姓名的 pdf 文件。我可以得到名字,但所有的图像都添加到一个 pdf 中。我希望在图像到 pdf 本身的转换时每 2 页拆分一次。
from fpdf import FPDF
import glob
for image in image_list:
print(image.title())
# print(image.index(1))
filename = image.rstrip("_front.png")
filename = filename.rstrip("_back.png")
print(filename)
filename = filename.lstrip("\\D:\\pythonex\\Achyutaashrama\\")
print("final filename--->"+filename)
pdf.add_page()
pdf.image(image,50,110,110)
if (len(pdf.pages)) / 2 == 0:
pdf.output(filename + ".pdf","F")
break
else:
continue
如果我将 pdf.output 行放在 for 循环之外,它会变成一个文件,上面的代码运行时没有任何错误,但不生成任何文件。
请帮忙。
解决方法
如果我理解正确,问题是如何每 2 页创建一个新的 pdf。
如果您确定图像在列表中的位置,这里有一个如何以非常愚蠢的方式拆分pdf文件的示例,可能还有更多更好的想法。
概念是:创建一个新的 FPDF() 实例。
在下面的代码中,我只写了如何拆分文件,每个页面内只有一个字符串:“Hello”和一个数字。
from fpdf import FPDF
def createpdf():
# here I just create a fake list,just to explain how to split the pdf files
image_list_fake = range(10)
count = 1
pdf = FPDF()
for imag in image_list_fake:
pdf.add_page()
pdf.set_font('Arial','B',16)
pdf.cell(40,10,'Hello '+ str(imag))
if count%2 == 0:
# you have to close it ...
pdf.output(str(imag)+'.pdf','F')
# ... and open a new FPDF instance
pdf = FPDF()
count = 1
else:
count += 1