Skip to content

Commit e3f60c1

Browse files
authored
BUG: PDF size increases because of too high float writing precision (#2213)
See #1910 address regression from #2203
1 parent 0a73b1d commit e3f60c1

File tree

4 files changed

+11
-3
lines changed

4 files changed

+11
-3
lines changed

pypdf/generic/_base.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,9 @@ def readFromStream(
379379
return IndirectObject.read_from_stream(stream, pdf)
380380

381381

382+
FLOAT_WRITE_PRECISION = 8 # shall be min 5 digits max, allow user adj
383+
384+
382385
class FloatObject(float, PdfObject):
383386
def __new__(
384387
cls, value: Union[str, Any] = "0.0", context: Optional[Any] = None
@@ -409,8 +412,8 @@ def clone(
409412
def myrepr(self) -> str:
410413
if self == 0:
411414
return "0.0"
412-
nb = int(log10(abs(self)))
413-
s = f"{self:.{max(1,16-nb)}f}".rstrip("0").rstrip(".")
415+
nb = FLOAT_WRITE_PRECISION - int(log10(abs(self)))
416+
s = f"{self:.{max(1,nb)}f}".rstrip("0").rstrip(".")
414417
return s
415418

416419
def __repr__(self) -> str:
-740 Bytes
Binary file not shown.

tests/test_generic.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1087,7 +1087,9 @@ def test_create_string_object_force():
10871087
("99900000000000000123", "99900000000000000000"),
10881088
("99900000000000000123.456000", "99900000000000000000"),
10891089
("0.00000000000000000000123", "0.00000000000000000000123"),
1090+
("0.00000123", "0.00000123"),
10901091
("0.00000000000000000000123000", "0.00000000000000000000123"),
1092+
("-4.6", "-4.6"), # from #1910
10911093
# (
10921094
# "50032481330523882508234.00000000000000000000123000",
10931095
# "50032481330523882508234.00000000000000000000123",

tests/test_writer.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -985,7 +985,9 @@ def test_colors_in_outline_item(pdf_file_path):
985985
reader2 = PdfReader(pdf_file_path)
986986
for outline_item in reader2.outline:
987987
# convert float to string because of mutability
988-
assert [str(c) for c in outline_item.color] == [str(p) for p in purple_rgb]
988+
assert ["%.5f" % c for c in outline_item.color] == [
989+
"%.5f" % p for p in purple_rgb
990+
]
989991

990992

991993
@pytest.mark.samples()
@@ -1619,6 +1621,7 @@ def test_watermark_rendering(tmp_path):
16191621
assert image_similarity(png_path, target_png_path) >= 0.95
16201622

16211623

1624+
@pytest.mark.skipif(GHOSTSCRIPT_BINARY is None, reason="Requires Ghostscript")
16221625
def test_watermarking_reportlab_rendering(tmp_path):
16231626
"""
16241627
This test is showing a rotated+mirrored watermark in pypdf==3.15.4.

0 commit comments

Comments
 (0)