python代码进行多个图片合并为pdf:
#python代码进行多个图片合并为pdf:
from PIL import Image
from fpdf import FPDF
import os
def images_to_pdf(image_paths, output_pdf, quality=85):
"""
将多个图片合并为一个PDF文件,并进行适当的压缩。
:param image_paths: 图片文件路径列表
:param output_pdf: 输出的PDF文件路径
:param quality: 图片压缩质量,范围为1-95,默认85
"""
pdf = FPDF()
n=0
for image_path in image_paths:
n=n+1
# 打开图片并调整其质量
img = Image.open(image_path)
if img.mode == 'RGBA':
img = img.convert('RGB')
img.save(f'temp{n}.jpg', 'JPEG', quality=quality)
# 将图片添加到PDF中
pdf.add_page()
pdf.image(f'temp{n}.jpg', 0, 0, 210, 297) # A4尺寸
img.close()#hsxadd
# 删除临时文件
os.remove(f'temp{n}.jpg')
# 保存PDF文件
pdf.output(output_pdf, "F")
# 示例使用
# image_paths = ['image1.jpg', 'image2.jpg', 'image3.jpg']
# output_pdf = 'output.pdf'
image_paths = [
r"D:\Programs\py\pythonProject\data\1.jpg",
r"D:\Programs\py\pythonProject\data\2.jpg",
r"D:\Programs\py\pythonProject\data\3.jpg"
]
output_pdf = r"D:\Programs\py\pythonProject\data\outputzip3.pdf"
images_to_pdf(image_paths, output_pdf)
python代码进行多个PDF合并:
#python代码进行多个PDF合并:
import os
from PyPDF2 import PdfMerger
def merge_pdfs(pdf_files, output_path):
"""
合并多个 PDF 文件
:param pdf_files: 包含 PDF 文件路径的列表
:param output_path: 合并后的 PDF 文件输出路径
"""
merger = PdfMerger()
for pdf_file in pdf_files:
if os.path.exists(pdf_file):
merger.append(pdf_file)
else:
print(f"文件 {pdf_file} 不存在,跳过。")
merger.write(output_path)
merger.close()
print(f"合并完成,输出文件: {output_path}")
# 示例使用
pdf_files = [r"D:\Programs\py\pythonProject\data\output.pdf", r"D:\Programs\py\pythonProject\data\outputzip2.pdf", r"D:\Programs\py\pythonProject\data\outputzip3.pdf"]
output_path = r"D:\Programs\py\pythonProject\data\merged_output.pdf"
merge_pdfs(pdf_files, output_path)