From df00787adae64af94f899b83e5909fefd53a5574 Mon Sep 17 00:00:00 2001 From: Jeremy Singer-Vine Date: Sun, 12 Jan 2020 23:06:48 -0500 Subject: [PATCH] Prevent custom LAParams from raising exception Issue #168 / PR #169. Many thanks to @frascuchon for submitting the PR, which is the source for the code/idea in this commit. --- README.md | 1 + pdfplumber/page.py | 18 +++--------------- tests/test-basics.py | 19 ++++++++++++------- 3 files changed, 16 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index c5d3a2f..c23b2eb 100644 --- a/README.md +++ b/README.md @@ -375,6 +375,7 @@ Many thanks to the following users who've contributed ideas, features, and fixes - [@meldonization](https://github.com/meldonization) - [Oisín Moran](https://github.com/OisinMoran) - [Samkit Jain](https://github.com/samkit-jain) +- [Francisco Aranda](https://github.com/frascuchon) ## Contributing diff --git a/pdfplumber/page.py b/pdfplumber/page.py index ed77c4e..2955208 100644 --- a/pdfplumber/page.py +++ b/pdfplumber/page.py @@ -81,20 +81,6 @@ class Page(Container): h - d(y) ) - IGNORE = [ - "bbox", - "matrix", - "_text", - "_objs", - "groups", - "stream", - "colorspace", - "ncs", - "graphicstate", - "imagemask", - "pts", - ] - noop = lambda x: x str_conv = lambda x: str(x or "") @@ -135,10 +121,12 @@ class Page(Container): "stroking_color": noop, } + CONVERSIONS_KEYS = set(CONVERSIONS.keys()) + def process_object(obj): attr = dict((k, CONVERSIONS[k](resolve_all(v))) for k, v in obj.__dict__.items() - if k not in IGNORE) + if k in CONVERSIONS_KEYS) kind = re.sub(lt_pat, "", obj.__class__.__name__).lower() attr["object_type"] = kind diff --git a/tests/test-basics.py b/tests/test-basics.py index 8159a82..57d5a04 100644 --- a/tests/test-basics.py +++ b/tests/test-basics.py @@ -53,13 +53,18 @@ class Test(unittest.TestCase): def test_password(self): path = os.path.join(HERE, "pdfs/password-example.pdf") - pdf = pdfplumber.open(path, password = "test") - assert(len(pdf.chars) > 0) - pdf.close() + with pdfplumber.open(path, password = "test") as pdf: + assert(len(pdf.chars) > 0) def test_colors(self): path = os.path.join(HERE, "pdfs/nics-background-checks-2015-11.pdf") - pdf = pdfplumber.open(path) - rect = pdf.pages[0].rects[0] - assert rect['non_stroking_color'] == [0.8, 1, 1] - pdf.close() + with pdfplumber.open(path) as pdf: + rect = pdf.pages[0].rects[0] + assert rect['non_stroking_color'] == [0.8, 1, 1] + + def test_load_with_custom_laparams(self): + # See https://github.com/jsvine/pdfplumber/issues/168 + path = os.path.join(HERE, "pdfs/cupertino_usd_4-6-16.pdf") + laparams = dict(line_margin = 0.2) + with pdfplumber.open(path, laparams = laparams) as pdf: + assert float(pdf.pages[0].chars[0]["top"]) == 61.656