本教程将展示如何使用Spire.PDF for Java在PDF文档中绘制形状,以及设置形状边线颜色和填充色。
import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;
public class extraction {
public static void main(String[] args) throws Exception {
//创建PdfDocument对象
PdfDocument doc = new PdfDocument();
//添加一页
PdfPageBase page = doc.getPages().add();
//绘制矩形
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);
//绘制椭圆
Point2D centerStart= new Point2D.Float(205,45);
Point2D centerEnd= new Point2D.Float(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);
page.getCanvas().drawEllipse(pen,radialGradientBrush,rect2);
//绘制多边形
Point2D p1=new Point2D.Float(290,70);
Point2D p2=new Point2D.Float(310,45);
Point2D p3=new Point2D.Float(325,60);
Point2D p4=new Point2D.Float(340,20);
Point2D p5=new Point2D.Float(370,70);
Point2D[] points = {p1, p2, p3, p4, p5};
PdfBrush brush= PdfBrushes.getGreenYellow();
page.getCanvas().drawPolygon(pen,brush, points);
//绘制弧形
float startAngle = 0;
float sweepAngle = 270;
Rectangle2D.Float rect3= new Rectangle2D.Float(0, 110, 50, 50);
page.getCanvas().drawArc(pen, rect3, startAngle, sweepAngle);
//绘制扇形
Rectangle2D.Float rect4= new Rectangle2D.Float(70, 110, 50, 50);
page.getCanvas().drawPie(pen, rect4, startAngle, sweepAngle);
//绘制直线
Point2D pStart=new Point2D.Float(205,110);
Point2D pEnd=new Point2D.Float(205,160);
page.getCanvas().drawLine(pen, pStart, pEnd);
//绘制贝塞尔曲线
Point2D startPoint = new Point2D.Float(290, 135);
Point2D firstControlPoint = new Point2D.Float(330, 70);
Point2D secondControlPoint = new Point2D.Float(330, 200);
Point2D endPoint = new Point2D.Float(370, 135);
page.getCanvas().drawBezier(pen, startPoint, firstControlPoint, secondControlPoint, endPoint);
//保存文档
doc.saveToFile("DrawShapes.pdf", FileFormat.PDF);
}
}