Skip to content

Commit

Permalink
Fix Page.extract_table(...) when no table found
Browse files Browse the repository at this point in the history
Return None instead of crashing.

Fixes #216
  • Loading branch information
jsvine committed May 28, 2020
1 parent 8110430 commit d64afa8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
4 changes: 4 additions & 0 deletions pdfplumber/page.py
Expand Up @@ -174,6 +174,10 @@ def extract_tables(self, table_settings={}):

def extract_table(self, table_settings={}):
tables = self.find_tables(table_settings)

if len(tables) == 0:
return None

# Return the largest table, as measured by number of cells.
sorter = lambda x: (-len(x.cells), x.bbox[1], x.bbox[0])
largest = list(sorted(tables, key=sorter))[0]
Expand Down
11 changes: 10 additions & 1 deletion tests/test-issues.py
Expand Up @@ -148,8 +148,17 @@ def test_issue_140(self):
cropped_page = page.crop((0, 0, page.width, 122))
assert len(cropped_page.extract_table()) == 5


def test_issue_203(self):
path = os.path.join(HERE, "pdfs/issue-203-decimalize.pdf")
with pdfplumber.open(path) as pdf:
assert len(pdf.objects)

def test_issue_216(self):
"""
.extract_table() should return None if there's no table,
instead of crashing
"""
path = os.path.join(HERE, "pdfs/issue-140-example.pdf")
with pdfplumber.open(path) as pdf:
cropped = pdf.pages[0].crop((0, 0, 1, 1))
assert cropped.extract_table() is None

0 comments on commit d64afa8

Please sign in to comment.