1. 需要先安装两个模块
pip3 install fitz
pip3 install PyMuPDF
2. 脚本如下
import fitz
import os
from functools import cmp_to_key
# 过滤掉当前目录除jpg以外的文件
def file_filter(tmp):
if tmp[-4:] in [".jpg"]:
return True
return False
jpg_names = list(filter(file_filter, os.listdir("./")))
# 按照数字大小排序,避免顺序错误
# 排序后列表0.jpg 1.jpg ... 9.jpg 10.jpg
def cmp(x, y):
return int(x[0:-4]) - int(y[0:-4])
jpg_names = sorted(jpg_names, key=cmp_to_key(cmp))
# 将jpg转成pdf后合并
pdf = fitz.open()
for i in range(len(jpg_names)):
pdfbytes = fitz.open(jpg_names[i]).convert_to_pdf()
imgpdf = fitz.open(f"{jpg_names[i][0:-4]}.pdf", pdfbytes)
pdf.insert_pdf(imgpdf)
pdf.save("combined.pdf")
pdf.close()
标签:return,python,jpg,fitz,names,pdf,cmp
From: https://www.cnblogs.com/wstong2052/p/17206820.html