pdfplumber是一个用于从 PDF 文件中提取文本、表格和元数据的 Python 库特别擅长处理含复杂布局如多栏、合并单元格、不规则表格的 PDF。它基于pdfminer.six但提供了更友好、更直观的 API。安装方式pipinstallpdfplumber基本使用示例提取文本importpdfplumberwithpdfplumber.open(example.pdf)aspdf:full_textforpageinpdf.pages:full_textpage.extract_text()or# extract_text() 可能返回 Noneprint(full_text)提取表格示例withpdfplumber.open(example.pdf)aspdf:forpageinpdf.pages:tablespage.extract_tables()# 返回列表每个元素是二维列表表格fortableintables:print(table)注意事项中文支持需确保 PDF 内嵌字体且编码正确若乱码可尝试设置layoutTrue或配合pdfplumber.open(..., passwordxxx)解密。性能较慢逐页解析大文件建议按需处理页码。不支持直接编辑或生成 PDF仅用于提取。在pdfplumber中可以通过page.crop(bbox)方法先裁剪页面指定矩形区域bounding box再在该子区域内调用extract_text()或extract_words()等方法从而实现精准提取指定坐标范围内的文本。✅坐标系说明重要pdfplumber 使用 PDF 标准坐标系原点(0, 0)在左下角x向右递增y向上递增bbox (x0, y0, x1, y1)表示矩形区域其中x0,y0左下角横纵坐标x1,y1右上角横纵坐标要求x0 x1且y0 y1。操作步骤打开 PDF定位目标页使用page.crop((x0, y0, x1, y1))获取裁剪后的CroppedPage对象在裁剪页上调用extract_text()支持layoutTrue/False、keep_blank_chars等参数可选用page.debug_tablefinder({})可视化表格区域辅助定位。 示例代码importpdfplumberwithpdfplumber.open(report.pdf)aspdf:pagepdf.pages[0]# 第一页# 示例提取左上角约 100×50 区域注意 y 坐标从底向上# 假设页面高度为 page.height ≈ 792如 Letter 尺寸则顶部区域 y 范围约为 height-50 到 heightbbox(50,page.height-100,200,page.height-50)# (x0, y0, x1, y1)croppedpage.crop(bbox)textcropped.extract_text()print(指定区域文本,textor[无文本]) 提示若不确定坐标可用page.to_image().draw_rect(bbox).save(debug.png)可视化验证需安装Pillow和opencv-python或pdfplumber[plot]支持链式调用page.crop(...).extract_text()crop()也适用于extract_tables()、extract_words()等提升精度和性能。
`pdfplumber` 是一个用于从 PDF 文件中提取文本、表格和元数据的 Python 库
发布时间:2026/6/16 1:26:15
pdfplumber是一个用于从 PDF 文件中提取文本、表格和元数据的 Python 库特别擅长处理含复杂布局如多栏、合并单元格、不规则表格的 PDF。它基于pdfminer.six但提供了更友好、更直观的 API。安装方式pipinstallpdfplumber基本使用示例提取文本importpdfplumberwithpdfplumber.open(example.pdf)aspdf:full_textforpageinpdf.pages:full_textpage.extract_text()or# extract_text() 可能返回 Noneprint(full_text)提取表格示例withpdfplumber.open(example.pdf)aspdf:forpageinpdf.pages:tablespage.extract_tables()# 返回列表每个元素是二维列表表格fortableintables:print(table)注意事项中文支持需确保 PDF 内嵌字体且编码正确若乱码可尝试设置layoutTrue或配合pdfplumber.open(..., passwordxxx)解密。性能较慢逐页解析大文件建议按需处理页码。不支持直接编辑或生成 PDF仅用于提取。在pdfplumber中可以通过page.crop(bbox)方法先裁剪页面指定矩形区域bounding box再在该子区域内调用extract_text()或extract_words()等方法从而实现精准提取指定坐标范围内的文本。✅坐标系说明重要pdfplumber 使用 PDF 标准坐标系原点(0, 0)在左下角x向右递增y向上递增bbox (x0, y0, x1, y1)表示矩形区域其中x0,y0左下角横纵坐标x1,y1右上角横纵坐标要求x0 x1且y0 y1。操作步骤打开 PDF定位目标页使用page.crop((x0, y0, x1, y1))获取裁剪后的CroppedPage对象在裁剪页上调用extract_text()支持layoutTrue/False、keep_blank_chars等参数可选用page.debug_tablefinder({})可视化表格区域辅助定位。 示例代码importpdfplumberwithpdfplumber.open(report.pdf)aspdf:pagepdf.pages[0]# 第一页# 示例提取左上角约 100×50 区域注意 y 坐标从底向上# 假设页面高度为 page.height ≈ 792如 Letter 尺寸则顶部区域 y 范围约为 height-50 到 heightbbox(50,page.height-100,200,page.height-50)# (x0, y0, x1, y1)croppedpage.crop(bbox)textcropped.extract_text()print(指定区域文本,textor[无文本]) 提示若不确定坐标可用page.to_image().draw_rect(bbox).save(debug.png)可视化验证需安装Pillow和opencv-python或pdfplumber[plot]支持链式调用page.crop(...).extract_text()crop()也适用于extract_tables()、extract_words()等提升精度和性能。