2012-12-13 191 views
5

我正在使用iText5(Java)编写可能包含中文字符的PDF。所以我使用FontSelector来处理字符串,这工作正常。使用FontSelector时更改字体颜色和大小

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

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

我需要写str1Font Color = Bluesize = 10,而str2Font Color = Graysize = 25

我无法弄清楚如何使用FontSelector来实现这个目标。

任何帮助表示赞赏。

回答

8

这很简单。这里有一个代码片段,增加了蓝色时代罗马文字和中国文字红:

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 
+0

真棒。谢谢。 – 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