Skip to content

Commit a2e940c

Browse files
committed
ENH: _writer: Add method to calculate text width
This adds a method to calculate the width of a text string. This method can later be used to wrap text at a certain length.
1 parent 8c22223 commit a2e940c

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

pypdf/_writer.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3408,6 +3408,30 @@ def _create_outline_item(
34083408
return outline_item
34093409

34103410

3411+
def calculate_text_width(character_widths: dict[str, int], font_size: float, txt: str) -> float:
3412+
"""
3413+
Calculates the display width of a given text string in PDF user space units.
3414+
3415+
Args:
3416+
character_widths: A dictionary with font widths.
3417+
font_size: The font size in points
3418+
txt: A text string, the width of which you'd like to know
3419+
3420+
Returns:
3421+
The text string width in PDF user space units
3422+
"""
3423+
total_font_units_width: float = 0
3424+
3425+
for char in txt:
3426+
try:
3427+
char_width = character_widths[char]
3428+
except KeyError:
3429+
char_width = character_widths.get("default", 0)
3430+
total_font_units_width += char_width
3431+
3432+
return (total_font_units_width * font_size) / 1000.0
3433+
3434+
34113435
def generate_appearance_stream(
34123436
txt: str,
34133437
sel: list[str],

0 commit comments

Comments
 (0)