方法1
import os from PyPDF2 import PdfFileReader,PdfFileMerger from reportlab.lib.pagesizes import A4,landscape,portrait from reportlab.pdfgen import canvas # pip3 install PyPDF2 # pip3 install reportlab def jpg_to_pdf(img_dir='./images/',pdf_name = 'result1.pdf'): list_jpgs=[os.path.join(img_dir,fn) for fn in os.listdir(img_dir) if fn.endswith('jpeg')] if not list_jpgs:return result_pdf=PdfFileMerger() temp_pdf='temp.pdf' for i in sorted(list_jpgs): cnv=canvas.Canvas(temp_pdf,pagesize=portrait(A4)) cnv.drawImage(i,0,0,*portrait(A4)) cnv.save() with open(temp_pdf,'rb') as f: pdf_reader=PdfFileReader(f) result_pdf.append(pdf_reader) result_pdf.write(pdf_name) result_pdf.close() 方法2
# pip install PyMuPDF def pic2pdf(img_dir='./images/', pdf_name='result.pdf'): import fitz import glob import os doc = fitz.open() temp_pdf = 'temp.pdf' for img in sorted(glob.glob("{}/*".format(img_dir))): # 读取图片,确保按文件名排序 imgdoc = fitz.open(img) # 打开图片 pdfbytes = imgdoc.convert_to_pdf() # 使用图片创建单页的 PDF imgpdf = fitz.open("pdf", pdfbytes) doc.insert_pdf(imgpdf) # 将当前页插入文档 if os.path.exists(temp_pdf):os.remove(temp_pdf) doc.save(pdf_name) # 保存pdf文件 doc.close()