Add Ellipse Shapes to PDF in Java

Add ellipse outlines

  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 Ellipse shape and configure its geometry.
  5. Add the Ellipse to the Graph container.
  6. Set the shape properties required by the example, including Color and TextFragment.
  7. Save the output PDF Document.
public static void addEllipse(Path outputFile) {
    try (Document document = new Document()) {
        Page page = document.getPages().add();
        Graph graph = new Graph(400.0, 400.0);
        graph.setBorder(new BorderInfo(BorderSide.All, Color.getGreen()));

        Ellipse ellipse1 = new Ellipse(150, 100, 120, 60);
        ellipse1.getGraphInfo().setColor(Color.getGreenYellow());
        ellipse1.setText(new TextFragment("Ellipse"));
        graph.getShapes().addItem(ellipse1);

        page.getParagraphs().add(graph);
        document.save(outputFile.toString());
    }
}

The full example adds two different outline ellipses to the same graph.

Add filled ellipses

createEllipseFilled fills two ellipses with Color.getGreenYellow() and Color.getDarkRed().

Add text inside ellipses

  1. Create a new PDF Document.
  2. Add a Page to the document.
  3. Create a TextFragment and set the required text formatting options.
  4. Create a Graph container and add it to the page.
  5. Create the Ellipse shape and configure its geometry.
  6. Add the Ellipse to the Graph container.
  7. Save the output PDF Document.
public static void addTextInsideEllipse(Path outputFile) {
    try (Document document = new Document()) {
        Page page = document.getPages().add();
        Graph graph = new Graph(400.0, 400.0);
        graph.setBorder(new BorderInfo(BorderSide.All, Color.getGreen()));

        TextFragment textFragment = new TextFragment("Ellipse");
        textFragment.getTextState().setFont(FontRepository.findFont("Helvetica"));
        textFragment.getTextState().setFontSize(24);

        Ellipse ellipse1 = new Ellipse(100, 100, 120, 180);
        ellipse1.getGraphInfo().setFillColor(Color.getGreenYellow());
        ellipse1.setText(textFragment);
        graph.getShapes().addItem(ellipse1);

        page.getParagraphs().add(graph);
        document.save(outputFile.toString());
    }
}