Java JEE - Apache PDFBox Series
Adding Text, Fonts, and Pages
Draw text with PDPageContentStream, embed fonts, and build multi-page documents.
Table of Contents
1. PDPageContentStream Basics
Open a stream in append mode, set font, move text position, show text, close stream.
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
cs.beginText();
cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
cs.newLineAtOffset(50, 700);
cs.showText("Hello PDFBox");
cs.endText();
}
2. Standard and Embedded Fonts
Standard 14 fonts need no embedding. For Unicode, load TTF with PDType0Font.load().
3. Multi-line and Positioning
Use newLineAtOffset and manual Y decrements for line spacing. Consider helper utilities for wrapped paragraphs.
4. Multi-page Documents
Add a new PDPage when content exceeds page bounds. Track cursor Y and paginate in your layout engine.
5. Conclusion
Text rendering requires understanding coordinates (origin bottom-left), font embedding, and closing content streams. Practice with simple layouts before complex reports.
0 Comments