Add Rectangle Shapes to PDF in Java

Add a rectangle outline

  1. Create a new PDF Document.
  2. Add a Page to the document.
  3. Create a Graph container and add it to the page.
  4. Create the Rectangle shape and configure its geometry.
  5. Add the Rectangle to the Graph container.
  6. 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:

  • createRectangleFilled for a solid fill with Color.getRed()
  • addDrawingWithGradientFill for a GradientAxialShading fill

Use alpha transparency

createRectangleWithAlphaColorChannel applies translucent colors with Color.fromArgb(...) so overlapping rectangles remain visible.

Control z-order of rectangles

  1. Create a new PDF Document.
  2. Add a Page to the document.
  3. Set the required Page size.
  4. Add the configured Rectangle shapes to the target page with the required z-order.
  5. 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());
    }
}