Python批量提取pdf首页并合并为一个文件

前情提要:python安装pypdf2包

复制代码
pip install pypdf2

第一种:既需要每一个单独的首页,也需要将首页合并。

整体操作思路,将文件夹下面原本的每一个pdf获取第一页,然后再写出,将其放在FirstPage文件夹下。再读取FirstPage文件夹下面的所有首页的pdf,将其合并为一个文件。

python 复制代码
from PyPDF2 import PdfReader, PdfWriter,  PdfMerger
import os

# 切换到pdf所在工作目录
os.chdir("D:/个人工作/paper202403")
#在上级目录新建一个文件夹
os.mkdir("../FirstPages")

#循环生成第一页PDF
for _ in os.listdir():
    origin_file = PdfReader(_)
    first_page = PdfWriter()
    first_page.add_page(origin_file.pages[0] )
    with open("../FirstPages/{}".format(_), "wb") as f:
        first_page.write(f)

#定义即将读取的指定PDF文件路径,注意文件的顺序,正斜杠/
target_path = '../FirstPages'

pdf_lst = [f for f in os.listdir(target_path) if f.endswith('.pdf')]
pdf_lst = [os.path.join(target_path, filename) for filename in pdf_lst]

# 合并pdf文件
file_merger = PdfMerger()
for pdf in pdf_lst:
    file_merger.append(pdf)
# 合并pdf文件,并输出到指定路径
file_merger.write("../FirstPages/1_outputMerge.pdf")

第二种:只需要一个首页合并,不需要单独的首页。直接在一个Pdfwriter里add所有的首页,然后输出即可。

python 复制代码
from PyPDF2 import PdfReader, PdfWriter
import os


# 切换到pdf所在工作目录
os.chdir("D:/个人工作/paper202403")
#在上级目录新建一个文件夹
os.mkdir("../2FirstPages")

#循环读取文件夹下所有pdf首页,全部添加在first_page中
first_page = PdfWriter()
for _ in os.listdir():
    origin_file = PdfReader(_)
    first_page.add_page(origin_file.pages[0] )  
#写出first_page中所有首页信息
with open("../2FirstPages/2_outputMerge.pdf", "wb") as f:
    first_page.write(f)
相关推荐
张彦峰ZYF1 天前
从“全量 OCR”到按页智能路由:pdf-inspector 与企业 PDF 解析架构的工程化重构
人工智能·pdf·ocr·ai agent·pdf-inspector
SamChan901 天前
Python批量处理PDF踩坑实录:中文编码、字体内嵌、多栏排版与内存占用
python·单片机·ai·pdf·机器翻译
一念春风1 天前
PDF浏览器(WPF C# )
pdf
麻花地2 天前
MinerU 文档解析全指南:从 magic-pdf 到 3.4.5,PDF→Markdown 开源利器深度实战
pdf·开源
2601_967760782 天前
PDF 转图片再转回总翻车?2026 国内免费实测
pdf
zhlx28352 天前
小初高教材 PDF 批量获取|中小学电子课本下载器,支持批量下载带书签 PDF 教材[Windows]
pdf
张某布响丸辣2 天前
Node 16 下用 pdfjs + @napi-rs/canvas 把中文 PDF 渲染成图片
pdf·node·字体映射
weixin_493503673 天前
Vue3 前端生成 PDF:会员证书与活动签到表的三种打印方案与踩坑记录
前端·pdf·状态模式
、如果3 天前
PDF图片文字提取零依赖方案:pymupdf+AI视觉实战
人工智能·数据分析·pdf·图片提取·文字提取·skills