Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get ReportLab to line-break at hyphens?

I have a design template that forces me to use very large uppercase letters for a headline. If I have a long word that does not fit into one line, I run into expected problems because RL does not have built-in hyphenation – that’s okay. If I have a long compound word, however, that contains a hyphen (e.g. "VVVVEEEERRRRYYYY-LLLLOOOONNNNGGGG"), it is not broken at the hyphen as I would expect.

Expected:

|VVVVEEEERRRRYYYY-      |
|LLLLOOOONNNNGGGG       |

Actual:

|VVVVEEEERRRRYYYY-LLLLOO|
|OONNNNGGGG             |

How can I tell ReportLab to perform a conditional line-break when encountering a hyphen?

BTW, the PDF is generated using Python 3.4 and reportlab 3.1.8 like so:

doc = BaseDocTemplate(fname,
                      leftMargin=20 * mm, rightMargin=20 * mm,
                      topMargin=25 * mm, bottomMargin=20 * mm)
story = []
frame_first_page = Frame(doc.leftMargin, doc.bottomMargin, doc.width,
                         doc.height - 24 * mm,
                         leftPadding=0, rightPadding=0, id='first')
doc.addPageTemplates([PageTemplate(id='first_page',
                      frames=frame_first_page,
                      onPage=_on_first_page),
                      PageTemplate(id='remaining_pages',
                      frames=frame_remaining_pages,
                      onPage=_on_remaining_pages)])
story.append(Paragraph(heading_text.upper(), styles["title"]))
doc.build(story)
like image 905
ilpssun Avatar asked Nov 22 '22 03:11

ilpssun


1 Answers

This is an old question, but I stumbled upon the same problem today and found a solution: ReportLab seems to only wrap on white-space, so the idea is to add white-space with no visual space. Sadly it does not recognize the „zero width space“ or the „zero width non-joiner“ ‌ as a word-boundary, but the „thin space“ (encoded e.g. as  ) and the even thinner „hair space“   works and in my tests are good enough regarding no visual space.

So replacing all hyphens in your content should help: text_content.replace("-", "- ")

like image 179
Richard Avatar answered Dec 05 '22 04:12

Richard