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 the same font color for both
str2. I want to have different font color and size for these
Strings. How Can I do that on
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
Text objects. In iText 7, a
Text object is like an atomic part of text in the sense that all the text in this object 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
Text objects. This is shown in the ColoredText example:
Text redText = new Text("This text is red. ") .setFontColor(Color.RED) .setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); Text blueText = new Text("This text is blue and bold. ") .setFontColor(Color.BLUE) .setFont(PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD)); Text greenText = new Text("This text is green and italic. ") .setFontColor(Color.GREEN) .setFont(PdfFontFactory.createFont(FontConstants.HELVETICA_OBLIQUE)); Paragraph p1 = new Paragraph(redText).setMargin(0); doc.add(p1); Paragraph p2 = new Paragraph().setMargin(0); p2.add(blueText); p2.add(greenText); doc.add(p2); new Canvas(new PdfCanvas(pdfDoc.getLastPage()), pdfDoc, new Rectangle(36, 600, 108, 160)) .add(p1) .add(p2);
In this example, we create two paragraphs. One with a single
Text in red. Another one that contains two
Texts with a different color.
As a result, the paragraphs are added twice: once positioned by iText, once positioned by ourselves by defining coordinates using a
Click this link if you want to see how to answer this question in iText 5.