jorisschellekens / borb

borb is a library for reading, creating and manipulating PDF files in python.
https://borbpdf.com/
Other
3.4k stars 147 forks source link

Customizable Column Fonts in 'TableUtil.from_pandas_dataframe' #194

Closed Tofull closed 9 months ago

Tofull commented 9 months ago

This pull request introduces the optional parameter font_by_column to the from_pandas_dataframe function, enabling users to customize the font for each column in the table.

The default behavior remains unchanged, and tables continue to be displayed using the Helvetica font by default.

When the font_by_column parameter is set, it should be provided as a dictionary, where the keys correspond to the column names of the dataframe, and the values represent the desired font names for each respective column.

This enhancement proves particularly beneficial when working with dataframes containing email columns within non-flexible tables. In such cases, where large emails lack spacing, resulting paragraphs can become unbreakable, causing text to extend beyond the cell boundaries. With the introduction of font_by_column, users can selectively set the font, such as to Courier (a monospace font) for the email column, thereby controlling the string length to fit within the cell. This ensures a more predictable display of the table, granting users greater control over the presentation.

Additionally, this pull request includes a test to validate the functionality of the new font_by_column parameter.

Example

# Generate random email addresses and dates for the dataframe
data = pd.DataFrame(
    {
        "email": [generate_fake_email() for _ in range(10)],
        "last_login": [generate_random_date() for _ in range(10)],
    }
)

doc: Document = Document()
page: Page = Page()
doc.add_page(page)
layout: PageLayout = SingleColumnLayout(page)
layout.add(TableUtil.from_pandas_dataframe(
    data,
    font_by_column={
        "email": "Courier",
    },
))

image

Related to https://github.com/jorisschellekens/borb/issues/134

jorisschellekens commented 9 months ago

To me this feels like a bridge too far.

The user has the option of building a Table and specifying exactly which fonts, font sizes, etc are used in each row/column/cell.