Check Shape Bounds in PDF Graphs with Python

Check shape bounds in a Graph

When you add shapes to a Graph, you can enable bounds validation to ensure each shape fits within the graph area.

Use BoundsCheckMode to define behavior when a shape is out of range. In this example, THROW_EXCEPTION_IF_DOES_NOT_FIT is used to raise an exception.

Follow the steps below:

  1. Create a new PDF Document.
  2. Add a Page.
  3. Create a Graph and add it to the page.
  4. Create a Rectangle that extends outside graph bounds.
  5. Set bounds checking mode to THROW_EXCEPTION_IF_DOES_NOT_FIT.
  6. Add the rectangle and handle the exception.
  7. Save the document.
import aspose.pdf as ap
import aspose.pdf.drawing as drawing


def check_shape_bounds(outfile: str):
    document = ap.Document()
    page = document.pages.add()

    graph = drawing.Graph(100, 100)
    graph.top = 10
    graph.left = 15
    graph.border = ap.BorderInfo(ap.BorderSide.BOX, 1, ap.Color.black)
    page.paragraphs.add(graph)

    rect = drawing.Rectangle(-1, 0, 50, 50)
    rect.graph_info.fill_color = ap.Color.tomato

    try:
        graph.shapes.update_bounds_check_mode(
            ap.BoundsCheckMode.THROW_EXCEPTION_IF_DOES_NOT_FIT
        )
        graph.shapes.add(rect)
    except Exception as e:
        print(e)

    document.save(outfile)

Notes

  • Use THROW_EXCEPTION_IF_DOES_NOT_FIT when strict layout validation is required.
  • For permissive behavior, choose another BoundsCheckMode option based on your layout needs.