Changing the font color and size when using FontSe

2019-01-24 16:35发布

问题:

I am using iText5 (Java) to write a PDF which may contain Chinese characters. So I am using FontSelector to process the String and this works fine.

Now the problem is that if there are 2 strings

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

I need to write str1 witch Font Color = Blue and size = 10, whereas str2 with Font Color = Gray and size = 25.

I am not able to figure out how to achieve this using FontSelector.

Any help is appreciated.

回答1:

That's easy. Here you have a code snippet that adds the Times Roman text in Blue and the Chinese text in Red:

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

In your case you need two 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:

you can do it in another way in my case i use 14 for header and 10 for data in tabular report

    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