Applying color to Strings in Paragraph using Itext

狂风中的少年 提交于 2019-12-24 02:09:14

问题


I am combining 2 strings to Paragraph this way,

String str2="";
String str1="";
ColumnText ct = new ColumnText(cb);
ct.setSimpleColumn(36, 600, 600, 800);
ct.addElement(new Paragraph(str1 + str2));
int status1 = ct.go();

The problem is I am getting same font color for both str1 & str2.

I want to have different font color and size for str1 & str2..

How Can i do that on ColumnText/Paragraph?

Can someone help me in this...


回答1:


When you combine text into a Paragraph like this:

Paragraph p = new Paragraph("abc" + "def");

You implicitly tell iText that "abc" and "def" should be rendered using the same (default) font. As you probably know, a Paragraph is a collection of Chunk objects. In iText, a Chunk is like an atomic part of text in the sense that all the text in a Chunk has the same font, font size, font color, etc...

If you want to create a Paragraph with different font colors, you need to compose your Paragraph using different Chunk objects. This is shown in the ColoredText example:

Font red = new Font(FontFamily.HELVETICA, 12, Font.NORMAL, BaseColor.RED);
Chunk redText = new Chunk("This text is red. ", red);
Font blue = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLUE);
Chunk blueText = new Chunk("This text is blue and bold. ", blue);
Font green = new Font(FontFamily.HELVETICA, 12, Font.ITALIC, BaseColor.GREEN);
Chunk greenText = new Chunk("This text is green and italic. ", green);
Paragraph p1 = new Paragraph(redText);
document.add(p1);
Paragraph p2 = new Paragraph();
p2.add(blueText);
p2.add(greenText);
document.add(p2);

In this example, we create two paragraphs. One with a single Chunk in red. Another one that contains two Chunks with a different color.

In your question, you refer to ColumnText. The next code snippet uses p1 and p2 in a ColumnText context:

ColumnText ct = new ColumnText(writer.getDirectContent());
ct.setSimpleColumn(new Rectangle(36, 600, 144, 760));
ct.addElement(p1);
ct.addElement(p2);
ct.go();

As a result, the paragraphs are added twice: once positioned by iText, once positioned by ourselves by defining coordinates using a Rectangle:



来源:https://stackoverflow.com/questions/27578497/applying-color-to-strings-in-paragraph-using-itext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!