给纯小白的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。
相关推荐
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook1 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田2 天前
使用 pkgutil 实现动态插件系统
python
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战2 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋2 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者3 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者3 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python