这是示例代码,主要处理PDF的去白边,再将尺寸调整为A4标准大小。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import fitz  # PyMuPDF

# 打开PDF文件
pdf_path = 'input.pdf'
pdf_document = fitz.open(pdf_path)

# 创建一个新的PDF文件
output_pdf_path = 'utput.pdf'
output_pdf_document = fitz.open()

# 白边裁剪尺寸
margin = 8

# 遍历每一页PDF并调整大小
for page_number in range(len(pdf_document)):
# 获取原始页面
page = pdf_document[page_number]

# 获取页面大小
page_width = page.rect.width
page_height = page.rect.height

# 计算裁剪后的页面大小
crop_width = page_width - 2 * margin
crop_height = page_height - 2 * margin

# 定义裁剪区域
crop_rect = fitz.Rect(margin, margin, margin + crop_width, margin + crop_height)

# 将页面转换为图像 (裁剪白边)
pix = page.get_pixmap(dpi=150, clip=crop_rect)
image = fitz.Pixmap(fitz.csRGB, pix)

# 计算调整后的页面大小
A4_width = 595 # A4纸的宽度
adjusted_height = int(crop_height * A4_width / crop_width)

# 创建新页面并插入调整后的图像
output_pdf_page = output_pdf_document.new_page(width=A4_width, height=adjusted_height)
output_pdf_page.insert_image(output_pdf_page.rect, pixmap=image)

# 保存新的PDF文件
output_pdf_document.save(output_pdf_path)

output_pdf_document.close()
pdf_document.close()

print("转换完成!")