How to Add Drawing Shapes in Java

Draw a Circle

Add a CircleAnnotation to draw a filled or bordered ellipse on a page:

try (Document doc = new Document()) {
    Page page = doc.getPages().add();
    CircleAnnotation circle = new CircleAnnotation(page,
        new Rectangle(100, 100, 200, 200));
    circle.setColor(Color.fromRgb(0, 0, 1));
    page.getAnnotations().add(circle);
    doc.save("circle.pdf");
}

The Rectangle constructor takes (x1, y1, x2, y2) in PDF units (points, measured from the bottom-left corner of the page).

Inspect Page Artifacts

Artifacts are non-content decorations such as headers, footers, and watermarks. Iterate over existing artifacts on a page:

try (Document doc = new Document("input.pdf")) {
    Page page = doc.getPages().get(1);
    for (Artifact artifact : page.getArtifacts()) {
        System.out.println(artifact.getArtifactType() + ": " + artifact.getSubtype());
    }
}

Remove a Watermark Artifact

Find artifacts of type “Watermark” and delete them from the page’s artifact collection. Save the document after making the change:

try (Document doc = new Document("watermarked.pdf")) {
    Page page = doc.getPages().get(1);
    // Find and remove watermark artifacts
    for (Artifact artifact : page.getArtifacts()) {
        if ("Watermark".equals(artifact.getArtifactType())) {
            page.getArtifacts().delete(artifact);
            break;
        }
    }
    doc.save("clean.pdf");
}

Page Dimensions

To position shapes correctly, first get the page’s media box dimensions. Standard A4 is 595×842 points; standard US Letter is 612×792 points:

try (Document doc = new Document("input.pdf")) {
    Page page = doc.getPages().get(1);
    double width = page.getMediaBox().getWidth();
    double height = page.getMediaBox().getHeight();
    // Standard A4: width=595, height=842
}

See Also