You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PyPDF2的PdfFileMerger在PDF文件间插入空白页

解决方案

你现有脚本跑不通的核心原因有两点:

  • 调用merger.addBlankPage(w,h)时没有定义w和h两个参数,运行会直接报NameError
  • 循环不加判断给所有文件后都加空白页的话,最后一份账单末尾会多一张无用空纸,完全没必要

修改思路

  • 补导入PdfFileReader,用来读取每份账单的实际页面宽高,保证插入的空白页和原账单纸张尺寸完全匹配,不会出现页面大小错配的问题
  • 遍历文件时加判断:只有当前处理的不是最后一份账单,才在后面插入空白页
  • 空白页尺寸直接取当前账单第一页的参数即可,不用手动硬编码A4尺寸,不管账单是什么规格都能自动适配

修正后可直接运行的代码

# 提示缺PyPDF2模块的话,命令行执行 pip install PyPDF2 安装
import os
from os import listdir, mkdir, startfile
from os.path import isfile, join, exists
from PyPDF2 import PdfFileMerger, PdfFileReader

# 读取目标文件夹下所有PDF文件
path = input("Enter the folder location: ")
pdffiles = [f for f in listdir(path) if isfile(join(path, f)) and '.pdf' in f]
print('\nList of PDF Files:\n')
for file in pdffiles:
    print(file)

# 设置输出文件名
resultFile = input("\nEnter the name of the result file : ")
if '.pdf' not in resultFile:
    resultFile += '.pdf'

merger = PdfFileMerger()
total_files = len(pdffiles)
for idx, pdf in enumerate(pdffiles):
    pdf_abs_path = join(path, pdf)
    merger.append(pdf_abs_path)
    # 不是最后一个文件才插入空白页
    if idx != total_files - 1:
        # 取当前PDF第一页的尺寸作为空白页尺寸
        cur_pdf_reader = PdfFileReader(pdf_abs_path)
        first_page = cur_pdf_reader.getPage(0)
        page_w = first_page.mediaBox.getWidth()
        page_h = first_page.mediaBox.getHeight()
        merger.addBlankPage(width=page_w, height=page_h)

# 不存在输出目录则新建
output_path = join(path, 'Output')
if not exists(output_path):
    mkdir(output_path)

# 写出合并后的文件
result_abs_path = join(output_path, resultFile)
merger.write(result_abs_path)
merger.close()

# 自动打开生成好的文件
print(f'\n{resultFile} 已成功生成,存储路径为:{output_path}')
startfile(result_abs_path)

效果说明

  • 每份3页的账单后面刚好补1张空白页,双面打印时每份账单占2张纸,下一份账单的首页永远在新纸正面,不会打到上一份账单的背面
  • 最后一份账单末尾不会追加多余空白页,不浪费纸张
  • 用os.path.join拼接路径替代硬编码的反斜杠,不会出现Windows/macOS路径格式不兼容的问题

内容的提问来源于stack exchange,提问作者Josh Scoville

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 20:36:29