Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removing useless trailing zeros in content streams #824

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ This can also be enabled programmatically with `warnings.simplefilter('default',
- [`FPDF.image()`](https://pyfpdf.github.io/fpdf2/fpdf/fpdf.html#fpdf.fpdf.FPDF.image): allowing images path starting with `data` to be passed as input
### Deprecated
- the `center` optional parameter of [`FPDF.cell()`](https://pyfpdf.github.io/fpdf2/fpdf/fpdf.html#fpdf.fpdf.FPDF.cell) is **no more** deprecated, as it allows for horizontal positioning, which is different from text alignment control with `align="C"`
### Changed
- useless trailing zeros in the PDF content streams have been removed, which makes the size of the generated PDF files slightly smaller

## [2.7.4] - 2023-04-28
### Added
Expand Down
2 changes: 1 addition & 1 deletion docs/Links.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ Other methods can also insert internal links:
* [FPDF.link](https://pyfpdf.github.io/fpdf2/fpdf/fpdf.html#fpdf.fpdf.FPDF.link)
* [FPDF.write_html](HTML.md) using anchor tags: `<a href="page number">link text</a>`

The unit tests `test_internal_links()` in [test_links.py](https://github.com/PyFPDF/fpdf2/blob/master/test/test_links.py) provides examples for all of those methods.
The unit test `test_internal_links()` in [test_links.py](https://github.com/PyFPDF/fpdf2/blob/master/test/test_links.py) provides examples for all of those methods.


## Links to other documents on the filesystem ##
Expand Down
9 changes: 6 additions & 3 deletions fpdf/annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from .syntax import create_dictionary_string as pdf_dict
from .syntax import create_list_string as pdf_list
from .syntax import iobj_ref as pdf_ref
from .util import nbr2str


# cf. https://docs.verapdf.org/validation/pdfa-part1/#rule-653-2
Expand Down Expand Up @@ -47,7 +48,9 @@ def __init__(
):
self.type = Name("Annot")
self.subtype = Name(subtype)
self.rect = f"[{x:.2f} {y:.2f} {x + width:.2f} {y - height:.2f}]"
self.rect = (
f"[{nbr2str(x)} {nbr2str(y)} {nbr2str(x + width)} {nbr2str(y - height)}]"
)
self.border = f"[0 0 {border_width}]"
self.f_t = Name(field_type) if field_type else None
self.v = value
Expand All @@ -59,14 +62,14 @@ def __init__(
self.t = PDFString(title) if title else None
self.m = PDFDate(modification_time) if modification_time else None
self.quad_points = (
pdf_list(f"{quad_point:.2f}" for quad_point in quad_points)
pdf_list(f"{nbr2str(quad_point)}" for quad_point in quad_points)
if quad_points
else None
)
self.p = None # must always be set before calling .serialize()
self.name = name
self.ink_list = (
("[" + pdf_list(f"{coord:.2f}" for coord in ink_list) + "]")
("[" + pdf_list(f"{nbr2str(coord)}" for coord in ink_list) + "]")
if ink_list
else None
)
Expand Down
48 changes: 16 additions & 32 deletions fpdf/drawing.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
PDFStyleKeys,
)
from .syntax import Name, Raw
from .util import escape_parens
from .util import escape_parens, nbr2str

__pdoc__ = {"force_nodocument": False}

Expand Down Expand Up @@ -87,21 +87,6 @@ def _check_range(value, minimum=0.0, maximum=1.0):
return value


def number_to_str(number):
"""
Convert a decimal number to a minimal string representation (no trailing 0 or .).

Args:
number (Number): the number to be converted to a string.

Returns:
The number's string representation.
"""
# this approach tries to produce minimal representations of floating point numbers
# but can also produce "-0".
return f"{number:.4f}".rstrip("0").rstrip(".")


# this maybe should live in fpdf.syntax
def render_pdf_primitive(primitive):
"""
Expand Down Expand Up @@ -143,7 +128,7 @@ def render_pdf_primitive(primitive):
elif isinstance(primitive, bool): # has to come before number check
output = ["false", "true"][primitive]
elif isinstance(primitive, NumberClass):
output = number_to_str(primitive)
output = nbr2str(primitive)
elif isinstance(primitive, (list, tuple)):
output = "[" + " ".join(render_pdf_primitive(val) for val in primitive) + "]"
elif isinstance(primitive, dict):
Expand Down Expand Up @@ -209,7 +194,7 @@ def colors(self):
return self[:-1]

def serialize(self) -> str:
return " ".join(number_to_str(val) for val in self.colors) + f" {self.OPERATOR}"
return " ".join(nbr2str(val) for val in self.colors) + f" {self.OPERATOR}"


__pdoc__["DeviceRGB.OPERATOR"] = False
Expand Down Expand Up @@ -252,7 +237,7 @@ def colors(self):
return self[:-1]

def serialize(self) -> str:
return " ".join(number_to_str(val) for val in self.colors) + f" {self.OPERATOR}"
return " ".join(nbr2str(val) for val in self.colors) + f" {self.OPERATOR}"


__pdoc__["DeviceGray.OPERATOR"] = False
Expand Down Expand Up @@ -308,7 +293,7 @@ def colors(self):
return self[:-1]

def serialize(self) -> str:
return " ".join(number_to_str(val) for val in self.colors) + f" {self.OPERATOR}"
return " ".join(nbr2str(val) for val in self.colors) + f" {self.OPERATOR}"


__pdoc__["DeviceCMYK.OPERATOR"] = False
Expand Down Expand Up @@ -481,7 +466,7 @@ class Point(NamedTuple):
def render(self):
"""Render the point to the string `"x y"` for emitting to a PDF."""

return f"{number_to_str(self.x)} {number_to_str(self.y)}"
return f"{nbr2str(self.x)} {nbr2str(self.y)}"

def dot(self, other):
"""
Expand Down Expand Up @@ -679,7 +664,7 @@ def __matmul__(self, other):
return NotImplemented

def __str__(self):
return f"(x={number_to_str(self.x)}, y={number_to_str(self.y)})"
return f"(x={nbr2str(self.x)}, y={nbr2str(self.y)})"


class Transform(NamedTuple):
Expand Down Expand Up @@ -1019,18 +1004,18 @@ def render(self, last_item):
A tuple of `(str, last_item)`. `last_item` is returned unchanged.
"""
return (
f"{number_to_str(self.a)} {number_to_str(self.b)} "
f"{number_to_str(self.c)} {number_to_str(self.d)} "
f"{number_to_str(self.e)} {number_to_str(self.f)} cm",
f"{nbr2str(self.a)} {nbr2str(self.b)} "
f"{nbr2str(self.c)} {nbr2str(self.d)} "
f"{nbr2str(self.e)} {nbr2str(self.f)} cm",
last_item,
)

def __str__(self):
return (
f"transform: ["
f"{number_to_str(self.a)} {number_to_str(self.b)} 0; "
f"{number_to_str(self.c)} {number_to_str(self.d)} 0; "
f"{number_to_str(self.e)} {number_to_str(self.f)} 1]"
f"{nbr2str(self.a)} {nbr2str(self.b)} 0; "
f"{nbr2str(self.c)} {nbr2str(self.d)} 0; "
f"{nbr2str(self.e)} {nbr2str(self.f)} 1]"
)


Expand Down Expand Up @@ -3155,7 +3140,7 @@ def render(self, gsd_registry, first_point, scale, height, starting_style):
render_list.insert(
3,
render_pdf_primitive(style.stroke_dash_pattern)
+ f" {number_to_str(style.stroke_dash_phase)} d",
+ f" {nbr2str(style.stroke_dash_phase)} d",
)

render_list.append("Q")
Expand Down Expand Up @@ -3220,7 +3205,7 @@ def render_debug(
render_list.insert(
3,
render_pdf_primitive(style.stroke_dash_pattern)
+ f" {number_to_str(style.stroke_dash_phase)} d",
+ f" {nbr2str(style.stroke_dash_phase)} d",
)

render_list.append("Q")
Expand Down Expand Up @@ -4076,8 +4061,7 @@ def build_render_list(

if emit_dash is not None:
render_list.append(
render_pdf_primitive(emit_dash[0])
+ f" {number_to_str(emit_dash[1])} d"
render_pdf_primitive(emit_dash[0]) + f" {nbr2str(emit_dash[1])} d"
)

if debug_stream:
Expand Down
Loading