I have created 2 paragraphs and added them to paragraph3 this way,
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("NextLineTextPDF.pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); cb.beginText(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font grey = new Font(bf,12f,0,Color.gray); Chunk blueText = new Chunk(leading1, grey); Font blue = new Font(bf,12f,0,Color.BLUE); Chunk greenText = new Chunk(leading2, blue); Paragraph p1 = new Paragraph(blueText); Paragraph p2 = new Paragraph(greenText); Paragraph p3 = new Paragraph(); p3.add(blueText); p3.add(greenText); document.add(p3); cb.endText();
But the problem is, if the string inside paragraph3 is is lenghty, characters are trimmed and the string is nor wrapped.
Is there any way, so that I can enclose my Paragraph3 into a recctangle , to wrap my string, without trimming?
You created 2 paragraphs, and you add them to a third paragraph. May I ask why?
Although you can do that, it doesn’t make any sense. Either you create one
Paragraph consisting of the
greenText chunks, or you create two paragraphs, and you add them to the page sequentially.
You say you want to add these paragraphs to a rectangle, yet you are using
May I ask why?
When you use
document.add(); you tell iText to position the text for you, based on the size of the page and its margins.
If you want to add text at absolute positions, for instance in a rectangle, you have two options.
You can do it the hard way, by using a sequence of low-level operations, as is done in this question: Separating redundant code from pdf generator function, but given your level of expertise, I would not advise you to do this. If I were you, I would look at my answer to the question, and use the
Adding paragraphs to a rectangle is done like this:
rectangle is a
Rectangle object defining the coordinates of the rectangle where you want to add the two paragraphs, then you need this code:
ColumnText ct = new ColumnText(writer.getDirectContent()); ct.setSimpleColumn(rectangle); ct.addElement(p1); ct.addElement(p2); ct.go();
As you can see, there is no need for a third paragraph. However, you need to be careful and make sure that the content fits the rectangle. Read these questions and answers before you start implementing:
- How to fit a String inside a rectangle?
- Using ColumnText results in “The document has no pages” exception
These questions were selected for the book “The Best iText Questions on StackOverflow”. The book is available for free. There’s also a question and answer that explains how to draw the rectangle, should that really be one of your requirements.