-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader13.py
More file actions
83 lines (67 loc) · 2.86 KB
/
reader13.py
File metadata and controls
83 lines (67 loc) · 2.86 KB
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
import fitz # PyMuPDF
def extract_transaction_table_region(input_pdf_path, output_pdf_path):
doc = fitz.open(input_pdf_path)
output_doc = fitz.open()
for page_num in range(len(doc)):
page = doc.load_page(page_num)
blocks = page.get_text("blocks")
header_threshold = page.rect.height * 0.15
found_header = False
header_bottom = None
for block in blocks:
x0, y0, x1, y1, text, *_ = block
if text.strip() == "TRANSACTIONS" and y1 < header_threshold:
found_header = True
header_bottom = y1
break
if found_header:
# Scan blocks below header to find end of table
table_blocks = []
last_valid_y1 = None
for block in blocks:
x0, y0, x1, y1, text, *_ = block
if y0 <= header_bottom:
continue # Skip header and above
clean_text = text.strip()
if clean_text == "":
continue
# Heuristic: stop if block looks like metadata
if (
clean_text.isupper() and len(clean_text.split()) > 3
) or (
y1 - y0 < 8 # Very small height block (likely footnote)
):
break
table_blocks.append(block)
last_valid_y1 = y1
if not table_blocks or last_valid_y1 is None:
continue
# Define crop region from first to last valid block
table_top = table_blocks[0][1] - 5
table_bottom = last_valid_y1 + 5
table_rect = fitz.Rect(0, table_top, page.rect.width, table_bottom)
# Render cropped region
pix = page.get_pixmap(clip=table_rect, dpi=300)
# Output page layout
page_width = page.rect.width
image_height = table_rect.height
padding_top = 30
new_page_height = image_height + padding_top + 30
# Create new page and insert image
new_page = output_doc.new_page(width=page_width, height=new_page_height)
new_page.insert_text((50, 20), f"Page {page_num + 1} - TRANSACTIONS Table", fontsize=12)
new_page.insert_image(
fitz.Rect(0, padding_top, page_width, padding_top + image_height),
pixmap=pix
)
if output_doc.page_count > 0:
output_doc.save(output_pdf_path)
print(f"✅ Cropped table regions saved to: {output_pdf_path}")
else:
print("⚠️ No matching pages found.")
doc.close()
output_doc.close()
# 🔧 Replace with your actual paths
input_pdf = r"C:\Users\Suren\Downloads\input.pdf"
output_pdf = r"C:\Users\Suren\Downloads\transactions_table_only.pdf"
extract_transaction_table_region(input_pdf, output_pdf)