How to Add Drawing Shapes in Java

How to Add Drawing Shapes in Java

This guide shows how to draw geometric shapes and work with page artifact decorations in Aspose.PDF FOSS for Java. You will learn to add a CircleAnnotation to draw an ellipse, inspect watermark and header artifacts, and remove artifact objects.

Draw a Circle

Add a CircleAnnotation to draw a filled or bordered ellipse on a page. The setColor() method sets the annotation fill color. Add the annotation to the page’s annotation collection and save the document:

try (Document doc = new Document()) {
    PageCollection pages = doc.getPages();
    Page page = pages.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 to inspect their type and subtype:

try (Document doc = new Document("input.pdf")) {
    PageCollection pages = doc.getPages();
    Page page = pages.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")) {
    PageCollection pages = doc.getPages();
    Page page = pages.get(1);
    for (Artifact artifact : page.getArtifacts()) {
        if ("Watermark".equals(artifact.getArtifactType())) {
            page.getArtifacts().delete(artifact);
            break;
        }
    }
    doc.save("clean.pdf");
}

Get 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")) {
    PageCollection pages = doc.getPages();
    Page page = pages.get(1);
    double width = page.getMediaBox().getWidth();
    double height = page.getMediaBox().getHeight();
    System.out.println("Page: " + width + " x " + height + " pt");
}

See Also

 English