如何使用Python将PDF文档的所有页面调整为统一尺寸
Python 批量统一PDF页面尺寸实现方案
依赖准备
使用PyMuPDF库实现,处理性能、内容还原度比常规PDF处理库更稳定,安装命令:pip install pymupdf
支持能力
- 两种尺寸规则可选:对齐原PDF首页尺寸、设置为A4等自定义固定尺寸
- 原页面内容等比缩放无拉伸、无裁切,自动居中放置
- 横向页面内容适配后可自动匹配新尺寸比例,例如横向页面内容适配纵向A4时将居中占页面约一半区域,无内容溢出
- 处理后所有页面尺寸完全一致,可直接解决前端PDF渲染时因页面尺寸不统一导致的坐标映射异常问题
核心实现逻辑
- 读取目标尺寸:若选择对齐首页模式,直接读取PDF第一页的宽高作为全文档统一尺寸;若选择固定尺寸模式,直接传入预设的宽高值(标准A4尺寸为595842磅,对应210297mm)
- 逐页计算缩放参数:对每一个原页面,分别计算宽、高方向适配目标尺寸的缩放比例,取较小值作为最终缩放比,保证内容完整显示
- 内容居中放置:根据缩放后的内容宽高,计算其在新页面中的居中坐标,将原页面内容渲染到新页面对应位置
- 保留原内容属性:文本、矢量图形、注释等内容全部保留,缩放后无模糊、可正常选中
完整可运行代码
import fitz def unify_pdf_size(input_path: str, output_path: str, target_size = "first_page"): """ 统一PDF所有页面尺寸 :param input_path: 原PDF文件路径 :param output_path: 处理后输出路径 :param target_size: 目标尺寸,传"first_page"则对齐首页尺寸,传"a4"则使用标准A4纵向尺寸,也可传入(宽,高)元组自定义尺寸 """ pdf_doc = fitz.open(input_path) # 确定目标尺寸矩形 if target_size == "first_page": target_rect = pdf_doc[0].rect elif target_size == "a4": target_rect = fitz.paper_rect("a4") # 纵向A4,若要横向A4可使用fitz.paper_rect("a4-l") elif isinstance(target_size, tuple) and len(target_size) == 2: target_rect = fitz.Rect(0, 0, target_size[0], target_size[1]) else: raise ValueError("目标尺寸参数不合法") # 新建空白PDF用于存储处理后的内容 output_doc = fitz.open() for page in pdf_doc: original_rect = page.rect # 计算等比缩放比,取宽高缩放的较小值保证内容不裁切 scale = min(target_rect.width / original_rect.width, target_rect.height / original_rect.height) # 计算缩放后内容的居中放置位置 scaled_w = original_rect.width * scale scaled_h = original_rect.height * scale paste_x0 = (target_rect.width - scaled_w) / 2 paste_y0 = (target_rect.height - scaled_h) / 2 paste_rect = fitz.Rect(paste_x0, paste_y0, paste_x0 + scaled_w, paste_y0 + scaled_h) # 创建目标尺寸的新页面 new_page = output_doc.new_page(width=target_rect.width, height=target_rect.height) # 将原页面内容按计算好的位置和缩放比渲染到新页面 new_page.show_pdf_page(paste_rect, pdf_doc, page.number) output_doc.save(output_path) output_doc.close() pdf_doc.close() # 调用示例:将PDF统一为A4尺寸 # unify_pdf_size("input.pdf", "output_a4.pdf", target_size="a4") # 调用示例:将PDF所有页面对齐首页尺寸 # unify_pdf_size("input.pdf", "output_same_first.pdf", target_size="first_page")
使用说明
- 若需要横向A4作为统一尺寸,将代码中
fitz.paper_rect("a4")替换为fitz.paper_rect("a4-l")即可 - 若需要自定义其他尺寸,直接传入(宽度, 高度)的磅值元组即可,1磅=1/72英寸
- 处理后所有页面尺寸完全一致,前端渲染时仅需做一次坐标映射规则计算即可,无需逐页适配尺寸
内容的提问来源于stack exchange,提问作者Kelly
相关产品推荐
相关产品推荐

