-
Notifications
You must be signed in to change notification settings - Fork 1
/
pdf_wrangling.py
1352 lines (1198 loc) · 47.9 KB
/
pdf_wrangling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import io
import math
import re
from enum import Enum
import tempfile
from copy import copy
from typing import (
Any,
Dict,
Iterable,
Optional,
List,
Union,
Tuple,
BinaryIO,
Mapping,
TypedDict,
)
from collections.abc import Sequence
from pathlib import Path
import random
import cv2
from boxdetect import config
from boxdetect.pipelines import get_checkboxes
import numpy as np
from pdf2image import convert_from_path
import pikepdf
from pikepdf import Pdf
from reportlab.pdfgen import canvas
from reportlab.lib.colors import magenta, pink, blue
from pdfminer.converter import PDFLayoutAnalyzer
from pdfminer.layout import LAParams, LTPage, LTTextBoxHorizontal, LTChar, LTContainer
from pdfminer.pdffont import PDFUnicodeNotDefined
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
# Change this to true to output lots of images to help understand why a kernel didn't work
DEBUG = False
######## PDF internals related functions ##########
class FieldType(Enum):
TEXT = "text" # Text input Field
AREA = "area" # Text input Field, but an area
SIGNATURE = "Signature"
CHECK_BOX = "checkbox"
LIST_BOX = "listbox" # allows multiple selection
CHOICE = "choice" # allows only one selection
RADIO = "radio"
def __str__(self):
return self.value
class PikeField(TypedDict):
type: str
var_name: str
all: pikepdf.objects.Object
BoundingBox = Tuple[int, int, int, int]
# x0, y0, width, height
BoundingBoxF = Tuple[float, float, float, float]
XYPair = Tuple[float, float]
class FormField:
"""A data holding class, used to easily specify how a PDF form field should be created."""
def __init__(
self,
field_name: str,
type_name: Union[FieldType, str],
x: int,
y: int,
font_size: Optional[int] = None,
tooltip: str = "",
configs: Optional[Dict[str, Any]] = None,
):
"""
Constructor
Args:
x: the x position of the lower left corner of the field. Should be in X,Y coordinates,
where (0, 0) is the lower left of the page, x goes to the right, and units are in
points (1/72th of an inch)
y: the y position of the lower left corner of the field. Should be in X,Y coordinates,
where (0, 0) is the lower left of the page, y goes up, and units are in points
(1/72th of an inch)
config: a dictionary containing any keyword argument to the reportlab field functions,
which will vary depending on what type of field this is. See section 4.7 of the
[reportlab User Guide](https://www.reportlab.com/docs/reportlab-userguide.pdf)
field_name: the name of the field, exposed to via most APIs. Not the tooltip, but `users1_name__0`
"""
if font_size is None:
font_size = 20
if isinstance(type_name, str):
# throws a ValueError, keeping in for now
self.type = FieldType(type_name.lower())
else:
self.type = type_name
self.name = field_name
self.x = x
self.y = y
self.tooltip = tooltip
self.font_size = font_size
# If we aren't given options, make our own depending on self.type
if self.type == FieldType.CHECK_BOX:
self.configs = {
"buttonStyle": "check",
"borderColor": magenta,
"fillColor": pink,
"textColor": blue,
"forceBorder": True,
}
elif self.type == FieldType.TEXT:
self.configs = {"fieldFlags": "doNotScroll"}
elif self.type == FieldType.AREA:
self.configs = {
"fieldFlags": "doNotScroll multiline",
}
else:
self.configs = {}
if configs:
self.configs.update(configs)
@classmethod
def make_textbox(cls, label: str, field_bbox: BoundingBox, font_size):
return FormField(
label,
FieldType.TEXT,
field_bbox[0],
field_bbox[1],
font_size=font_size,
configs={"width": field_bbox[2], "height": field_bbox[3]},
)
@classmethod
def make_textarea(cls, label: str, field_bbox: BoundingBox, font_size):
return FormField(
label,
FieldType.AREA,
field_bbox[0],
field_bbox[1],
font_size=font_size,
configs={"width": field_bbox[2], "height": field_bbox[3]},
)
@classmethod
def make_checkbox(cls, label: str, bbox: BoundingBox):
return FormField(
label,
FieldType.CHECK_BOX,
bbox[0],
bbox[1] - bbox[3],
configs={"size": min(bbox[2], bbox[3])},
)
@classmethod
def from_pikefield(cls, pike_field: PikeField):
if pike_field["type"] == "/Tx":
var_type = FieldType.TEXT
elif pike_field["type"] == "/Btn":
var_type = FieldType.CHECK_BOX
elif pike_field["type"] == "/Sig":
var_type = FieldType.SIGNATURE
else:
var_type = FieldType.TEXT
if hasattr(pike_field["all"], "Rect"):
x = float(pike_field["all"].Rect[0]) # type: ignore
y = float(pike_field["all"].Rect[1]) # type: ignore
width = float(pike_field["all"].Rect[2]) - x # type: ignore
height = float(pike_field["all"].Rect[3]) - y # type: ignore
else:
x = 0
y = 0
width = 0
height = 0
font_size = None
if hasattr(pike_field["all"], "DA"):
try:
da_ops = str(pike_field["all"].DA).split()
tf_idx = da_ops.index("Tf")
font_size = int(float(da_ops[tf_idx - 1]))
except (IndexError, ValueError, AttributeError, KeyError) as ex:
print(f"Skipping {str(pike_field['all'].DA)}, because of {ex}")
return FormField(
pike_field["var_name"],
var_type,
int(x),
int(y),
font_size=font_size,
configs={"width": width, "height": height},
)
def get_bbox(self) -> BoundingBoxF:
if self.type == FieldType.TEXT or self.type == FieldType.AREA:
return (
self.x,
self.y,
self.configs.get("width", 0),
self.configs.get("height", 0),
)
elif self.type == FieldType.CHECK_BOX:
return (
self.x,
self.y,
self.configs.get("size", 0),
self.configs.get("size", 0),
)
return (
self.x,
self.y,
self.configs.get("size", 0),
self.configs.get("size", 0),
)
def __str__(self):
return f"Type: {self.type}, Name: {self.name}, tooltip: {self.tooltip}, X: {self.x}, Y: {self.y}, font_size: {self.font_size}, Configs: {self.configs}"
def __repr__(self):
return str(self)
def _create_only_fields(
io_obj,
fields_per_page: Iterable[Iterable[FormField]],
font_name: str = "Courier",
font_size: int = 20,
):
"""Creates a PDF that contains only AcroForm fields. This PDF is then merged into an existing PDF to add fields to it.
We're adding fields to a PDF this way because reportlab isn't able to read PDFs, but is the best feature library for
writing them.
"""
c = canvas.Canvas(io_obj)
c.setFont(font_name, font_size)
form = c.acroForm
for fields in fields_per_page:
for field in fields:
if hasattr(field, "font_size"):
c.setFont(font_name, field.font_size)
# Signatures aren't supported in reportlab, so just make them textblocks.
if field.type == FieldType.TEXT or field.type == FieldType.SIGNATURE:
form.textfield(
name=field.name,
tooltip=field.tooltip,
x=field.x,
y=field.y,
fontSize=field.font_size,
**field.configs,
)
elif field.type == FieldType.AREA:
form.textfield(
name=field.name,
tooltip=field.tooltip,
x=field.x,
y=field.y,
fontSize=field.font_size,
**field.configs,
)
elif field.type == FieldType.CHECK_BOX:
form.checkbox(
name=field.name,
tooltip=field.tooltip,
x=field.x,
y=field.y,
**field.configs,
)
elif field.type == FieldType.LIST_BOX:
form.listbox(
name=field.name,
tooltip=field.tooltip,
x=field.x,
y=field.y,
**field.configs,
)
elif field.type == FieldType.CHOICE:
form.choice(
name=field.name,
tooltip=field.tooltip,
x=field.x,
y=field.y,
**field.configs,
)
elif field.type == FieldType.RADIO:
form.radio(
name=field.name,
tooltip=field.tooltip,
x=field.x,
y=field.y,
**field.configs,
)
else:
pass
c.showPage() # Goes to the next page
c.save()
def set_fields(
in_file: Union[str, Path, BinaryIO],
out_file: Union[str, Path, BinaryIO],
fields_per_page: Iterable[Iterable[FormField]],
*,
overwrite=False,
):
"""Adds fields per page to the in_file PDF, writing the new PDF to a new file.
Example usage:
```python
set_fields('no_fields.pdf', 'four_fields_on_second_page.pdf',
[
[], # nothing on the first page
[ # Second page
FormField('new_field', 'text', 110, 105, configs={'width': 200, 'height': 30}),
# Choice needs value to be one of the possible options, and options to be a list of strings or tuples
FormField('new_choices', 'choice', 110, 400, configs={'value': 'Option 1', 'options': ['Option 1', 'Option 2']}),
# Radios need to have the same name, with different values
FormField('new_radio1', 'radio', 110, 600, configs={'value': 'option a'}),
FormField('new_radio1', 'radio', 110, 500, configs={'value': 'option b'})
]
]
)
```
Args:
in_file: the input file name or path of a PDF that we're adding the fields to
out_file: the output file name or path where the new version of in_file will
be written. Doesn't need to exist.
fields_per_page: for each page, a series of fields that should be added to that
page.
owerwrite: if the input file already some fields (AcroForm fields specifically)
and this value is true, it will erase those existing fields and just add
`fields_per_page`. If not true and the input file has fields, this won't generate
a PDF, since there isn't currently a way to merge AcroForm fields from
different PDFs.
Returns:
Nothing.
"""
if not fields_per_page:
# Nothing to do, lol
return
in_pdf = Pdf.open(in_file, allow_overwriting_input=overwrite)
if hasattr(in_pdf.Root, "AcroForm") and not overwrite:
print("Not going to overwrite the existing AcroForm!")
return None
# Make an in-memory PDF with the fields
io_obj = io.BytesIO()
_create_only_fields(io_obj, fields_per_page)
temp_pdf = Pdf.open(io_obj)
in_pdf = copy_pdf_fields(source_pdf=temp_pdf, destination_pdf=in_pdf)
in_pdf.save(out_file)
in_pdf.close()
temp_pdf.close()
def rename_pdf_fields(
in_file: Union[str, Path, BinaryIO],
out_file: Union[str, Path, BinaryIO],
mapping: Mapping[str, str],
) -> None:
"""Given a dictionary that maps old to new field names, rename the AcroForm
field with a matching key to the specified value.
Example:
```python
rename_pdf_fields('current.pdf', 'new_field_names.pdf',
{'abc123': 'user1_name', 'abc124', 'user1_address_city'})
Args:
in_file: the filename of an input file
out_file: the filename of the output file. Doesn't need to exist,
will be overwritten if it does exist.
mapping: the python dict that maps from a current field name to the desired name
Returns:
Nothing
"""
in_pdf = Pdf.open(in_file, allow_overwriting_input=True)
for parent_field in iter(in_pdf.Root.AcroForm.Fields):
for field in _unnest_pdf_fields(parent_field):
name = str(field["var_name"])
if name in mapping:
# we aren't changing the parent names at all, so just change the last part of the name
if "." in mapping[name]:
field["all"].T = mapping[name].split(".")[-1]
else:
field["all"].T = mapping[name]
in_pdf.save(out_file)
in_pdf.close()
def unlock_pdf_in_place(in_file: Union[str, Path, BinaryIO]) -> None:
"""
Try using pikePDF to unlock the PDF it it is locked. This won't work if it has a non-zero length password.
"""
pdf_file = Pdf.open(in_file, allow_overwriting_input=True)
if pdf_file.is_encrypted:
pdf_file.save(in_file)
pdf_file.close()
def _unnest_pdf_fields(
field, parent_name: Optional[List[str]] = None
) -> List[PikeField]:
if parent_name is None:
parent_name = []
if hasattr(field, "T"):
parent_name.append(str(field.T))
if hasattr(field, "FT") and hasattr(field, "F"):
# PDF fields have bit flags for specific options. The 17th bit (or hex
# 10000) on Buttons mark a "push button", w/o a permanent value
# (e.g. "Print this PDF") They aren't really fields, just skip them.
if hasattr(field, "Ff") and field.FT == "/Btn" and bool(field.Ff & 0x10000):
return []
return [{"type": field.FT, "var_name": ".".join(parent_name), "all": field}]
elif hasattr(field, "Kids"):
return [y for x in field.Kids for y in _unnest_pdf_fields(x, copy(parent_name))]
else:
return []
def get_existing_pdf_fields(
in_file: Union[str, Path, BinaryIO, Pdf]
) -> List[List[FormField]]:
"""Use PikePDF to get fields from the PDF"""
if isinstance(in_file, Pdf):
in_pdf = in_file
else:
in_pdf = Pdf.open(in_file)
fields_in_pages: List[List[FormField]] = [[] for p in in_pdf.pages]
if not hasattr(in_pdf.Root, "AcroForm") or not hasattr(
in_pdf.Root.AcroForm, "Fields"
):
return fields_in_pages
all_fields = [
y
for field in iter(in_pdf.Root.AcroForm.Fields)
for y in _unnest_pdf_fields(field)
]
i = 0
pages = list(in_pdf.pages)
for field_i, field in enumerate(all_fields):
if len(pages) == 1 or not hasattr(field["all"], "P"):
# I don't know how exactly fields are associated with pages (they're associated with
# annotations, and pages have names? Unclear), so just throw it at the beginning
# if there isn't a page.
i = 0
elif hasattr(field["all"].P, "Type") and field["all"].P.Type == "/Template":
continue
elif not field["all"].P.objgen == pages[i].objgen:
i = -1
for idx, page in enumerate(pages):
if field["all"].P.objgen == page.objgen:
i = idx
break
if i == -1:
continue
fields_in_pages[i].append(FormField.from_pikefield(field))
return fields_in_pages
def swap_pdf_page(
*,
source_pdf: Union[str, Path, Pdf],
destination_pdf: Union[str, Path, Pdf],
source_offset: int = 0,
destination_offset: int = 0,
append_fields: bool = False,
) -> Pdf:
"""(DEPRECATED: use copy_pdf_fields) Copies the AcroForm fields from one PDF to another blank PDF form. Optionally, choose a starting page for both
the source and destination PDFs. By default, it will remove any existing annotations (which include form fields)
in the destination PDF. If you wish to append annotations instead, specify `append_fields = True`
"""
return copy_pdf_fields(
source_pdf=source_pdf,
destination_pdf=destination_pdf,
source_offset=source_offset,
destination_offset=destination_offset,
append_fields=append_fields,
)
def copy_pdf_fields(
*,
source_pdf: Union[str, Path, Pdf],
destination_pdf: Union[str, Path, Pdf],
source_offset: int = 0,
destination_offset: int = 0,
append_fields: bool = False,
) -> Pdf:
"""Copies the AcroForm fields from one PDF to another blank PDF form (without AcroForm fields).
Useful for getting started with an updated PDF form, where the old fields are pretty close to where
they should go on the new document.
Optionally, you can choose a starting page for both
the source and destination PDFs. By default, it will remove any existing annotations (which include form fields)
in the destination PDF. If you wish to append annotations instead, specify `append_fields = True`
Example:
```python
new_pdf_with_fields = copy_pdf_fields(
source_pdf="old_pdf.pdf",
destination_pdf="new_pdf_with_no_fields.pdf")
new_pdf_with_fields.save("new_pdf_with_fields.pdf")
```
Args:
source_pdf: a file name or path to a PDF that has AcroForm fields
destination_pdf: a file name or path to a PDF without AcroForm fields. Existing fields will be removed.
source_offset: the starting page that fields will be copied from. Defaults to 0.
destination_offset: the starting page that fields will be copied to. Defaults to 0.
append_annotations: controls whether formfyxer will try to append form fields instead of
overwriting. Defaults to false; when enabled may lead to undefined behavior.
Returns:
A pikepdf.Pdf object with new fields. If `blank_pdf` was a pikepdf.Pdf object, the
same object is returned.
"""
if isinstance(source_pdf, (str, Path)):
source_pdf = Pdf.open(source_pdf)
if isinstance(destination_pdf, (str, Path)):
destination_pdf = Pdf.open(destination_pdf)
if not hasattr(source_pdf.Root, "AcroForm"):
# if the given PDF doesn't have any fields, don't copy them!
return destination_pdf
foreign_root = destination_pdf.copy_foreign(source_pdf.Root)
destination_pdf.Root.AcroForm = foreign_root.AcroForm
for destination_page, source_page in zip(
destination_pdf.pages[destination_offset:], source_pdf.pages[source_offset:]
):
if not hasattr(source_page, "Annots"):
continue # no fields on this page, skip
annots = source_pdf.make_indirect(source_page.Annots)
if append_fields and hasattr(destination_page, "Annots"):
destination_page.Annots.extend(iter(destination_pdf.copy_foreign(annots)))
else:
destination_page["/Annots"] = destination_pdf.copy_foreign(annots)
return destination_pdf
class BoxPDFPageAggregator(PDFLayoutAnalyzer):
def __init__(
self,
rsrcmgr: PDFResourceManager,
pageno: int = 1,
laparams: Optional[LAParams] = None,
):
PDFLayoutAnalyzer.__init__(self, rsrcmgr, pageno=pageno, laparams=laparams)
self.results: List[LTPage] = []
def render_char(
self, matrix, font, fontsize, scaling, rise, cid, ncs, graphicstate
):
try:
text = font.to_unichr(cid)
assert isinstance(text, str), str(type(text))
except PDFUnicodeNotDefined:
text = self.handle_undefined_char(font, cid)
textwidth = font.char_width(cid)
textdisp = font.char_disp(cid)
if text == "_":
return textwidth * fontsize * scaling
item = LTChar(
matrix,
font,
fontsize,
scaling,
rise,
text,
textwidth,
textdisp,
ncs,
graphicstate,
)
self.cur_item.add(item)
return item.adv
def receive_layout(self, ltpage: LTPage) -> None:
self.results.append(ltpage)
def get_result(self) -> List[LTPage]:
return self.results
class BracketPDFPageAggregator(PDFLayoutAnalyzer):
def __init__(
self,
rsrcmgr: PDFResourceManager,
pageno: int = 1,
laparams: Optional[LAParams] = None,
):
PDFLayoutAnalyzer.__init__(self, rsrcmgr, pageno=pageno, laparams=laparams)
self.results: List[LTPage] = []
def render_char(
self, matrix, font, fontsize, scaling, rise, cid, ncs, graphicstate
):
try:
text = font.to_unichr(cid)
assert isinstance(text, str), str(type(text))
except PDFUnicodeNotDefined:
text = self.handle_undefined_char(font, cid)
textwidth = font.char_width(cid)
textdisp = font.char_disp(cid)
if text != "[" and text != "]":
return textwidth * fontsize * scaling
item = LTChar(
matrix,
font,
fontsize,
scaling,
rise,
text,
textwidth,
textdisp,
ncs,
graphicstate,
)
self.cur_item.add(item)
return item.adv
def receive_layout(self, ltpage: LTPage) -> None:
self.results.append(ltpage)
def get_result(self) -> List[LTPage]:
return self.results
class Textbox(TypedDict):
textbox: LTTextBoxHorizontal
bbox: BoundingBoxF
def _get_nested_textboxes(obj):
if isinstance(obj, LTTextBoxHorizontal):
return [obj]
if isinstance(obj, LTContainer):
boxes = []
for child in obj:
boxes.extend(_get_nested_textboxes(child))
return boxes
else:
return []
def get_textboxes_in_pdf(
in_file: Union[str, Path, BinaryIO],
line_margin=0.02,
char_margin=2.0,
) -> List[List[Textbox]]:
"""Gets all of the text boxes found by pdfminer in a PDF, as well as their bounding boxes"""
if isinstance(in_file, str) or isinstance(in_file, Path):
open_file = open(in_file, "rb")
parser = PDFParser(open_file)
else: # if isinstance(in_file, (Path, Pdf, bytes, io.BufferedReader)):
open_file = None
parser = PDFParser(in_file)
doc = PDFDocument(parser)
rsrcmgr = PDFResourceManager()
device = BoxPDFPageAggregator(
rsrcmgr,
laparams=LAParams(
line_margin=line_margin, char_margin=char_margin, all_texts=True
),
)
interpreter = PDFPageInterpreter(rsrcmgr, device)
page_count = 0
for page in PDFPage.create_pages(doc):
page_count += 1
interpreter.process_page(page)
if open_file and isinstance(open_file, io.BufferedReader):
open_file.close()
return [
[
{"textbox": obj, "bbox": (obj.x0, obj.y0, obj.width, obj.height)}
for obj in _get_nested_textboxes(device.get_result()[i])
if obj.get_text().strip(" \n") != ""
]
for i in range(page_count)
]
def get_bracket_chars_in_pdf(
in_file: Union[str, Path, BinaryIO],
line_margin=0.02,
char_margin=0.0,
) -> List:
"""Gets all of the bracket characters ('[' and ']') found by pdfminer in a PDF, as well as their bounding boxes
TODO: Will eventually be used to find [ ] as checkboxes, but right now we can't tell the difference between [ ] and [i].
This simply gets all of the brackets, and the characters of [hi] in a PDF and [ ] are the exact same distance apart.
Currently going with just "[hi]" doesn't happen, let's hope that assumption holds.
"""
if isinstance(in_file, str) or isinstance(in_file, Path):
open_file = open(in_file, "rb")
parser = PDFParser(open_file)
else:
open_file = None
parser = PDFParser(in_file)
doc = PDFDocument(parser)
rsrcmgr = PDFResourceManager()
device = BracketPDFPageAggregator(
rsrcmgr, laparams=LAParams(line_margin=line_margin, char_margin=char_margin)
)
interpreter = PDFPageInterpreter(rsrcmgr, device)
page_count = 0
for page in PDFPage.create_pages(doc):
page_count += 1
interpreter.process_page(page)
if open_file and isinstance(in_file, str):
open_file.close()
to_return = []
for page_idx in range(page_count):
in_page = [
(obj, (obj.x0, obj.y0, obj.width, obj.height))
for obj in device.get_result()[page_idx]._objs
if isinstance(obj, LTTextBoxHorizontal)
and obj.get_text().strip(" \n") != ""
]
left_bracket = [
item[1] for item in in_page if item[0].get_text().strip() == "["
]
right_bracket = [
item[1] for item in in_page if item[0].get_text().strip() == "]"
]
page_brackets = []
for l_box in left_bracket:
for r_box in right_bracket:
if intersect_bbox(l_box, r_box, horiz_dilation=12):
page_brackets.append(
(l_box[0], l_box[1] + l_box[3], l_box[3], l_box[3])
)
break
to_return.append(page_brackets)
return to_return
####### OpenCV related functions #########
pts_in_inch = 72
dpi = 250
def unit_convert(pix):
return pix / dpi * pts_in_inch
def img2pdf_coords(img, max_height):
if isinstance(img, int) or isinstance(img, float):
return unit_convert(img)
# If bbox: X, Y, width, height, and whatever else you want (we won't return it)
if len(img) >= 4:
return (
unit_convert(img[0]),
unit_convert(max_height - img[1]),
unit_convert(img[2]),
unit_convert(img[3]),
)
# If just X and Y
elif len(img) >= 2:
return (unit_convert(img[0]), unit_convert(max_height - img[1]))
else:
return unit_convert(img[0])
def intersect_bbox(bbox_a, bbox_b, vert_dilation=2, horiz_dilation=2) -> bool:
"""bboxes are [left edge, bottom edge, horizontal length, vertical length]"""
a_bottom, a_top = bbox_a[1] - vert_dilation, bbox_a[1] + bbox_a[3] + vert_dilation
b_bottom, b_top = bbox_b[1], bbox_b[1] + bbox_b[3]
if a_bottom > b_top or a_top < b_bottom:
return False
a_left, a_right = bbox_a[0] - horiz_dilation, bbox_a[0] + bbox_a[2] + horiz_dilation
b_left, b_right = bbox_b[0], bbox_b[0] + bbox_b[2]
if a_left > b_right or a_right < b_left:
return False
return True
def intersect_bboxs(
bbox_a, bboxes, vert_dilation=2, horiz_dilation=2
) -> Iterable[bool]:
"""Returns an iterable of booleans, one of each of the input bboxes, true if it collides with bbox_a"""
a_left, a_right = bbox_a[0] - horiz_dilation, bbox_a[0] + bbox_a[2] + horiz_dilation
a_bottom, a_top = bbox_a[1] - vert_dilation, bbox_a[1] + bbox_a[3] + vert_dilation
return [
a_top > bbox[1]
and a_bottom < (bbox[1] + bbox[3])
and a_right > bbox[0]
and a_left < (bbox[0] + bbox[2])
for bbox in bboxes
]
def contain_boxes(bbox_a: BoundingBoxF, bbox_b: BoundingBoxF) -> BoundingBoxF:
"""Given two bounding boxes, return a single bounding box that contains both of them."""
top, bottom = min(bbox_a[1] - bbox_a[3], bbox_b[1] - bbox_b[3]), max(
bbox_a[1], bbox_b[1]
)
left, right = min(bbox_a[0], bbox_b[0]), max(
bbox_a[0] + bbox_a[2], bbox_b[0] + bbox_b[2]
)
return (left, bottom, right - left, bottom - top)
def get_dist_sq(point_a: XYPair, point_b: XYPair) -> float:
"""returns the distance squared between two points. Faster than the true euclidean dist"""
return (point_a[0] - point_b[0]) ** 2 + (point_a[1] - point_b[1]) ** 2
def get_dist(point_a: XYPair, point_b: XYPair) -> float:
"""euclidean (L^2 norm) distance between two points"""
return math.sqrt((point_a[0] - point_b[0]) ** 2 + (point_a[1] - point_b[1]) ** 2)
def get_connected_edges(point: XYPair, point_list: Sequence):
"""point list is always ordered clockwise from the bottom left,
i.e. bottom left, top left, top right, bottom right"""
if point == point_list[0] or point == point_list[3]:
horizontal = (point_list[0], point_list[3])
else:
horizontal = (point_list[1], point_list[2])
if point == point_list[0] or point == point_list[1]:
vertical = (point_list[0], point_list[1])
else:
vertical = (point_list[2], point_list[3])
return horizontal, vertical
def bbox_distance(
bbox_a: BoundingBoxF, bbox_b: BoundingBoxF
) -> Tuple[float, Tuple[XYPair, XYPair], Tuple[XYPair, XYPair]]:
"""Gets our specific "distance measure" between two different bounding boxes.
This distance is roughly the sum of the horizontal and vertical difference in alignment of
the closest shared field-bounding box edge. We are trying to find which, given a list of text boxes
around a field, is the most likely to be the actual text label for the PDF field.
bboxes are 4 floats, x, y, width and height"""
a_left, a_right = bbox_a[0], bbox_a[0] + bbox_a[2]
a_bottom, a_top = bbox_a[1], bbox_a[1] + bbox_a[3]
b_left, b_right = bbox_b[0], bbox_b[0] + bbox_b[2]
b_bottom, b_top = bbox_b[1], bbox_b[1] + bbox_b[3]
points_a = [
(a_left, a_bottom),
(a_left, a_top),
(a_right, a_top),
(a_right, a_bottom),
]
points_b = [
(b_left, b_bottom),
(b_left, b_top),
(b_right, b_top),
(b_right, b_bottom),
]
min_pair = (points_a[0], points_b[0])
min_dist = get_dist_sq(min_pair[0], min_pair[1])
for point_a in points_a:
for point_b in points_b:
dist = get_dist_sq(point_a, point_b)
if dist < min_dist:
min_pair = (point_a, point_b)
min_dist = dist
# get horizontal and vertical line pairs
a_hori, a_vert = get_connected_edges(min_pair[0], points_a)
b_hori, b_vert = get_connected_edges(min_pair[1], points_b)
hori_dist = min(get_dist(a_hori[0], b_hori[0]), get_dist(a_hori[1], b_hori[1]))
vert_dist = min(get_dist(a_vert[0], b_vert[0]), get_dist(a_vert[1], b_vert[1]))
if hori_dist < vert_dist:
return hori_dist + vert_dist, a_hori, b_hori
else:
return vert_dist + hori_dist, a_vert, b_vert
###### Field functionality #######
def get_possible_fields(
in_pdf_file: Union[str, Path],
textboxes: Optional[List[List[Textbox]]] = None,
) -> List[List[FormField]]:
"""Given an input PDF, runs a series of heuristics to predict where there
might be places for user enterable information (i.e. PDF fields), and returns
those predictions.
Example:
```python
fields = get_possible_fields('no_field.pdf')
print(fields[0][0])
# Type: FieldType.TEXT, Name: name, User name: , X: 67.68, Y: 666.0, Configs: {'fieldFlags': 'doNotScroll', 'width': 239.4, 'height': 16}
```
Args:
in_pdf_file: the input PDF
textboxes (optional): the location of various lines of text in the PDF.
If not given, will be calculated automatically. This allows us to
pass through expensive info to calculate through several functions.
Returns:
For each page in the input PDF, a list of predicted form fields
"""
images = convert_from_path(in_pdf_file, dpi=dpi)
tmp_files = [tempfile.NamedTemporaryFile() for i in range(len(images))]
for file_obj, img in zip(tmp_files, images):
img.save(file_obj, "JPEG")
file_obj.flush()
if not textboxes:
textboxes = get_textboxes_in_pdf(in_pdf_file)
checkbox_bboxes_per_page = [get_possible_checkboxes(tmp.name) for tmp in tmp_files]
if not any(
[in_page is not None and len(in_page) for in_page in checkbox_bboxes_per_page]
):
all_text = " ".join(
[
" ".join([page_item["textbox"].get_text() for page_item in page])
for page in textboxes
]
)
if re.search(r"\[ {1,3}\]", all_text):
checkbox_pdf_bboxes = get_bracket_chars_in_pdf(in_pdf_file)
else:
checkbox_bboxes_per_page = [
get_possible_checkboxes(tmp.name, find_small=True) for tmp in tmp_files
]
checkbox_pdf_bboxes = [
[img2pdf_coords(bbox, images[i].height) for bbox in bboxes_in_page]
for i, bboxes_in_page in enumerate(checkbox_bboxes_per_page)
]
else:
checkbox_pdf_bboxes = [
[img2pdf_coords(bbox, images[i].height) for bbox in bboxes_in_page]
for i, bboxes_in_page in enumerate(checkbox_bboxes_per_page)
]
text_bboxes_per_page = [
get_possible_text_fields(tmp.name, page_text)
for tmp, page_text in zip(tmp_files, textboxes)
]
text_pdf_bboxes = [
[
(img2pdf_coords(bbox, images[i].height), font_size)
for bbox, font_size in bboxes_in_page
]
for i, bboxes_in_page in enumerate(text_bboxes_per_page)
]
fields = []
i = 0
for (
bboxes_in_page,
checkboxes_in_page,
) in zip(text_pdf_bboxes, checkbox_pdf_bboxes):
# Get text boxes with more than one character (not including spaces, _, etc.)
page_fields = []
for j, field_info in enumerate(bboxes_in_page):
field_bbox, font_size = field_info
label = f"page_{i}_field_{j}"
# By default the line size is 16.
if field_bbox[3] > 24:
page_fields.append(
FormField.make_textarea(label, field_bbox, font_size)
)
else:
page_fields.append(FormField.make_textbox(label, field_bbox, font_size))
page_fields += [
FormField.make_checkbox(f"page_{i}_check_{j}", bbox)
for j, bbox in enumerate(checkboxes_in_page)
]
i += 1
fields.append(page_fields)
return fields
def improve_names_with_surrounding_text(
fields: List[List[FormField]], textboxes: List[List[Textbox]]
):
new_fields = []
used_field_names = set()
for i, (fields_in_page, text_in_page) in enumerate(zip(fields, textboxes)):
# Get text boxes with more than one character (not including spaces, _, etc.)
text_in_page = [