使用python语言,利用python的第三方库,实现多照片(.png,.jpeg,.jpg等格式),转成pdf格式,再将多个pdf合并为一个pdf文件。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/07/08 18:39
# @Author :
# @Site :
# @File : test05.py
# @Project : PythonCode
# @Software: vscode
# 照片转pdf,多图转多个pdf,多图转单个pdf,pdf合并
#
# coding = UTF-8
# 导入Python标准库
import os
from decimal import Decimal
from PIL import Image
from io import BytesIO
from PyPDF2 import PdfMerger,PdfReader, PdfWriter
# 导入第三方库
# 防止中文乱码
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
#支持的图片文件格式
SUPPORT_SUFFIX = ["jpg", "jpeg", "png"]
def pic_to_pdf(image_bytes: bytes) -> bytes:
"""将单个图片转换为单张PDF
:param image_bytes: 图片的bytes对象
:return: PDF的bytes对象
"""
# 将bytes对象转换为BytesIO对象
image_bytes_io = BytesIO(image_bytes)
# 从内存中读取图片
image_object = Image.open(image_bytes_io)
# 打开内存中的文件用于保存PDF
with BytesIO() as result_bytes_io:
# 将图片保存为单张PDF
image_object.save(result_bytes_io, "PDF", resolution=100.0)
# 获取内存中的文件
data = result_bytes_io.getvalue()
# 返回PDF的bytes对象
return data
def validate_directory(directory: str) -> bool:
"""验证目录是否存在且安全"""
if not os.path.isdir(directory):
return False
return True
def batch_convert(image_path: str, pdf_path: str) -> None:
"""批量将图片转换为单张PDF"""
if not validate_directory(image_path) or not validate_directory(pdf_path):
raise ValueError("提供的路径不合法或不存在")
try:
# 遍历文件夹下所有文件
for root, dirs, files in os.walk(image_path, topdown=False):
for name in files:
if 'pdf' in name:
continue
# 提取文件的后缀名
file_suffix = os.path.splitext(name)[-1].lstrip(".").lower()
# 检测该文件格式是否受到支持
if file_suffix not in SUPPORT_SUFFIX:
continue
# 拼接出图片文件的绝对路径
source_file_path = os.path.join(root, name)
# 拼接出PDF文件的绝对路径
target_file_path = os.path.join(pdf_path, f"{os.path.splitext(name)[0]}.pdf")
# 将图片文件转换为PDF文件
with open(source_file_path, "rb") as source:
with open(target_file_path, "wb") as target:
target.write(pic_to_pdf(source.read()))
except IOError as e:
print(f"文件操作失败: {e}")
except PermissionError as e:
print(f"权限不足: {e}")
except Exception as e:
print(f"转换过程中发生未知错误: {e}")
def mergePdf(i, pdf_list):
# 将所有 PDF 合并成一个文件
merger = PdfMerger()
writer = PdfWriter()
# 获取标准A4纸张尺寸
a4_width_mm = 210.0
a4_height_mm = 297.0
mm_to_points = 72 / 25.4 # 每毫米等于多少点
a4_width_points =a4_width_mm * mm_to_points
a4_height_points = a4_height_mm * mm_to_points
# for file_path in pdf_list:
# merger.append(str(file_path))
for file_path in pdf_list:
reader = PdfReader(file_path)
for page in reader.pages:
# 获取当前页面尺寸
current_width = page.mediabox.width
current_height = page.mediabox.height
# 计算缩放比例
scale_x =a4_width_points / float(current_width)
scale_y = a4_height_points/ float(current_height)
# 使用较小的缩放比例以确保页面适合A4纸张
scale = min(scale_x, scale_y)
# 应用缩放
page.scale(scale, scale)
# 将调整后的页面添加到输出文档
writer.add_page(page)
writer.write(f"{Output_path}/output.pdf")
if __name__ == '__main__':
Output_path = "E:/output" # 输出路径
pics_path = "D:/image" # 图片路径
batch_convert(pics_path, pics_path) # 批量转换
pdf_list = []
for i in os.listdir(pics_path):
if "pdf" in i:
pdf_list.append(os.path.join(pics_path, i ))
mergePdf('_all', pdf_list)