table-renderer 0.5.0__tar.gz → 0.6.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {table_renderer-0.5.0 → table_renderer-0.6.0}/PKG-INFO +1 -1
- table_renderer-0.6.0/pyproject.toml +105 -0
- table_renderer-0.5.0/pyproject.toml → table_renderer-0.6.0/pyproject.toml.orig +6 -4
- table_renderer-0.6.0/src/table_renderer/__init__.py +33 -0
- table_renderer-0.6.0/src/table_renderer/backends/geometry.py +287 -0
- table_renderer-0.6.0/src/table_renderer/backends/pdf_rasterizer.py +235 -0
- table_renderer-0.6.0/src/table_renderer/backends/weasyprint_renderer.py +206 -0
- {table_renderer-0.5.0 → table_renderer-0.6.0}/src/table_renderer/html_generator.py +39 -40
- {table_renderer-0.5.0 → table_renderer-0.6.0}/src/table_renderer/models/cell.py +57 -7
- {table_renderer-0.5.0 → table_renderer-0.6.0}/src/table_renderer/models/style.py +59 -25
- {table_renderer-0.5.0 → table_renderer-0.6.0}/src/table_renderer/models/table.py +6 -31
- table_renderer-0.6.0/src/table_renderer/resolved_table.py +172 -0
- {table_renderer-0.5.0 → table_renderer-0.6.0}/src/table_renderer/templates/table.html.j2 +2 -2
- table_renderer-0.5.0/src/table_renderer/__init__.py +0 -11
- table_renderer-0.5.0/src/table_renderer/backends/weasyprint_renderer.py +0 -271
- {table_renderer-0.5.0 → table_renderer-0.6.0}/README.md +0 -0
- {table_renderer-0.5.0 → table_renderer-0.6.0}/src/table_renderer/backends/__init__.py +0 -0
- {table_renderer-0.5.0 → table_renderer-0.6.0}/src/table_renderer/backends/base.py +0 -0
- {table_renderer-0.5.0 → table_renderer-0.6.0}/src/table_renderer/models/__init__.py +0 -0
- {table_renderer-0.5.0 → table_renderer-0.6.0}/src/table_renderer/models/column.py +0 -0
- {table_renderer-0.5.0 → table_renderer-0.6.0}/src/table_renderer/models/row.py +0 -0
- {table_renderer-0.5.0 → table_renderer-0.6.0}/src/table_renderer/py.typed +0 -0
- {table_renderer-0.5.0 → table_renderer-0.6.0}/src/table_renderer/renderer.py +0 -0
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["uv_build>=0.11.0,<0.14.0"]
|
|
3
|
+
build-backend = "uv_build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "table-renderer"
|
|
7
|
+
version = "0.6.0"
|
|
8
|
+
description = "A Python library for rendering structured tables as high-quality images or HTML."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.12,<3.15"
|
|
12
|
+
keywords = [
|
|
13
|
+
"table",
|
|
14
|
+
"renderer",
|
|
15
|
+
"rendering",
|
|
16
|
+
"image",
|
|
17
|
+
"html",
|
|
18
|
+
"weasyprint",
|
|
19
|
+
"pdfium",
|
|
20
|
+
"report",
|
|
21
|
+
]
|
|
22
|
+
classifiers = [
|
|
23
|
+
"Development Status :: 4 - Beta",
|
|
24
|
+
"Intended Audience :: Developers",
|
|
25
|
+
"Programming Language :: Python :: 3.12",
|
|
26
|
+
"Programming Language :: Python :: 3.13",
|
|
27
|
+
"Programming Language :: Python :: 3.14",
|
|
28
|
+
"Operating System :: OS Independent",
|
|
29
|
+
"Topic :: Multimedia :: Graphics",
|
|
30
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
31
|
+
]
|
|
32
|
+
dependencies = [
|
|
33
|
+
"jinja2~=3.0",
|
|
34
|
+
"pillow~=12.0",
|
|
35
|
+
"pypdfium2~=5.0",
|
|
36
|
+
"typing-extensions>=4.5.0",
|
|
37
|
+
"weasyprint>=68.1",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
[[project.authors]]
|
|
41
|
+
name = "pTaunium"
|
|
42
|
+
email = "pTaunium@gmail.com"
|
|
43
|
+
|
|
44
|
+
[dependency-groups]
|
|
45
|
+
dev = [
|
|
46
|
+
"ipython",
|
|
47
|
+
"pytest~=9.0",
|
|
48
|
+
"pytest-cov~=7.0",
|
|
49
|
+
"ruff~=0.17",
|
|
50
|
+
"ty>=0.0.95",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
[tool.ruff]
|
|
54
|
+
line-length = 88
|
|
55
|
+
indent-width = 4
|
|
56
|
+
extend-exclude = ["*.md"]
|
|
57
|
+
|
|
58
|
+
[tool.ruff.lint]
|
|
59
|
+
select = [
|
|
60
|
+
"E",
|
|
61
|
+
"W",
|
|
62
|
+
"I",
|
|
63
|
+
"N",
|
|
64
|
+
"F",
|
|
65
|
+
"C90",
|
|
66
|
+
"ANN",
|
|
67
|
+
"ASYNC",
|
|
68
|
+
"S",
|
|
69
|
+
"B",
|
|
70
|
+
"A",
|
|
71
|
+
"C4",
|
|
72
|
+
"PIE",
|
|
73
|
+
"PT",
|
|
74
|
+
"RET",
|
|
75
|
+
"SIM",
|
|
76
|
+
"PERF",
|
|
77
|
+
"FURB",
|
|
78
|
+
"UP",
|
|
79
|
+
"RUF",
|
|
80
|
+
]
|
|
81
|
+
ignore = ["E501"]
|
|
82
|
+
|
|
83
|
+
[tool.ruff.lint.isort]
|
|
84
|
+
section-order = [
|
|
85
|
+
"future",
|
|
86
|
+
"standard-library",
|
|
87
|
+
"third-party",
|
|
88
|
+
"first-party",
|
|
89
|
+
"local-folder",
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
[tool.ruff.lint.per-file-ignores]
|
|
93
|
+
"tests/**/*.py" = [
|
|
94
|
+
"S101",
|
|
95
|
+
"S105",
|
|
96
|
+
"S106",
|
|
97
|
+
"S107",
|
|
98
|
+
]
|
|
99
|
+
|
|
100
|
+
[tool.ruff.format]
|
|
101
|
+
docstring-code-format = true
|
|
102
|
+
docstring-code-line-length = "dynamic"
|
|
103
|
+
|
|
104
|
+
[tool.coverage.run]
|
|
105
|
+
source = ["src"]
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
[build-system]
|
|
2
|
-
requires = ["uv_build>=0.11.0,<0.
|
|
2
|
+
requires = ["uv_build>=0.11.0,<0.14.0"]
|
|
3
3
|
build-backend = "uv_build"
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "table-renderer"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.6.0"
|
|
8
8
|
description = "A Python library for rendering structured tables as high-quality images or HTML."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "MIT"
|
|
@@ -37,13 +37,15 @@ dev = [
|
|
|
37
37
|
"ipython",
|
|
38
38
|
"pytest~=9.0",
|
|
39
39
|
"pytest-cov~=7.0",
|
|
40
|
-
"ruff~=0.
|
|
41
|
-
"ty>=0.0.
|
|
40
|
+
"ruff~=0.17",
|
|
41
|
+
"ty>=0.0.95",
|
|
42
42
|
]
|
|
43
43
|
|
|
44
44
|
[tool.ruff]
|
|
45
45
|
line-length = 88
|
|
46
46
|
indent-width = 4
|
|
47
|
+
# Keep hand-aligned comments in README code blocks.
|
|
48
|
+
extend-exclude = ["*.md"]
|
|
47
49
|
|
|
48
50
|
[tool.ruff.lint]
|
|
49
51
|
select = [
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import importlib.metadata
|
|
2
|
+
|
|
3
|
+
from .models import Cell, Column, Row, Style, StyledObject, Table
|
|
4
|
+
from .resolved_table import (
|
|
5
|
+
FontFace,
|
|
6
|
+
ResolvedCell,
|
|
7
|
+
ResolvedColumn,
|
|
8
|
+
ResolvedRow,
|
|
9
|
+
ResolvedTable,
|
|
10
|
+
resolve_table,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
__version__ = importlib.metadata.version("table-renderer")
|
|
15
|
+
except importlib.metadata.PackageNotFoundError:
|
|
16
|
+
# Package is not installed (e.g. during local development without pip install -e .)
|
|
17
|
+
__version__ = "0.6.0"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"Cell",
|
|
21
|
+
"Column",
|
|
22
|
+
"FontFace",
|
|
23
|
+
"ResolvedCell",
|
|
24
|
+
"ResolvedColumn",
|
|
25
|
+
"ResolvedRow",
|
|
26
|
+
"ResolvedTable",
|
|
27
|
+
"Row",
|
|
28
|
+
"Style",
|
|
29
|
+
"StyledObject",
|
|
30
|
+
"Table",
|
|
31
|
+
"__version__",
|
|
32
|
+
"resolve_table",
|
|
33
|
+
]
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Layout geometry calculations for table rendering.
|
|
2
|
+
|
|
3
|
+
This module is a deep module that encapsulates all unit-conversion,
|
|
4
|
+
length-parsing, page-size estimation, overflow checks, and crop-box
|
|
5
|
+
calculations. It deals purely with numbers and ResolvedTable dimensions,
|
|
6
|
+
independent of any PDF engine or browser renderer.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import math
|
|
12
|
+
from collections.abc import Sequence
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import TYPE_CHECKING
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from table_renderer.resolved_table import ResolvedTable
|
|
18
|
+
|
|
19
|
+
CSS_DPI: int = 96
|
|
20
|
+
PDF_DPI: int = 72
|
|
21
|
+
DEFAULT_COL_WIDTH_PX: int = 100
|
|
22
|
+
MIN_PAGE_WIDTH_PX: int = 200
|
|
23
|
+
DEFAULT_BODY_PADDING_CSS_PX: int = 20
|
|
24
|
+
BODY_PADDING_BUFFER_CSS_PX: int = 4
|
|
25
|
+
WIDTH_MARGIN_ALLOWANCE_CSS_PX: int = 20
|
|
26
|
+
HEIGHT_SAFETY_BUFFER_CSS_PX: int = 100
|
|
27
|
+
INITIAL_PAGE_HEIGHT_CSS_PX: int = 1_000_000
|
|
28
|
+
BORDER_SLACK_DEV_PX: int = 1
|
|
29
|
+
MAX_BODY_PADDING_ALIGNMENT_STEP_CSS_PX: int = 8
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(slots=True)
|
|
33
|
+
class TableBounds:
|
|
34
|
+
"""Bounding box of a rendered table in CSS pixels."""
|
|
35
|
+
|
|
36
|
+
x: float
|
|
37
|
+
y: float
|
|
38
|
+
width: float
|
|
39
|
+
height: float
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(slots=True)
|
|
43
|
+
class PageDimensions:
|
|
44
|
+
"""Dimensions of a rendering canvas/page in CSS pixels."""
|
|
45
|
+
|
|
46
|
+
width: int
|
|
47
|
+
height: int
|
|
48
|
+
body_padding_css_px: int
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def parse_pixel_length(value: int | str) -> int | None:
|
|
52
|
+
"""Parse an integer or CSS pixel length string into integer pixels.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
value: An integer pixel value or CSS length string (e.g., ``"1200px"``).
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
Positive integer pixel count, or ``None`` if not a pixel value.
|
|
59
|
+
"""
|
|
60
|
+
if isinstance(value, bool):
|
|
61
|
+
return None
|
|
62
|
+
if isinstance(value, int):
|
|
63
|
+
return value if value > 0 else None
|
|
64
|
+
if isinstance(value, str):
|
|
65
|
+
stripped = value.strip().lower()
|
|
66
|
+
if stripped.endswith("px"):
|
|
67
|
+
stripped = stripped[:-2].strip()
|
|
68
|
+
try:
|
|
69
|
+
parsed = float(stripped)
|
|
70
|
+
except ValueError:
|
|
71
|
+
return None
|
|
72
|
+
if parsed > 0 and math.isfinite(parsed):
|
|
73
|
+
return math.ceil(parsed)
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def compute_body_padding_css_px(*, dpi: int, padding: int) -> int:
|
|
78
|
+
"""Compute the CSS body padding required to accommodate device-pixel padding.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
dpi: Target resolution in dots per inch.
|
|
82
|
+
padding: Padding in device pixels.
|
|
83
|
+
|
|
84
|
+
Returns:
|
|
85
|
+
CSS body padding in pixels.
|
|
86
|
+
"""
|
|
87
|
+
device_px_per_css_px = dpi / CSS_DPI
|
|
88
|
+
raw_body_padding_css_px = max(
|
|
89
|
+
DEFAULT_BODY_PADDING_CSS_PX,
|
|
90
|
+
math.ceil(max(0, padding) / device_px_per_css_px) + BODY_PADDING_BUFFER_CSS_PX,
|
|
91
|
+
)
|
|
92
|
+
# Align CSS body padding to device pixel grid, capping alignment step to avoid runaway page expansion
|
|
93
|
+
body_padding_alignment_step_css_px = min(
|
|
94
|
+
MAX_BODY_PADDING_ALIGNMENT_STEP_CSS_PX,
|
|
95
|
+
CSS_DPI // math.gcd(dpi, CSS_DPI),
|
|
96
|
+
)
|
|
97
|
+
return (
|
|
98
|
+
math.ceil(raw_body_padding_css_px / body_padding_alignment_step_css_px)
|
|
99
|
+
* body_padding_alignment_step_css_px
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def estimate_page_width(
|
|
104
|
+
resolved: ResolvedTable,
|
|
105
|
+
*,
|
|
106
|
+
body_padding_css_px: int = DEFAULT_BODY_PADDING_CSS_PX,
|
|
107
|
+
) -> int:
|
|
108
|
+
"""Estimate the required table page width in CSS pixels.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
resolved: The ResolvedTable to measure.
|
|
112
|
+
body_padding_css_px: CSS body padding in pixels.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
Estimated page width in CSS pixels.
|
|
116
|
+
"""
|
|
117
|
+
margin_allowance_css_px = body_padding_css_px * 2 + WIDTH_MARGIN_ALLOWANCE_CSS_PX
|
|
118
|
+
if not resolved.cells:
|
|
119
|
+
return max(MIN_PAGE_WIDTH_PX, margin_allowance_css_px)
|
|
120
|
+
|
|
121
|
+
parsed_table_width = parse_pixel_length(resolved.width)
|
|
122
|
+
if parsed_table_width is not None:
|
|
123
|
+
return max(MIN_PAGE_WIDTH_PX, parsed_table_width + margin_allowance_css_px)
|
|
124
|
+
|
|
125
|
+
total_width_css_px = 0
|
|
126
|
+
for col in resolved.columns:
|
|
127
|
+
parsed_col_width = parse_pixel_length(col.width)
|
|
128
|
+
if parsed_col_width is not None:
|
|
129
|
+
total_width_css_px += parsed_col_width
|
|
130
|
+
else:
|
|
131
|
+
total_width_css_px += DEFAULT_COL_WIDTH_PX
|
|
132
|
+
|
|
133
|
+
return max(MIN_PAGE_WIDTH_PX, total_width_css_px + margin_allowance_css_px)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def estimate_page_dimensions(
|
|
137
|
+
resolved: ResolvedTable,
|
|
138
|
+
*,
|
|
139
|
+
dpi: int,
|
|
140
|
+
padding: int,
|
|
141
|
+
) -> PageDimensions:
|
|
142
|
+
"""Estimate initial continuous page dimensions for a table.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
resolved: The ResolvedTable to measure.
|
|
146
|
+
dpi: Target resolution in dots per inch.
|
|
147
|
+
padding: Requested image padding in device pixels.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
PageDimensions with width, initial page height, and body padding.
|
|
151
|
+
"""
|
|
152
|
+
body_padding_css_px = compute_body_padding_css_px(dpi=dpi, padding=padding)
|
|
153
|
+
width = estimate_page_width(resolved, body_padding_css_px=body_padding_css_px)
|
|
154
|
+
return PageDimensions(
|
|
155
|
+
width=width,
|
|
156
|
+
height=INITIAL_PAGE_HEIGHT_CSS_PX,
|
|
157
|
+
body_padding_css_px=body_padding_css_px,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def build_page_css(dimensions: PageDimensions) -> str:
|
|
162
|
+
"""Build ``@page`` and ``html body`` CSS rules for continuous layout.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
dimensions: The target page dimensions and padding.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
CSS string suitable for injection into ``extra_css``.
|
|
169
|
+
"""
|
|
170
|
+
return (
|
|
171
|
+
"@page {\n"
|
|
172
|
+
f" size: {dimensions.width}px {dimensions.height}px;\n"
|
|
173
|
+
" margin: 0;\n"
|
|
174
|
+
"}\n"
|
|
175
|
+
"html body {\n"
|
|
176
|
+
f" padding: {dimensions.body_padding_css_px}px;\n"
|
|
177
|
+
"}"
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def compute_relayout_dimensions(
|
|
182
|
+
bounds: Sequence[TableBounds],
|
|
183
|
+
page_count: int,
|
|
184
|
+
current_dimensions: PageDimensions,
|
|
185
|
+
) -> PageDimensions | None:
|
|
186
|
+
"""Determine if re-layout is needed and return the expanded dimensions.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
bounds: Measured bounds for table instances across pages.
|
|
190
|
+
page_count: Number of pages generated in the layout pass.
|
|
191
|
+
current_dimensions: Current page dimensions.
|
|
192
|
+
|
|
193
|
+
Returns:
|
|
194
|
+
Expanded PageDimensions if relayout is needed and dimensions change,
|
|
195
|
+
or ``None`` if current dimensions are sufficient.
|
|
196
|
+
"""
|
|
197
|
+
if not bounds:
|
|
198
|
+
return None
|
|
199
|
+
|
|
200
|
+
max_right_css_px = max(b.x + b.width for b in bounds)
|
|
201
|
+
total_height_css_px = sum(b.height for b in bounds)
|
|
202
|
+
|
|
203
|
+
needed_width_css_px = math.ceil(
|
|
204
|
+
max_right_css_px + current_dimensions.body_padding_css_px
|
|
205
|
+
)
|
|
206
|
+
needed_height_css_px = math.ceil(
|
|
207
|
+
total_height_css_px
|
|
208
|
+
+ current_dimensions.body_padding_css_px * 2
|
|
209
|
+
+ HEIGHT_SAFETY_BUFFER_CSS_PX
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
target_width = max(current_dimensions.width, needed_width_css_px)
|
|
213
|
+
target_height = max(current_dimensions.height, needed_height_css_px)
|
|
214
|
+
|
|
215
|
+
if (
|
|
216
|
+
page_count > 1
|
|
217
|
+
or target_width > current_dimensions.width
|
|
218
|
+
or target_height > current_dimensions.height
|
|
219
|
+
):
|
|
220
|
+
if page_count > 1 and target_height <= current_dimensions.height:
|
|
221
|
+
target_height = current_dimensions.height + HEIGHT_SAFETY_BUFFER_CSS_PX
|
|
222
|
+
|
|
223
|
+
return PageDimensions(
|
|
224
|
+
width=target_width,
|
|
225
|
+
height=target_height,
|
|
226
|
+
body_padding_css_px=current_dimensions.body_padding_css_px,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
return None
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def compute_crop_box_px(
|
|
233
|
+
bounds: TableBounds, *, dpi: int, padding: int
|
|
234
|
+
) -> tuple[int, int, int, int]:
|
|
235
|
+
"""Compute device-pixel crop bounding box from TableBounds.
|
|
236
|
+
|
|
237
|
+
Args:
|
|
238
|
+
bounds: Measured TableBounds in CSS pixels.
|
|
239
|
+
dpi: Target resolution in dots per inch.
|
|
240
|
+
padding: Padding around the table in device pixels.
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
Tuple of ``(left, top, right, bottom)`` in device pixels.
|
|
244
|
+
"""
|
|
245
|
+
device_px_per_css_px = dpi / CSS_DPI
|
|
246
|
+
pad = max(0, padding)
|
|
247
|
+
|
|
248
|
+
table_left_px = math.floor(bounds.x * device_px_per_css_px)
|
|
249
|
+
table_top_px = math.floor(bounds.y * device_px_per_css_px)
|
|
250
|
+
|
|
251
|
+
# Compute absolute right/bottom edges with outward slack for anti-aliased borders
|
|
252
|
+
table_right_px = (
|
|
253
|
+
math.ceil((bounds.x + bounds.width) * device_px_per_css_px)
|
|
254
|
+
+ BORDER_SLACK_DEV_PX
|
|
255
|
+
)
|
|
256
|
+
table_bottom_px = (
|
|
257
|
+
math.ceil((bounds.y + bounds.height) * device_px_per_css_px)
|
|
258
|
+
+ BORDER_SLACK_DEV_PX
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
left = max(0, table_left_px - pad)
|
|
262
|
+
top = max(0, table_top_px - pad)
|
|
263
|
+
right = table_right_px + pad
|
|
264
|
+
bottom = table_bottom_px + pad
|
|
265
|
+
return left, top, right, bottom
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def compute_bbox_padding_px(
|
|
269
|
+
bbox: tuple[int, int, int, int], *, padding: int
|
|
270
|
+
) -> tuple[int, int, int, int]:
|
|
271
|
+
"""Apply device-pixel padding around a device-pixel bounding box.
|
|
272
|
+
|
|
273
|
+
Args:
|
|
274
|
+
bbox: Raw bounding box ``(left, top, right, bottom)`` in device pixels.
|
|
275
|
+
padding: Padding around content in device pixels.
|
|
276
|
+
|
|
277
|
+
Returns:
|
|
278
|
+
Tuple of ``(left, top, right, bottom)`` with padding applied.
|
|
279
|
+
"""
|
|
280
|
+
pad = max(0, padding)
|
|
281
|
+
min_x, min_y, max_x, max_y = bbox
|
|
282
|
+
return (
|
|
283
|
+
max(0, min_x - pad),
|
|
284
|
+
max(0, min_y - pad),
|
|
285
|
+
max_x + pad,
|
|
286
|
+
max_y + pad,
|
|
287
|
+
)
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""2D Tiled PDF rasterization and auto-crop utilities using pypdfium2.
|
|
2
|
+
|
|
3
|
+
This module encapsulates all low-level PDF page loading, tiled coordinate
|
|
4
|
+
conversion, 2D chunked bitmap rasterization, and ink content bounding-box
|
|
5
|
+
detection into a deep, reusable rendering component.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
from collections.abc import Iterator
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
|
+
|
|
14
|
+
import pypdfium2 as pdfium
|
|
15
|
+
from PIL import Image, ImageChops
|
|
16
|
+
|
|
17
|
+
from table_renderer.backends.geometry import CSS_DPI, PDF_DPI
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from PIL.Image import Image as PilImage
|
|
21
|
+
|
|
22
|
+
MAX_TILE_SIZE_PX: int = 8192
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def px_to_crop_pt(px: int, pdf_scale: float) -> float:
|
|
26
|
+
"""Convert an integer device-pixel offset to PDF points for pypdfium2 crop.
|
|
27
|
+
|
|
28
|
+
Subtracts a tiny epsilon before dividing so that pypdfium2's internal
|
|
29
|
+
``math.ceil(c * scale)`` recovers the exact integer ``px`` even when
|
|
30
|
+
``pdf_scale`` is a repeating fraction (e.g., at 300 DPI).
|
|
31
|
+
"""
|
|
32
|
+
if px <= 0:
|
|
33
|
+
return 0.0
|
|
34
|
+
return (px - 1e-6) / pdf_scale
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def render_pdf_tile(
|
|
38
|
+
page: pdfium.PdfPage,
|
|
39
|
+
*,
|
|
40
|
+
x0: int,
|
|
41
|
+
y0: int,
|
|
42
|
+
x1: int,
|
|
43
|
+
y1: int,
|
|
44
|
+
page_width_dev_px: int,
|
|
45
|
+
page_height_dev_px: int,
|
|
46
|
+
pdf_scale: float,
|
|
47
|
+
) -> PilImage:
|
|
48
|
+
"""Render a single rectangular tile of a PDF page into a PIL RGBA Image."""
|
|
49
|
+
crop_pts = (
|
|
50
|
+
px_to_crop_pt(x0, pdf_scale),
|
|
51
|
+
px_to_crop_pt(page_height_dev_px - y1, pdf_scale),
|
|
52
|
+
px_to_crop_pt(page_width_dev_px - x1, pdf_scale),
|
|
53
|
+
px_to_crop_pt(y0, pdf_scale),
|
|
54
|
+
)
|
|
55
|
+
bitmap = page.render(
|
|
56
|
+
scale=pdf_scale,
|
|
57
|
+
fill_color=(255, 255, 255, 0),
|
|
58
|
+
crop=crop_pts,
|
|
59
|
+
rev_byteorder=True,
|
|
60
|
+
)
|
|
61
|
+
try:
|
|
62
|
+
return bitmap.to_pil().copy()
|
|
63
|
+
finally:
|
|
64
|
+
bitmap.close()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def iter_pdf_tiles(
|
|
68
|
+
page: pdfium.PdfPage,
|
|
69
|
+
*,
|
|
70
|
+
bounds: tuple[int, int, int, int],
|
|
71
|
+
page_width_dev_px: int,
|
|
72
|
+
page_height_dev_px: int,
|
|
73
|
+
pdf_scale: float,
|
|
74
|
+
tile_size: int = MAX_TILE_SIZE_PX,
|
|
75
|
+
) -> Iterator[tuple[int, int, PilImage]]:
|
|
76
|
+
"""Iterate over 2D rectangular tiles within given pixel bounds.
|
|
77
|
+
|
|
78
|
+
Yields:
|
|
79
|
+
Tuple of ``(tile_x0, tile_y0, tile_image)`` in device pixels.
|
|
80
|
+
"""
|
|
81
|
+
left, top, right, bottom = bounds
|
|
82
|
+
for y0 in range(top, bottom, tile_size):
|
|
83
|
+
y1 = min(y0 + tile_size, bottom)
|
|
84
|
+
for x0 in range(left, right, tile_size):
|
|
85
|
+
x1 = min(x0 + tile_size, right)
|
|
86
|
+
tile_image = render_pdf_tile(
|
|
87
|
+
page,
|
|
88
|
+
x0=x0,
|
|
89
|
+
y0=y0,
|
|
90
|
+
x1=x1,
|
|
91
|
+
y1=y1,
|
|
92
|
+
page_width_dev_px=page_width_dev_px,
|
|
93
|
+
page_height_dev_px=page_height_dev_px,
|
|
94
|
+
pdf_scale=pdf_scale,
|
|
95
|
+
)
|
|
96
|
+
yield x0, y0, tile_image
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def detect_tile_content_bbox(
|
|
100
|
+
tile_image: PilImage,
|
|
101
|
+
*,
|
|
102
|
+
is_transparent_bg: bool,
|
|
103
|
+
bg_sample: tuple[int, ...],
|
|
104
|
+
) -> tuple[int, int, int, int] | None:
|
|
105
|
+
"""Find the ink bounding box within a single rendered tile."""
|
|
106
|
+
if is_transparent_bg:
|
|
107
|
+
return tile_image.getbbox()
|
|
108
|
+
with Image.new("RGBA", tile_image.size, bg_sample) as bg_img:
|
|
109
|
+
diff_img = ImageChops.difference(tile_image, bg_img)
|
|
110
|
+
try:
|
|
111
|
+
return diff_img.getbbox()
|
|
112
|
+
finally:
|
|
113
|
+
diff_img.close()
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def render_pdf_crop(
|
|
117
|
+
pdf_bytes: bytes,
|
|
118
|
+
*,
|
|
119
|
+
dpi: int,
|
|
120
|
+
crop_box_px: tuple[int, int, int, int],
|
|
121
|
+
) -> PilImage:
|
|
122
|
+
"""Rasterize a specified region of the first PDF page in 2D tiles.
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
pdf_bytes: Raw PDF bytes.
|
|
126
|
+
dpi: Target resolution in dots per inch.
|
|
127
|
+
crop_box_px: Target ``(left, top, right, bottom)`` in device pixels.
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
A PIL RGBA Image containing the rendered crop region.
|
|
131
|
+
"""
|
|
132
|
+
pdf_scale = dpi / PDF_DPI
|
|
133
|
+
|
|
134
|
+
with pdfium.PdfDocument(pdf_bytes) as pdf:
|
|
135
|
+
if len(pdf) == 0:
|
|
136
|
+
return Image.new("RGBA", (1, 1), (255, 255, 255, 0))
|
|
137
|
+
|
|
138
|
+
page = pdf[0]
|
|
139
|
+
page_width_dev_px = math.ceil(page.get_width() * pdf_scale)
|
|
140
|
+
page_height_dev_px = math.ceil(page.get_height() * pdf_scale)
|
|
141
|
+
|
|
142
|
+
left, top, right, bottom = crop_box_px
|
|
143
|
+
left = max(0, min(left, page_width_dev_px - 1))
|
|
144
|
+
top = max(0, min(top, page_height_dev_px - 1))
|
|
145
|
+
right = max(left + 1, min(right, page_width_dev_px))
|
|
146
|
+
bottom = max(top + 1, min(bottom, page_height_dev_px))
|
|
147
|
+
|
|
148
|
+
canvas = Image.new("RGBA", (right - left, bottom - top), (255, 255, 255, 0))
|
|
149
|
+
|
|
150
|
+
for x0, y0, tile_image in iter_pdf_tiles(
|
|
151
|
+
page,
|
|
152
|
+
bounds=(left, top, right, bottom),
|
|
153
|
+
page_width_dev_px=page_width_dev_px,
|
|
154
|
+
page_height_dev_px=page_height_dev_px,
|
|
155
|
+
pdf_scale=pdf_scale,
|
|
156
|
+
):
|
|
157
|
+
canvas.paste(tile_image, (x0 - left, y0 - top))
|
|
158
|
+
|
|
159
|
+
return canvas
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def detect_pdf_content_bbox(
|
|
163
|
+
pdf_bytes: bytes,
|
|
164
|
+
*,
|
|
165
|
+
dpi: int,
|
|
166
|
+
background_color: str,
|
|
167
|
+
body_padding_css_px: int,
|
|
168
|
+
) -> tuple[int, int, int, int] | None:
|
|
169
|
+
"""Scan PDF page tiles from the top to detect ink content bounding box.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
pdf_bytes: Raw PDF bytes.
|
|
173
|
+
dpi: Target resolution in dots per inch.
|
|
174
|
+
background_color: CSS background color string.
|
|
175
|
+
body_padding_css_px: Expected CSS body padding.
|
|
176
|
+
|
|
177
|
+
Returns:
|
|
178
|
+
Raw ink bounding box ``(min_x, min_y, max_x, max_y)`` in device pixels,
|
|
179
|
+
or ``None`` if no content was found.
|
|
180
|
+
"""
|
|
181
|
+
pdf_scale = dpi / PDF_DPI
|
|
182
|
+
is_transparent_bg = background_color.strip().lower() in ("transparent", "")
|
|
183
|
+
max_empty_start_y_px = (
|
|
184
|
+
math.ceil(body_padding_css_px * (dpi / CSS_DPI)) + MAX_TILE_SIZE_PX
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
with pdfium.PdfDocument(pdf_bytes) as pdf:
|
|
188
|
+
if len(pdf) == 0:
|
|
189
|
+
return None
|
|
190
|
+
|
|
191
|
+
page = pdf[0]
|
|
192
|
+
page_width_dev_px = math.ceil(page.get_width() * pdf_scale)
|
|
193
|
+
page_height_dev_px = math.ceil(page.get_height() * pdf_scale)
|
|
194
|
+
|
|
195
|
+
min_x, min_y = page_width_dev_px, page_height_dev_px
|
|
196
|
+
max_x, max_y = 0, 0
|
|
197
|
+
has_content = False
|
|
198
|
+
bg_sample: tuple[int, ...] | None = None
|
|
199
|
+
|
|
200
|
+
for y0 in range(0, page_height_dev_px, MAX_TILE_SIZE_PX):
|
|
201
|
+
y1 = min(y0 + MAX_TILE_SIZE_PX, page_height_dev_px)
|
|
202
|
+
has_strip_content = False
|
|
203
|
+
|
|
204
|
+
for x0, tile_y0, tile_image in iter_pdf_tiles(
|
|
205
|
+
page,
|
|
206
|
+
bounds=(0, y0, page_width_dev_px, y1),
|
|
207
|
+
page_width_dev_px=page_width_dev_px,
|
|
208
|
+
page_height_dev_px=page_height_dev_px,
|
|
209
|
+
pdf_scale=pdf_scale,
|
|
210
|
+
):
|
|
211
|
+
if bg_sample is None:
|
|
212
|
+
pixel = tile_image.getpixel((0, 0))
|
|
213
|
+
bg_sample = (
|
|
214
|
+
pixel if isinstance(pixel, tuple) else (255, 255, 255, 255)
|
|
215
|
+
)
|
|
216
|
+
bbox = detect_tile_content_bbox(
|
|
217
|
+
tile_image,
|
|
218
|
+
is_transparent_bg=is_transparent_bg,
|
|
219
|
+
bg_sample=bg_sample,
|
|
220
|
+
)
|
|
221
|
+
if bbox is not None:
|
|
222
|
+
has_strip_content = True
|
|
223
|
+
has_content = True
|
|
224
|
+
min_x = min(min_x, x0 + bbox[0])
|
|
225
|
+
min_y = min(min_y, tile_y0 + bbox[1])
|
|
226
|
+
max_x = max(max_x, x0 + bbox[2])
|
|
227
|
+
max_y = max(max_y, tile_y0 + bbox[3])
|
|
228
|
+
|
|
229
|
+
if not has_strip_content and (has_content or y1 >= max_empty_start_y_px):
|
|
230
|
+
break
|
|
231
|
+
|
|
232
|
+
if not has_content:
|
|
233
|
+
return None
|
|
234
|
+
|
|
235
|
+
return min_x, min_y, max_x, max_y
|