Skip to content

Commit dd832f9

Browse files
committed
ENH: _font: 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. Code blatantly copied from the _font.py file in the text extractor code.
1 parent 9452698 commit dd832f9

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

pypdf/_font.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,9 @@ def from_font_resource(cls, pdf_font_dict: DictionaryObject) -> "FontDescriptor"
3535
if font_name in CORE_FONT_METRICS:
3636
return CORE_FONT_METRICS[font_name]
3737
return cls(name=font_name)
38+
39+
def text_width(self, text: str) -> float:
40+
"""Sum of character widths specified in PDF font for the supplied text."""
41+
return sum(
42+
[self.character_widths.get(char, self.character_widths.get("default", 0)) for char in text], 0.0
43+
)

0 commit comments

Comments
 (0)