本篇文档将介绍通过Java编程在PDF文档中绘制图形的方法。包括绘制矩形、椭圆形、不规则多边形、线条、弧线、曲线、扇形等等。针对方法中提供的思路,也可以自行变换图形设计思路,如菱形、梯形或者组合图形等。
使用工具:Free Spire.PDF for Java(免费版)
Jar文件导入:
步骤1:将安装包中lib文件夹下的两个文件复制到程序中新建的文件夹中(这里在程序中可新建一个文件夹并命名为Lib)
步骤2:复制文件后,将两个添加引用到程序:选中这两个jar文件,点击鼠标右键,选择“Build Path” – “Add to Build Path”。完成引用。
Java代码示例(供参考)
import java.awt.Color; import java.awt.Point; import java.awt.geom.Rectangle2D; import com.spire.pdf.FileFormat; import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.graphics.*; public class DrawShapes { public static void main(String[] args) { //创建PdfDocument对象 PdfDocument doc = new PdfDocument(); //添加一页 PdfPageBase page = doc.getPages().add(); //创建画笔、画刷 PdfPen pen =new PdfPen(new PdfRGBColor(Color.black),0.3); PdfBrush brush= PdfBrushes.getGreenYellow(); //绘制矩形 Rectangle2D.Float rect1 = new Rectangle2D.Float(0, 20, 120, 50);//创建Rectangle2D对象,并指定图形在PDF页面中的大小、位置 PdfLinearGradientBrush linearGradientBrush = new PdfLinearGradientBrush(rect1,new PdfRGBColor(Color.PINK),new PdfRGBColor(Color.YELLOW),PdfLinearGradientMode.Horizontal);//填充图形颜色 page.getCanvas().drawRectangle(linearGradientBrush, rect1);//绘制矩形到页面 //绘制椭圆 Point centerStart= new Point(205,45); Point centerEnd= new Point(205,45); PdfRadialGradientBrush radialGradientBrush = new PdfRadialGradientBrush(centerStart,0,centerEnd,60,new PdfRGBColor(Color.white),new PdfRGBColor(Color.cyan)); Rectangle2D.Float rect2= new Rectangle2D.Float(180, 20, 50, 50); page.getCanvas().drawEllipse(radialGradientBrush,rect2); //绘制多边形 Point p1=new Point(290,70); Point p2=new Point(310,45); Point p3=new Point(325,60); Point p4=new Point(340,20); Point p5=new Point(370,70); Point[] points = {p1, p2, p3, p4, p5}; 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); //绘制直线 Point pStart=new Point(205,110); Point pEnd=new Point(205,160); page.getCanvas().drawLine(pen, pStart, pEnd); //绘制贝塞尔曲线 Point startPoint = new Point(290, 135); Point firstControlPoint = new Point(330, 70); Point secondControlPoint = new Point(330, 200); Point endPoint = new Point(370, 135); page.getCanvas().drawBezier(pen, startPoint, firstControlPoint, secondControlPoint, endPoint); //保存文档 doc.saveToFile("DrawShapes.pdf",FileFormat.PDF); } }
完成代码后,运行程序,生成文档。(如下图)
(本文完)
转载请注明出处!!