形状是包括箭头,直线,曲线,圆形,矩形,椭圆形等的图形对象。它使Word文档生动,美观。 借助Spire.Doc,我们可以轻松创建和处理DOCX格式文档中的预定义形状。
我们可以设置形状的格式以使其更美观,例如线条颜色,填充颜色,设置形状的位置等。在这里,我们将介绍如何在Word文档中创建矩形和椭圆形形状并为其设置格式选项。
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.*;
import com.spire.doc.fields.ShapeObject;
import java.awt.*;
public class AddingShapes {
public static void main(String[] args) throws Exception {
//create a Word document.
Document doc = new Document();
//add a section and a paragraph
Section sec = doc.addSection();
Paragraph para = sec.addParagraph();
//insert a rectangle and format shape
ShapeObject rectangle = para.appendShape(130, 80, ShapeType.Rectangle);
rectangle.setFillColor(Color.cyan);
rectangle.setStrokeColor(Color.CYAN);
rectangle.setVerticalPosition(50);
//insert a ellipse
ShapeObject circle = para.appendShape(200,80, ShapeType.Ellipse);
circle.setFillColor(Color.blue);
circle.setStrokeWeight(5);
circle.setStrokeColor(Color.GRAY);
circle.setVerticalPosition(50);
circle.setHorizontalPosition((float)(200 + 160/Math.sqrt(3)));
//save to file
doc.saveToFile("output/InsertShapes.docx", FileFormat.Docx);
}
}
旋转形状:我们可以旋转形状,也可以对其应用翻转(水平和垂直)。 以下代码示例说明了如何在Java应用程序中旋转Word文档中的形状。
import com.spire.doc.Document;
import com.spire.doc.DocumentObject;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.*;
import com.spire.doc.fields.ShapeObject;
public class RotateShapes {
public static void main(String[] args) throws Exception {
//Load the Sample Word document.
Document doc = new Document();
doc.loadFromFile("InsertShapes.docx");
//Get the first section
Section sec = doc.getSections().get(0);
//Traverse every paragraphs and get the shapes and rotate them
for ( Paragraph para: (Iterable<Paragraph>) sec.getParagraphs()) {
for (DocumentObject obj : (Iterable<DocumentObject>) para.getChildObjects()) {
if (obj instanceof ShapeObject) {
((ShapeObject) obj).setRotation(20);
}
}
}
//save to file
doc.saveToFile("output/RotateShape.docx", FileFormat.Docx);
}
}
使用Spire.Doc for Java,我们还可以对形状进行分组并从Word文档中删除形状。 希望能有所帮助。