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"

Upvotes: 1

Views: 8040

Answers (2)

Alexey Subach
Alexey Subach

Reputation: 12312

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));

Upvotes: 10

D A
D A

Reputation: 2054

For iText 7:

public static final Font HELVETICA_BOLD =
new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLUE);

new Text("MyText").setFontColor(Color.BLUE)
.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD));

You have some more details examples here

For iText 5:

 public const string DEFAULT_FONT_FAMILY = "Arial";

 public static Font SmallFontBold
    {
        get
        {
            BaseColor black = new BaseColor(0, 0, 0);
            Font font = FontFactory.GetFont(DEFAULT_FONT_FAMILY, 10, Font.BOLD, black);
            return font;
        }//get
    }//SmallFontBold

...   

Phrase aPh = new Phrase("My Bold", SmallFontBold);

And from here, you can try to use it combined.

Upvotes: 1

Related Questions