使用FontSelector更改字体颜色和大小

6

我正在使用iText5(Java)编写可能包含中文字符的PDF文档。因此,我正在使用FontSelector来处理字符串,并且这是有效的。

但现在遇到的问题是,如果有两个字符串

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

我需要编写一个文本字符串str1, 其中字体颜色为蓝色且大小为10,另一个字符串str2的字体颜色为灰色且大小为25。不过我无法通过使用FontSelector实现此要求。希望能得到您的帮助。
2个回答

9
很简单,这里有一段代码片段,可以将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

太棒了。谢谢。 - Neela

0

在我的情况下,您可以以另一种方式完成它,我使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接