用DeepSeek开发PDF神器!一键去水印及A3转A4,附完整代码
经常遇到老师发的一些需要打印的PDF,用扫描王扫的PDF,右下角有水印,有的是A3格式,直接打印成A4的话,字又太小了,需要将左右或上下分割成A4来打印,最近DeepSeek比较火,于是用它来开发PDF工具,解决这些问题。
向DeepSeek提问:
你好DeepSeek!我需要一段Python代码实现以下功能:
- PDF页面分割:将PDF每页从上下中间均分为2页
- 格式转换:分割后的页面逆时针旋转90度,并按A4尺寸上下左右居中显示
- 输出规则:原3页PDF生成6页新PDF
请提供完整代码,并推荐适合的UI库及打包exe方案。
代码实现(基于PyMuPDF):
import fitz # PyMuPDF
from PIL import Image # Pillow
def process_pdf(input_path, output_path):
"""处理PDF文件的主函数"""
src_doc = fitz.open(input_path)
dst_doc = fitz.open()
# 定义标准A4尺寸(单位:点)
a4_width, a4_height = fitz.paper_size("a4")
for page in src_doc:
# 计算裁剪区域(坐标系原点在页面左上角)
original_rect = page.rect
crop_area = fitz.Rect(
original_rect.width * 0.03, # 左边界:5%
0, # 上边界:0
original_rect.width * 0.97, # 右边界:95%
original_rect.height * 0.94 # 下边界:90%
)
# 创建空白A4页面
new_page = dst_doc.new_page(width=a4_width, height=a4_height)
# 计算自适应缩放比例
content_width = crop_area.width
content_height = crop_area.height
scale_factor = min(
a4_width / content_width,
a4_height / content_height
)
# 计算居中位置
target_width = content_width * scale_factor
target_height = content_height * scale_factor
pos_x = (a4_width - target_width) / 2
pos_y = (a4_height - target_height) / 2
# 将裁剪内容插入新页面(保持矢量图形)
new_page.show_pdf_page(
fitz.Rect(pos_x, pos_y, pos_x + target_width, pos_y + target_height),
src_doc,
page.number,
clip=crop_area
)
# 优化输出文件大小
dst_doc.save(output_path, garbage=3, deflate=True)
print(f"处理完成,已保存至:{output_path}")
#上下分割
def split_pdf_updown_centered(input_pdf_path, output_pdf_path):
# 打开原始PDF文件
pdf_document = fitz.open(input_pdf_path)
# 创建新的PDF文档
new_pdf_document = fitz.open()
# A4尺寸(以点为单位)
a4_width = 842 # 210mm
a4_height = 595 # 297mm
# 遍历每一页
for page_num in range(len(pdf_document)):
page = pdf_document.load_page(page_num)
original_rect = page.rect
original_width = original_rect.width
original_height = original_rect.height
# 计算上下分割区域
top_rect = fitz.Rect(0, 0, original_width, original_height / 2)
bottom_rect = fitz.Rect(0, original_height / 2, original_width, original_height)
for clip_rect in [top_rect, bottom_rect]:
# 创建A4页面
new_page = new_pdf_document.new_page(width=a4_width, height=a4_height)
# 计算缩放比例(保持内容完整)
scale_w = a4_width / original_width
scale_h = a4_height / (original_height / 2)
scale = min(scale_w, scale_h) # 取最小比例避免溢出
# 计算缩放后的内容尺寸
scaled_width = original_width * scale*0.99
scaled_height = (original_height / 2) * scale*0.99
# 计算居中偏移量
x_offset = (a4_width - scaled_width) / 2
y_offset = (a4_height - scaled_height) / 2
# 将分割后的内容插入到A4页面
new_page.show_pdf_page(
fitz.Rect(x_offset, y_offset, x_offset + scaled_width, y_offset + scaled_height),
pdf_document,
page_num,
clip=clip_rect
)
new_page.set_rotation(270)
# 保存并清理
new_pdf_document.save(output_pdf_path)
pdf_document.close()
new_pdf_document.close()
print(f"生成成功!新PDF路径: {output_pdf_path}")
功能说明:
- 使用PyMuPDF库实现页面分割、旋转和居中排版
- 旋转后内容自动适应A4尺寸,保持比例不变形
- 每页分割成2页,满足文档打印需求
向DeepSeek补充提问:
- 如何实现右下方去除水印,如“XX扫描王”等
- 如何实现水平左右分割?
- 如何添加UI界面?
- 如何打包为exe?
最终实现如下图所示工具
需要全部源码或exe工具的请关注博主,并留言 pdf工具