使用Itext将颜色应用于段落中的字符串 [英] Applying color to Strings in Paragraph using Itext

查看:559
本文介绍了使用Itext将颜色应用于段落中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将2个字符串组合成Paragraph,

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

问题是我为str1和amp;获得相同的字体颜色str2。

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

我想为str1& ;;提供不同的字体颜色和大小。 str2 ..

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

我如何在ColumnText / Paragraph上做到这一点?

How Can i do that on ColumnText/Paragraph?

有人可以帮助我...

Can someone help me in this...

推荐答案

您将文本组合成段落,如下所示:

When you combine text into a Paragraph like this:

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

您隐式告诉iText abc应使用相同(默认)字体呈现def。您可能知道,段落对象的集合。在iText中, Chunk 就像文本的原子部分,因为 Chunk 中的所有文本都具有相同的字体,字体大小,字体颜色等...

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...

如果你想用不同的方法创建一个段落字体颜色,您需要使用不同的 Chunk 对象组成段落。这显示在 ColoredText 示例中:

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

在这个例子中,我们创建了两个段落。一个带有一个 Chunk 的红色。另一个包含两个 Chunk 的颜色不同。

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

在你的问题中,你引用 ColumnText 。下一个代码段在 ColumnText 中使用 p1 p2 context:

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

结果,段落被添加两次:一次由iText定位,一旦定位我们自己定义坐标使用矩形

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

这篇关于使用Itext将颜色应用于段落中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆