【问题标题】:Changing the font color and size when using FontSelector使用 FontSelector 时更改字体颜色和大小
【发布时间】:2017-10-31 07:01:15
【问题描述】:

我正在使用iText5 (Java) 编写可能包含中文字符的 PDF。所以我使用FontSelector 来处理字符串,这工作正常。

现在的问题是,如果有 2 个字符串

String str1 = "Hello Test1";
String str2 = "Hello Test2";

我需要写str1 女巫Font Color = Blue 和size = 10,而str2 和Font Color = Gray 和size = 25。

我无法弄清楚如何使用 FontSelector 来实现这一点。

感谢任何帮助。

【问题讨论】:

    标签: itext font-size


    【解决方案1】:

    这很容易。这里有一个代码 sn-p,它添加了蓝色的 Times Roman 文本和红色的中文文本:

    FontSelector selector = new FontSelector();
    Font f1 = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12);
    f1.setColor(BaseColor.BLUE);
    Font f2 = FontFactory.getFont("MSung-Light",
            "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED);
    f2.setColor(BaseColor.RED);
    selector.addFont(f1);
    selector.addFont(f2);
    Phrase ph = selector.process(TEXT);
    

    在您的情况下,您需要两个 FontSelectors。

    FontSelector selector1 = new FontSelector();
    Font f1 = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12);
    f1.setColor(BaseColor.BLUE);
    selector1.addFont(f1);
    Phrase ph = selector1.process(str1);//First one
    
    FontSelector selector2 = new FontSelector();
    Font f2 = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12);
    f2.setColor(BaseColor.GRAY);
    selector2.addFont(f2);
    Phrase ph = selector2.process(str2);//Second one
    

    【讨论】:

    • 太棒了。谢谢。
    【解决方案2】:

    你可以用另一种方式来做,在我的例子中,我使用 14 作为标题,10 作为表格报告中的数据

        private Font fHeader;
        private Font f1;
    
        BaseFont bf = BaseFont.createFont(Constants.Settings.ARIAL_FONT, BaseFont.IDENTITY_H, true);
    
         f1 = new Font(bf, 10);
         fHeader= new Font(bf,14);
         PdfPCell cell = new PdfPCell();
    
    //for report header
         cell = new PdfPCell(new Phrase(reportKingdomData + "\n" + departmentData + " " + username + " \n  " + reportHeader + "    \n ", fHeader));
    
    //and for background color
     cell .setBackgroundColor(new GrayColor(0.40f));//if 0.10f will be closer to black
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      • 2011-03-14
      相关资源
      最近更新 更多