iText pdf library
Website search

How can I use regular and bold in a single String?

I have a String that consists of a constant part and a variable part. How do I get the variable to be formatted using a regular font within the text paragraph, while the constant part is bold?

This is my code:


String cc_cust_name = request.getParameter("CC_CUST_NAME");
document.add(new Paragraph(" NAME  " + cc_cust_name, fontsmallbold));

My code for a cell in a table looks like this:


cell1 = new PdfPCell(new Phrase("Date of Birth" + cc_cust_dob ,fontsmallbold));
In both cases, the first part (" NAME " and "Date of Birth") should be bold and the variable part (cc_cust_name and cc_cust_dob) should be regular.


Posted on StackOverflow on Aug 11, 2015 by nitin

Right now you are creating a Paragraph using a single font: fontsmallbold. You want to create a Paragraph that uses two different fonts:

PdfFont regular = PdfFontFactory.createFont(FontConstants.HELVETICA);
PdfFont bold = PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD);
Text first = new Text("NAME: ").setFont(regular);
Text second = new Text(cc_cust_name).setFont(bold);
Paragraph paragraph = new Paragraph().add(first).add(second);
Cell cell = new Cell().add(paragraph);

As you can see, we created two Text objects and set different fonts for them. Now you just need to put these pieces to a Paragraph.

See also "How to use two different colors in a single String?" and "How to apply color to Strings in a Paragraph?" which are two questions that address the same topic.

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


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