Search code examples
itext7typography

How can I Bold one Word in a Line in iText 7?


I can set text bold using iText 7 like so:

parExecSummHeader2.Add(new Text(subj).SetBold());

...but when I try to combine a "normal" (non-bolded) bit of text with a bolded part, it doesn't work. I have this, which prints the line all "regular" (no bold):

parExecSummHeader2.Add("Average words per sentence (the general average is 15 - 20): " + Math.Round(WordsPerSentenceInDoc, 2).ToString());
            

...but want to make the calculated value bold. I tried both this:

parExecSummHeader2.Add("Average words per sentence (the general average is 15 - 20): ");
parExecSummHeader2.Add(new Text(Math.Round(WordsPerSentenceInDoc, 2).ToString().SetBold()));

...and this:

parExecSummHeader2.Add("Average words per sentence (the general average is 15 - 20): ");
string mathval = Math.Round(WordsPerSentenceInDoc, 2).ToString();
parExecSummHeader2.Add(new Text(mathval.SetBold()));

...but they both won't compile, complaining, "Error CS1061 'string' does not contain a definition for 'SetBold' and no accessible extension method 'SetBold' accepting a first argument of type 'string' could be found"


Solution

  • Shorter option which may result in not perfect quality of text rendering because bold simulation is used instead of a proper bold font:

    Paragraph parExecSummHeader2 = new Paragraph();
    parExecSummHeader2.Add("Average words per sentence (the general average is 15 - 20): ");
    parExecSummHeader2.Add(new Text("123").SetBold());
    

    Option with more code but better output quality because the proper bold font is use:

    PdfFont boldFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
    Paragraph parExecSummHeader2 = new Paragraph();
    parExecSummHeader2.Add("Average words per sentence (the general average is 15 - 20): ");
    parExecSummHeader2.Add(new Text("123").SetFont(boldFont));