给纯小白的Python操作 PDF 笔记

一、文件基础

  1. 打开与关闭

    • 推荐用 with open(path, mode, encoding='utf-8') as f:,自动完成 close(),避免泄露文件句柄。
    • 常见模式:'r' 读,'w' 写覆盖,'a' 追加,'rb'/'wb' 二进制。
    • Windows 默认编码为 GBK,Linux/Mac 为 UTF-8;跨平台脚本务必显式指定 encoding。
  2. 文本读写

    • f.read() 一次读全部;f.readline() 逐行;f.readlines() 得列表。
    • 追加写入:with open('test.txt','a',encoding='utf-8') as f: f.write('xxx')
  3. 路径与编码错误

    • 绝对路径:C:/Users/...(正斜杠或双反斜杠)。
    • 相对路径:以脚本所在目录为基准,可用 os.path.join() 拼接。
    • 遇到 UnicodeDecodeError 时,尝试 encoding='utf-8-sig''gbk'

二、PDF 处理(PyPDF2 + pdfplumber 组合拳)

  1. 环境准备

    复制代码
    pip install PyPDF2 pdfplumber pandas -i https://pypi.tuna.tsinghua.edu.cn/simple
  2. 读取文字

python 复制代码
   import pdfplumber
   with pdfplumber.open('demo.pdf') as pdf:
       for page in pdf.pages:
           print(page.extract_text())
  1. 读取表格
python 复制代码
   all_tables = []
   with pdfplumber.open('demo.pdf') as pdf:
       for p in pdf.pages:
           for table in p.extract_tables():
               all_tables.extend([row for row in table if any(row)])
   df = pd.DataFrame(all_tables)
   df.to_excel('pdf_table.xlsx', index=False, header=False)
  1. 合并 PDF(PyPDF2)
python 复制代码
   from PyPDF2 import PdfMerger
   merger = PdfMerger()
   for pdf in ['1.pdf', '2.pdf']:
       merger.append(pdf)
   merger.write('merged.pdf')
   merger.close()
  1. 添加水印(注意层级顺序)
python 复制代码
   from PyPDF2 import PdfFileReader, PdfFileWriter

   base = PdfFileReader('src.pdf')
   watermark = PdfFileReader('water.pdf').getPage(0)
   writer = PdfFileWriter()

   for i in range(base.getNumPages()):
       page = base.getPage(i)
       # 先底层内容,后水印;若水印被文字遮挡,可调整水印透明度或在生成水印 PDF 时放到底层
       page.mergePage(watermark)   # mergePage 会把两页叠加,watermark 在上层
       writer.addPage(page)

   with open('res_watermarked.pdf', 'wb') as f:
       writer.write(f)

课堂踩坑:水印盖字 → 在水印 PDF 里把文字透明度降低或置底后再合并。

  1. Word → PDF(Windows 专用,pypiwin32)
python 复制代码
   import win32com.client as win32
   word = win32.Dispatch('Word.Application')
   doc = word.Documents.Open(r'C:\abs\path\template.docx')
   doc.ExportAsFixedFormat('template.pdf', 17)  # 17=pdf
   doc.Close(); word.Quit()

三、实战小结

  • 文件操作牢记 with+encoding;PDF 处理分清 pdfplumber(读取)与 PyPDF2(编辑)。
  • 合并、加水印前先用小文件调试,避免一次性加载大 PDF 导致内存爆炸。
  • 路径/编码问题优先排查打印 os.getcwd() 与显式 encoding。
相关推荐
fqbqrr2 小时前
2606C++,C++构的多态
开发语言·c++
biter down2 小时前
从 0 到 1 搭建 Python 接口自动化测试框架(博客系统实战)
开发语言·python
肖永威4 小时前
Python多业务并行计算框架插件化演进:从硬编码到动态注册
python·插件化·并行计算·动态注册
yz_aiks4 小时前
Linux Jar包配置Systemd自启动实战:从排查到配置全流程
linux·python·jar·自启动·systemd
threelab4 小时前
Three.js 物理模拟着色器 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
武器大师724 小时前
lv_binding_js 代码解读
开发语言·javascript·ecmascript
不知名的老吴4 小时前
线程的生命周期之线程“插队“
java·开发语言·python
kaikaile19955 小时前
数字全息图处理系统(C# 实现)
开发语言·c#
xsc6996755 小时前
从零搭建大模型与智能体平台 - 完整技术详解
python