From 381bc6ba02cfa63a741d05f919347329fea9e8ee Mon Sep 17 00:00:00 2001 From: Jeremy Singer-Vine Date: Tue, 8 Mar 2016 09:47:23 -0500 Subject: [PATCH] Add utils.filter_objects(...) and Page.filter(...) --- pdfplumber/page.py | 18 +++++++++++++++++- pdfplumber/utils.py | 10 ++++++++++ tests/test-nics-background-checks-2015-11.py | 11 +++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/pdfplumber/page.py b/pdfplumber/page.py index 7cd45b6..5c8833c 100644 --- a/pdfplumber/page.py +++ b/pdfplumber/page.py @@ -180,10 +180,12 @@ class Page(Container): x_tolerance=x_tolerance, y_tolerance=y_tolerance) - def crop(self, bbox, strict=False): return CroppedPage(self, bbox, strict=strict) + def filter(self, fn): + return FilteredPage(self, fn) + class CroppedPage(Page): def __init__(self, parent_page, bbox, strict=False): self.parent_page = parent_page @@ -202,3 +204,17 @@ class CroppedPage(Page): self.bbox, **kwargs) return self._objects + +class FilteredPage(Page): + def __init__(self, parent_page, fn): + self.parent_page = parent_page + self.fn = fn + + @property + def objects(self): + if hasattr(self, "_objects"): return self._objects + self._objects = utils.filter_objects( + self.parent_page.objects, + self.fn + ) + return self._objects diff --git a/pdfplumber/utils.py b/pdfplumber/utils.py index aa29b2d..cd36f2d 100644 --- a/pdfplumber/utils.py +++ b/pdfplumber/utils.py @@ -195,6 +195,16 @@ def find_gutters(chars, orientation, min_size=5): gutters = gutters + [ end_max + Decimal('0.001') ] return gutters +def filter_objects(objs, fn): + if isinstance(objs, dict): + return dict((k, filter_objects(v, fn)) + for k,v in objs.items()) + + initial_type = type(objs) + objs = to_list(objs) + filtered = filter(fn, objs) + + return initial_type(filtered) def point_inside_bbox(point, bbox): px, py = point diff --git a/tests/test-nics-background-checks-2015-11.py b/tests/test-nics-background-checks-2015-11.py index 37d81f6..536be37 100644 --- a/tests/test-nics-background-checks-2015-11.py +++ b/tests/test-nics-background-checks-2015-11.py @@ -101,3 +101,14 @@ class Test(unittest.TestCase): month_chars = within_bbox(page.chars, (0, 35, self.PDF_WIDTH, 65)) month_text = collate_chars(month_chars, x_tolerance=2) assert(month_text == "November - 2015") + + def test_filter(self): + page = self.pdf.pages[0] + def test(obj): + if obj["object_type"] == "char": + if obj["size"] < 20: + return False + return True + filtered = page.filter(test) + text = filtered.extract_text(x_tolerance=2) + assert(text == "NICS Firearm Background Checks\nNovember - 2015")