Draw Shapes in PDF in Java

This tutorial will show you how to use Spire. PDF for Java to draw shapes in a PDF document, as well as set shape border colors and fill colors.

Entire Code:

import java.awt.Color;
import java.awt.geom.Rectangle2D;

import com.spire.ms.System.Drawing.PointF;
import com.spire.pdf.graphics.*;

public class DrawShapes {

	public static void main(String[] args) {
		//create a PdfDocument object
        PdfDocument doc = new PdfDocument();
        //add a page
        PdfPageBase page = doc.getPages().add();      
        //draw a rectangle
        PdfPen pen =new PdfPen(new PdfRGBColor(Color.black),0.1);
        Rectangle2D.Float rect1 = new Rectangle2D.Float(0, 20, 120, 50);
        PdfLinearGradientBrush linearGradientBrush = new PdfLinearGradientBrush(rect1,new PdfRGBColor(Color.white),new PdfRGBColor(Color.blue),PdfLinearGradientMode.Horizontal);          
        page.getCanvas().drawRectangle(pen, linearGradientBrush, rect1);
        //draw an ellipse
        PointF centerStart= new PointF(205,45);
        PointF centerEnd= new PointF(205,45);
        PdfRadialGradientBrush radialGradientBrush = new PdfRadialGradientBrush(centerStart,0,centerEnd,25,new PdfRGBColor(Color.pink),new PdfRGBColor(Color.red));
        Rectangle2D.Float rect2= new Rectangle2D.Float(180, 20, 50, 50);
        //draw a polygon
        PointF p1=new PointF(290,70);
        PointF p2=new PointF(310,45);
        PointF p3=new PointF(325,60);
        PointF p4=new PointF(340,20);
        PointF p5=new PointF(370,70);
        PointF[] points = {p1, p2, p3, p4, p5};
        PdfBrush brush= PdfBrushes.getGreenYellow();
        page.getCanvas().drawPolygon(pen,brush, points);
        //draw an arc
        float startAngle = 0;
        float sweepAngle = 270;
        Rectangle2D.Float rect3= new Rectangle2D.Float(0, 110, 50, 50);
        page.getCanvas().drawArc(pen, rect3, startAngle, sweepAngle);
        //draw a pie graph   
        Rectangle2D.Float rect4= new Rectangle2D.Float(70, 110, 50, 50);
        page.getCanvas().drawPie(pen, rect4, startAngle, sweepAngle);
        //draw a line
        PointF pStart=new PointF(205,110);
        PointF pEnd=new PointF(205,160);
        page.getCanvas().drawLine(pen, pStart, pEnd);
        //draw a Bezier curve
        PointF startPoint = new PointF(290, 135);
        PointF firstControlPoint = new PointF(330, 70);
        PointF secondControlPoint = new PointF(330, 200);
        PointF endPoint = new PointF(370, 135);
        page.getCanvas().drawBezier(pen, startPoint, firstControlPoint, secondControlPoint, endPoint);
        //save to file
        doc.saveToFile("DrawShapes.pdf", FileFormat.PDF);       



Draw Shapes in PDF in Java