Java JEE - Apache PDFBox Series
Images and Drawing Shapes
Embed images, draw rectangles and lines, and understand the PDF coordinate system.
Table of Contents
1. Embedding Images
Load PNG or JPEG with PDImageXObject.createFromFileByExtension() and draw with drawImage.
PDImageXObject image = PDImageXObject.createFromFileByExtension(file, doc);
cs.drawImage(image, 50, 500, 200, 100);
2. Drawing Shapes
Use addRect, lineTo, stroke, and fill for boxes and separators.
cs.setStrokingColor(Color.BLACK);
cs.addRect(50, 600, 500, 2);
cs.stroke();
3. Coordinate System
PDF user space: origin bottom-left, X right, Y up. Convert from top-left UI coordinates when porting canvas logic.
4. Best Practices
- Compress images before embedding.
- Reuse XObject resources for repeated logos.
- Keep aspect ratio when scaling images.
5. Conclusion
Combining vector shapes and raster images lets you build rich reports and stamps. Scale images to fit page margins and watch file size when embedding high-resolution photos.
0 Comments