Skip to content

Commit

Permalink
Perf: improving speed of FPDF.start_section() - fix #1092 (#1127)
Browse files Browse the repository at this point in the history
  • Loading branch information
Lucas-C authored Feb 28, 2024
1 parent a0d3652 commit 5c56598
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 13 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ This can also be enabled programmatically with `warnings.simplefilter('default',
### Fixed

### Changed
* improved the performance of `FPDF.start_section()` - _cf._ [issue #1092](https://github.com/py-pdf/fpdf2/issues/1092)


## [2.7.8] - 2024-02-09
Expand Down
42 changes: 29 additions & 13 deletions fpdf/fpdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,12 @@ def __init__(
self.l_margin = l_margin
self.b_margin = b_margin

def __repr__(self):
return (
super().__repr__()[:-1]
+ f", t_margin={self.t_margin}, l_margin={self.l_margin}, b_margin={self.b_margin})"
)


class ToCPlaceholder(NamedTuple):
render_function: Callable
Expand Down Expand Up @@ -1918,7 +1924,7 @@ def set_font(self, family=None, style="", size=0):
)
style = ""

if size == 0:
if not size:
size = self.font_size_pt

# Test if font is already selected
Expand Down Expand Up @@ -4863,23 +4869,33 @@ def start_section(self, name, level=0, strict=True):
dest = DestinationXYZ(self.page, top=self.h_pt - self.y * self.k)
outline_struct_elem = None
if self.section_title_styles:
title_style = self.section_title_styles[level]
# We first check if adding this multi-cell will trigger a page break:
with self.offset_rendering() as pdf:
# pylint: disable=protected-access
with pdf._use_title_style(pdf.section_title_styles[level]):
pdf.multi_cell(
w=pdf.epw,
h=pdf.font_size,
text=name,
new_x=XPos.LMARGIN,
new_y=YPos.NEXT,
)
if pdf.page_break_triggered:
if title_style.size_pt is not None:
prev_font_size_pt = self.font_size_pt
self.font_size_pt = title_style.size_pt
page_break_triggered = self.multi_cell(
w=self.epw,
h=self.font_size,
text=name,
new_x=XPos.LMARGIN,
new_y=YPos.NEXT,
dry_run=True, # => does not produce any output
output=MethodReturnValue.PAGE_BREAK,
padding=Padding(
top=title_style.t_margin or 0,
left=title_style.l_margin or 0,
bottom=title_style.b_margin or 0,
),
)
if title_style.size_pt is not None:
self.font_size_pt = prev_font_size_pt
if page_break_triggered:
# If so, we trigger a page break manually beforehand:
self.add_page()
with self._marked_sequence(title=name) as struct_elem:
outline_struct_elem = struct_elem
with self._use_title_style(self.section_title_styles[level]):
with self._use_title_style(title_style):
self.multi_cell(
w=self.epw,
h=self.font_size,
Expand Down

0 comments on commit 5c56598

Please sign in to comment.