Add Rectangle Shapes to PDF in Java
Contents
[
Hide
]
Add a rectangle outline
- Create a new PDF Document.
- Add a Page to the document.
- Create a Graph container and add it to the page.
- Create the Rectangle shape and configure its geometry.
- Add the Rectangle to the Graph container.
- Save the output PDF Document.
public static void addRectangle(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
Graph graph = new Graph(400.0, 300.0);
page.getParagraphs().add(graph);
graph.setBorder(new BorderInfo(BorderSide.All, Color.getRed()));
Rectangle rectangle = new Rectangle(20, 20, 350, 250);
graph.getShapes().addItem(rectangle);
document.save(outputFile.toString());
}
}
Fill a rectangle with solid or gradient color
The rectangle examples include:
createRectangleFilledfor a solid fill withColor.getRed()addDrawingWithGradientFillfor aGradientAxialShadingfill
Use alpha transparency
createRectangleWithAlphaColorChannel applies translucent colors with Color.fromArgb(...) so overlapping rectangles remain visible.
Control z-order of rectangles
- Create a new PDF Document.
- Add a Page to the document.
- Set the required Page size.
- Add the configured Rectangle shapes to the target page with the required z-order.
- Save the output PDF Document.
public static void controlZOrderOfRectangle(Path outputFile) {
try (Document document = new Document()) {
Page page = document.getPages().add();
page.setPageSize(375, 300);
page.getPageInfo().getMargin().setLeft(0);
page.getPageInfo().getMargin().setTop(0);
addRectangleToPage(page, 50, 40, 60, 40, Color.getRed(), 2);
addRectangleToPage(page, 20, 20, 30, 30, Color.getBlue(), 1);
addRectangleToPage(page, 40, 40, 60, 30, Color.getGreen(), 0);
document.save(outputFile.toString());
}
}