Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pdfbox wrap text

Tags:

java

text

pdfbox

I am using PDFBox with the following code:

doc = new PDDocument();
page = new PDPage();

doc.addPage(page);
PDFont font = PDType1Font.COURIER;

pdftitle = new PDPageContentStream(doc, page);
pdftitle.beginText();
pdftitle.setFont( font, 12 );
pdftitle.moveTextPositionByAmount( 40, 740 );
pdftitle.drawString("Here I insert a lot of text");
pdftitle.endText();
pdftitle.close();

Does anyone know how I can wrap the text so that it automatically goes to another line?

like image 378
Igor Tupitsyn Avatar asked Feb 04 '13 11:02

Igor Tupitsyn


People also ask

Is PDFBox free for commercial use?

Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative ...

Is PDFBox thread safe?

Is PDFBox thread safe? No! Only one thread may access a single document at a time. You can have multiple threads each accessing their own PDDocument object.

What is the use of PDFBox?

It allows the creation of new PDF documents, manipulation of existing documents, bookmarking PDF and the ability to extract content from PDF documents. We can also use it to digitally sign, print and validate files against the PDF/A-1b standard. PDFBox library was originally developed in 2002 by Ben Litchfield.


2 Answers

This worked for me. A combination of WordUtils and split

String[] wrT = null;
String s = null;
text = "Job Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque hendrerit lectus nec ipsum gravida placerat. Fusce eu erat orci. Nunc eget augue neque. Fusce arcu risus, pulvinar eu blandit ac, congue non tellus. Sed eu neque vitae dui placerat ultricies vel vitae mi. Vivamus vulputate nullam.";
wrT = WordUtils.wrap(text, 100).split("\\r?\\n");

for (int i=0; i< wrT.length; i++) {
    contents.beginText();
    contents.setFont(PDType1Font.HELVETICA, 10);
    contents.newLineAtOffset(50,600-i*15);
    s = wrT[i];
    contents.showText(s);
    contents.endText(); 
}
like image 113
Viviana Matthews Avatar answered Oct 10 '22 01:10

Viviana Matthews


I don't think it is possible to wrap text automatically. But you can wrap your text yourself. See How to Insert a Linefeed with PDFBox drawString and How can I create fixed-width paragraphs with PDFbox?.

like image 28
Lukas Avatar answered Oct 10 '22 00:10

Lukas