Facundo Ezequiel Diaz Cappella
Posted on May 14, 2021
Hi, I found this library PDFBox to create pdf documents and when I started to use I feel this library less intuitive than the others I used, for that I think this post will be helpful if you are using pdfbox for the first time.
The First step, will be to add the dependency, you can check here the last version:
MVNRepository
Now we will create a java class, to create a pdf from a big string. This class will be adding a new line for every sentence and after 25 lines will be adding a new page. (Of course, I put 25 lines, but you can put whatever you want).
I will add two constants the font size and leading:
private final static float FONT_SIZE = 12;
private final static float LEADING = 1.5f * 12;
If you see the value of leading it's using the font size.
Here you can see the main public method of this class, in my case "the big text" always have the new line code \n , but you can break your text using a different condition, this is to create a new line per sentences:
private void createMultiLinePagePdf(String text) throws IOException {
PDDocument doc = new PDDocument();
// break big text using my endof line flag
String[] listText = text.split("\n");
// create new page and add to the document, this is the
// first page
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new
PDPageContentStream(doc, page);
// here we set the leading and font
contentStream.setFont(getFont(), FONT_SIZE);
contentStream.setLeading(LEADING);
contentStream.beginText();
contentStream.newLineAtOffset(25, 700);
int countLines = 0;
// here we iterate the array with all the sentences, and every 25 lines we add a new page
for (String textLine : listText) {
// after 25 lines, we create a new page
if (countLines == 25) {
contentStream.endText();
contentStream.close();
countLines = 0;
contentStream = returnNewPageContent(doc);
}
writeLine(doc, contentStream, textLine);
countLines += 1;
}
contentStream.endText();
contentStream.close();
doc.save("mypdf.pdf");
doc.close();
}
This method writes every line:
private void writeLine(PDDocument doc, PDPageContentStream contentStream, String textLine) throws IOException {
contentStream.showText(newLineText);
contentStream.newLine();
}
This method create a new page:
private PDPageContentStream returnNewPageContent(PDDocument doc) throws IOException {
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
contentStream.setFont(getFont(), FONT_SIZE);
contentStream.setLeading(LEADING);
contentStream.beginText();
contentStream.newLineAtOffset(25, 700);
return contentStream;
}
And Finally, the get font method:
private static PDFont getFont() throws IOException {
return PDType1Font.TIMES_ROMAN;
}
Posted on May 14, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.