I am using Pdfbox to generate PDF files using Java. The problem is that when i add long text contents in the document, it is not displayed properly. Only a part of it is displayed. That too in a single line.
I want text to be in multiple lines.
My code is given below:
PDPageContentStream pdfContent=new PDPageContentStream(pdfDocument, pdfPage, true, true);
pdfContent.beginText();
pdfContent.setFont(pdfFont, 11);
pdfContent.moveTextPositionByAmount(30,750);
pdfContent.drawString("I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox");
pdfContent.endText();
My output:
Adding to the answer of Mark you might want to know where to split your long string. You can use the
PDFont
methodgetStringWidth
for that.Putting everything together you get something like this (with minor differences depending on the PDFBox version):
PDFBox 1.8.x
(BreakLongString.java test
testBreakString
for PDFBox 1.8.x)PDFBox 2.0.x
(BreakLongString.java test
testBreakString
for PDFBox 2.0.x)The result
This looks as expected.
Of course there are numerous improvements to make but this should show how to do it.
Adding unconditional line breaks
In a comment aleskv asked:
One can easily extend the solution to unconditionally break at newline characters by first splitting the string at '\n' characters and then iterating over the split result.
E.g. if instead of the long string from above
you want to process this even longer string with embedded new line characters
you can simply replace
in the solutions above by
(from BreakLongString.java test
testBreakStringNL
)The result:
contentStream.moveTextPositionByAmount(textx,texty) is key point.
say for example if you are using a A4 size means 580,800 is width and height correspondling(approximately). so you have move your text based on the position of your document size.
PDFBox supports varies page format . so the height and width will vary for different page format
Just draw the string in a position below, typically done within a loop:
These are the important lines:
Just keep drawing new strings in new positions. For an example using a table, see here: http://fahdshariff.blogspot.ca/2010/10/creating-tables-with-pdfbox.html
I know it's a bit late, but i had a little problem with mkl's solution. If the last line would only contain one word, your algorithm writes it on the previous one.
For Example: "Lorem ipsum dolor sit amet" is your text and it should add a line break after "sit".
But it does this:
I came up with my own solution i want to share with you.