py-pdf / fpdf2

Simple PDF generation for Python
https://py-pdf.github.io/fpdf2/
GNU Lesser General Public License v3.0
993 stars 227 forks source link

Text columns issue with top margin #1214

Closed andersonhc closed 3 days ago

andersonhc commented 1 week ago

I ran in a problem with text columns where when a paragraph starts at the bottom of a column and it has a top margin that should push the text to the next column, it causes a page break and stay on the same column.

This is a simple example:

from fpdf import FPDF

LOREM_IPSUM = "Lorem ipsum Ut nostrud irure reprehenderit anim nostrud dolore sed ut Excepteur dolore ut sunt irure consectetur tempor eu tempor nostrud dolore " * 12

pdf = FPDF()
pdf.add_page()
pdf.set_font("Helvetica", "", 14)

with pdf.text_columns(text_align="J", ncols=2) as cols:
    for _ in range(3):
        with cols.paragraph(
            text_align="J",
            bottom_margin=pdf.font_size * 5,
            top_margin = pdf.font_size * 5,
        ) as par:
            par.write(text=LOREM_IPSUM)

pdf.output("text-region-cols.pdf")

I believe the problem is in TextRegion._render_column_lines, the code that detects pdf.y surpassing bottom is in a else statement and never executed when top margin is added.

@gmischler do you think there is any possible side effect removing the else from line 527 and de-indenting the 3 lines under it?

gmischler commented 1 week ago

@gmischler do you think there is any possible side effect removing the else from line 527 and de-indenting the 3 lines under it?

An interesting corner case, thanks for catching that! Your suggested solution looks reasonable at first glance. But it may be worth to also check if paragraph top margins are correctly taken into account in other places, like eg. the calculation to determine the total height required by the text on line 676. I can take a closer look at it later this week.