I can insert simple text like this:
document = new PDDocument();
page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
PDPageContentStream content = new PDPageContentStream(document, page);
content.beginText();
content.moveTextPositionByAmount (10 , 10);
content.drawString ("test text");
content.endText();
content.close();
but how can I create a paragraph similar to HTML using the width attribute?
<p style="width:200px;">test text</p>
According to this answer it’s not possible to insert line breaks into some text and have PDF display it correctly (whether using PDFBox or something else), so I believe auto-wrapping some text to fit in some width may also be something it can’t do automatically. (besides, there are many ways to wrap a text – whole words only, break them in smaller parts, etc)
This answer to another question (about centering a string) gives some pointers on how to do this yourself. Assuming you wrote a function
possibleWrapPoints(String):int[]to list all points in the text a word wrap can happen (excluding “zero”, including “text length”), one possible solution could be:One example of
possibleWrapPoints, that allow wrapping at any point that’s not part of a word (reference), could be:Update: some additional info:
The PDF file format was designed to look the same in different situations, functionality like the one you requested makes sense in a PDF editor/creator, but not in the PDF file per se. For this reason, most “low level” tools tend to concentrate on dealing with the file format itself and leave away stuff like that.
Higher level tools OTOH usually have means to make this conversion. An example is Platypus (for Python, though), that do have easy ways of creating paragraphs, and relies on the lower level ReportLab functions to do the actual PDF rendering. I’m unaware of similar tools for PDFBox, but this post gives some hints on how to convert HTML content to PDF in a Java environment, using freely available tools. Haven’t tried them myself, but I’m posting here since it might be useful (in case my hand-made attempt above is not enough).