Check Shape Bounds in PDF Graphs with Java

Use BoundsCheckMode when you need to ensure that shapes fit inside a graph container.

Validate graph shape bounds

  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. Enable strict bounds checking and try to add the shape to the graph collection with BoundsCheckMode.
  6. Handle the exception if the shape does not fit.
  7. Save the output PDF Document.
public static void checkShapeBounds(Path outputFile) {
    try (Document document = new Document()) {
        Page page = document.getPages().add();
        Graph graph = new Graph(100.0, 100.0);
        graph.setTop(10);
        graph.setLeft(15);
        graph.setBorder(new BorderInfo(BorderSide.Box, 1, Color.getBlack()));
        page.getParagraphs().add(graph);

        Rectangle rectangle = new Rectangle(-1, 0, 50, 50);
        rectangle.getGraphInfo().setFillColor(Color.getTomato());
        try {
            graph.getShapes().updateBoundsCheckMode(BoundsCheckMode.ThrowExceptionIfDoesNotFit);
            graph.getShapes().addItem(rectangle);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

        document.save(outputFile.toString());
    }
}