How to use two different colors in a single String?

I have string like below, and I can't split the string. String result = "Developed By : Mr.XXXXX"; I can create a paragraph in iText and set font with color like this: Font dataGreenFont = Font

I have string like below, and I can't split the string.

String result = "Developed By : Mr.XXXXX";
I can create a paragraph in iText and set font with color like this:

Font dataGreenFont = FontFactory.getFont("Garamond", 10,Color.GREEN);
preface.add(new Paragraph(result, dataGreenFont));
It sets the green color to the entire text result but I want to set the color only for Mr. XXXXX part. How do I do this?

Posted on StackOverflow on Jun 17, 2014 by Ramakrishna

In iText 7 a Paragraph consists of a series of Text objects. A Text object is an atomic part of text in which all the glyphs are in the same font, have the same font size, color, etc...

Hence you need to split your String in two parts:

public static final String FONT_DIR = "src/main/resources/fonts/";

public void createPdf(String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc);

    FontProgramFactory.registerFont(FONT_DIR + "EBGaramond12-Regular.ttf", "Garamond");
    PdfFont garamond = PdfFontFactory.createRegisteredFont("Garamond", PdfEncodings.WINANSI, false);

    Text blackText = new Text("Developed By : ")
            .setFontColor(Color.BLACK)
            .setFont(garamond);
    Text greenText = new Text("Mr.XXXXX")
            .setFontColor(Color.GREEN)
            .setFont(garamond);

    Paragraph p1 = new Paragraph();
    p1.add(blackText);
    p1.add(greenText);
    doc.add(p1);

    doc.close();
}

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


Share this article

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