【问题标题】:How can I Bold one Word in a Line in iText 7?如何在 iText 7 中加粗一行中的一个单词?
【发布时间】:2020-11-02 16:27:10
【问题描述】:

我可以像这样使用 iText 7 设置文本粗体:

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

...但是当我尝试将“正常”(非粗体)文本与粗体部分组合时,它不起作用。我有这个,它打印所有“常规”(无粗体)的行:

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

...但想将计算值加粗。这两个我都试过了:

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

...还有这个:

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

...但他们都不会编译,抱怨,“错误 CS1061 'string' 不包含 'SetBold' 的定义,并且没有可访问的扩展方法 'SetBold' 接受'string'类型的第一个参数可能是找到”

【问题讨论】:

  • 感谢您的赏金!您绝对不必这样做,但仍然非常愉快:)
  • @AlexeySubach:不用担心;我喜欢慷慨地提供奖励,部分原因是我会因此获得声誉,人们会更愿意回答。

标签: itext7 typography


【解决方案1】:

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

你有一些更详细的例子here

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

从这里开始,你可以尝试结合使用它。

【讨论】:

  • BaseColor 无法识别。
【解决方案2】:

较短的选项可能导致文本渲染质量不完美,因为使用了粗体模拟而不是适当的粗体:

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

代码更多但输出质量更好的选项,因为使用了正确的粗体:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多