How to keep specific words together on one line?

I have a sample paragraph and I am adding chunk values to it like this:

 

p.add(firstname);
p.add(lastname);
p.add(phone);
p.add(login);
I want to make sure that firstname and lastname aren't split by a newline. When a phone number contains space characters, I don't want any newline to occur within the phone number.

Posted on StackOverflow on Oct 1, 2015 by Valeriane

Replace all the spaces where you don't want a line break with \u00A0. This way, you don't have to check positions etc. (That would only be possible if you calculate the width of every String snippet.)

For instance, if you do this:

Paragraph p = new Paragraph();
p.add("Valeriane\u00A0Valerius 012\u00A0345\u00A067\u00A089 valerianelogin");
doc.add(p);

The String can only be split on two places (unless you use so many non-breaking spaces that you take so much space that the part you don't want to break doesn't even fit a line).

P.S. Note that there are no Chunks in iText 7. We use Text instances as atomic parts of paragraphs instead.

Click this link if you want to see how to answer this question in iText 5.



Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now