Why can't I set the font of a Phrase?

I'm starting with iTextSharp and wondering if there is any reason why setting the font of a Phrase after the construction of the object doesn't work. Is there any reason, do I miss something?


iTextSharp.text.Font f = PdfFontFactory.GetComic();
Color c = Color.DarkRed;
f.Size = 20;
Phrase titreFormules = new Phrase("Nos formules",f); //THIS WORKS
// titreFormules.Font = f; // THIS DOESN'T WORK!

Posted on StackOverflow on Sep 11, 2014 by Alain BUFERNE

In your example "Nos formules" will be written in Helvetica. You change the font after the Helvetica Chunk with the text "Nos formules" was added to the Phrase. As you didn't add anything else to titreFormules, the font "Comic" is never used.

When you use setFont(), you change the font of the Phrase for all the content that is added after the font was set.

Note that there are no Chunks and Phrases in iText 7. Let me introduce some changes:

  • Text as an atomic part of text in the sense that all the text inside has the same font family, font size, font color,...

  • Paragraph is a collection of Text objects and it can contain different 'atoms' of text using different fonts.

Your code in Java will code like this:

public void createPdf(String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc);
    PdfFont f = PdfFontFactory.createFont(FontConstants.COURIER);
    Text redText = new Text("Nos formules")
    Paragraph p = new Paragraph().add(redText);

I used Courier font, but you can set any font you want. Feel free to create other Text instances with different properties and add them to the Paragraph. If you want an iText for C# example, you'll discover that it is very easy to port the Java to C# as the terminology is identical.

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

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