首页 > 解决方案 > 如何在 PDF 文件中查找表格网格线?

问题描述

为了更准确地提取嵌入在表格单元格中的类似表格的数据,我希望能够识别 PDF 中的表格单元格边界,如下所示:

pdf表格示例

我曾尝试使用 Camelot、pdfplumber 和 PyMuPDF 提取此类表,并取得了不同程度的成功。但由于我们收到的 PDF 不一致,即使指定表格边界,我也无法可靠地获得准确的结果。

我发现如果我通过明确指定单元格边界来单独提取每个表格单元格,结果会更好。我已经通过手动输入边界进行了测试,这是我使用 Camelot 的可视化调试工具获得的。

我的挑战是如何以编程方式识别表格单元格边界,因为表格可能从页面上的任何位置开始,并且单元格的垂直高度可变。

在我看来,可以通过查找行分隔线的坐标来做到这一点,这对人类来说在视觉上是如此明显。但我还没有弄清楚如何使用 python 工具找到这些行。这是可能的,还是有其他/更好的方法来解决这个问题?

标签: pythonpdf-extractionpython-camelotpymupdfpdfplumber

解决方案


我最近有一个类似的用例,我需要通过代码本身找出边界。对于您的用例,有两种选择:

  1. 如果要识别整个表的边界,可以执行以下操作:
import pdfplumber
pdf = pdfplumber.open('file_name.pdf')
p0 = pdf.pages[req_page] # go to the required page

tables = p0.debug_tablefinder() # list of tables which pdfplumber identifies
req_table = tables.tables[i] # Suppose you want to use ith table

req_table.bbox # gives you the bounding box of the table (coordinates)
  1. 您想访问表格中的每个单元格并从中提取单词:
import pdfplumber
pdf = pdfplumber.open('file_name.pdf')
p0 = pdf.pages[req_page] # go to the required page

tables = p0.debug_tablefinder() # list of tables which pdfplumber identifies
req_table = tables.tables[i] # Suppose you want to use ith table

cells = req_table.cells # gives list of all cells in that table

for cell in cells[i:j]: # iterating through the required cells
    p0.crop(cell).extract_words() # extract the words 

推荐阅读