Java JEE - Apache PDFBox Series
Creating PDFs from Scratch
Build new documents, add pages, and save to files or byte arrays.
Table of Contents
1. Creating a New Document
Instantiate PDDocument, add PDPage objects, then save.
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage();
doc.addPage(page);
doc.save("output.pdf");
}
2. Page Size and Orientation
Use PDRectangle.A4, LETTER, or custom dimensions. Rotate with page.setRotation(90).
3. Saving to OutputStream
For web APIs, write to ByteArrayOutputStream and return bytes as download responses.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
byte[] pdfBytes = baos.toByteArray();
4. Design Patterns
- Builder class per report type (InvoicePdfBuilder).
- Template method: header/footer hooks shared across documents.
- Separate layout from data for testability.
5. Conclusion
Creating PDFs programmatically is straightforward with PDDocument and PDPage. Next, learn fonts, text layout, and graphics on those pages.
0 Comments