Робота з фігурами
Ця тема обговорює, як працювати программатично з формами за допомогою Aspose.Wordsй
Форми в Aspose.Words представляє об’єкт в шарі малювання, такі як AutoShape, текстова коробка, форма, об’єкт OLE, управління ActiveX або малюнок. Документ Word може містити одну або іншу форму. Види документа представлені Shape клас.
Вставити форму за допомогою конструктора документів
Ви можете вставляти в лінію форму з вказаним типом і розміром і вільно плаваючою формою з вказаним положенням, розміром і типом текстового обгортання в документ, використовуючи вказаний тип і розмір і форму вільного плавлення з вказаним положенням, розміром і типом текстового обгортання в документ, за допомогою документа InsertShape метод. Про нас InsertShape метод дозволяє вставляти DML форму в документ модель. Документ повинен бути збережений у форматі, який підтримує форми DML, інакше такі вершини будуть перетворені на форму VML, при цьому збереження документа.
Приклад коду показує, як вставити ці типи форм у документ:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
//Free-floating shape insertion. | |
Shape shape = builder.insertShape(ShapeType.TEXT_BOX, | |
RelativeHorizontalPosition.PAGE, 100, | |
RelativeVerticalPosition.PAGE, 100, | |
50, 50, | |
WrapType.NONE); | |
shape.setRotation(30.0); | |
builder.writeln(); | |
//Inline shape insertion. | |
shape = builder.insertShape(ShapeType.TEXT_BOX, 50, 50); | |
shape.setRotation(30.0); | |
OoxmlSaveOptions so = new OoxmlSaveOptions(SaveFormat.DOCX); | |
// "Strict" or "Transitional" compliance allows to save shape as DML. | |
so.setCompliance(OoxmlCompliance.ISO_29500_2008_TRANSITIONAL); | |
dataDir = dataDir + "Shape_InsertShapeUsingDocumentBuilder_out.docx"; | |
// Save the document to disk. | |
doc.save(dataDir, so); |
Набір Aspect Ratio Locked
Використання Aspose.Words, Ви можете вказати, чи заблоковано співвідношення форми через AspectRatioLocked майно.
Приклад коду показує, як працювати з AspectRatioLocked майно:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Shape shape = builder.insertImage(dataDir + "Test.png"); | |
shape.setAspectRatioLocked(true); | |
// Save the document to disk. | |
dataDir = dataDir + "Shape_AspectRatioLocked_out.doc"; | |
doc.save(dataDir); |
Set Shape Layout В клітинку
Ви також можете вказати, чи відображається форма всередині таблиці або зовні його за допомогою IsLayoutInCell майно.
Приклад коду показує, як працювати з IsLayoutInCell майно:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "LayoutInCell.docx"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT); | |
watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE); | |
watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE); | |
watermark.isLayoutInCell(false); // Display the shape outside of table cell if it will be placed into a cell. | |
watermark.setWidth(300); | |
watermark.setHeight(70); | |
watermark.setHorizontalAlignment(HorizontalAlignment.CENTER); | |
watermark.setVerticalAlignment(VerticalAlignment.CENTER); | |
watermark.setRotation(-40); | |
watermark.getFill().setColor(Color.GRAY); | |
watermark.setStrokeColor(Color.GRAY); | |
watermark.getTextPath().setText("watermarkText"); | |
watermark.getTextPath().setFontFamily("Arial"); | |
watermark.setName("WaterMark_0"); | |
watermark.setWrapType(WrapType.NONE); | |
Run run = (Run) doc.getChildNodes(NodeType.RUN, true).get(doc.getChildNodes(NodeType.RUN, true).getCount() - 1); | |
builder.moveTo(run); | |
builder.insertNode(watermark); | |
doc.getCompatibilityOptions().optimizeFor(MsWordVersion.WORD_2010); | |
// Save the document to disk. | |
dataDir = dataDir + "Shape_IsLayoutInCell_out.docx"; | |
doc.save(dataDir); |
Додати Corners Snipped
Ви можете створити прямокутний прямокутний прямокутник за допомогою Aspose.Wordsй Типи форми SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped, TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, і DiagonalCornersRounded.
Форма DML створюється за допомогою InsertShape метод з цими типами форми. Ці типи не можуть використовуватися для створення VML-форм. Приєднатися до створення форми за допомогою публічного конструктора класу “Шапе” піднімає виняток “НепідтриманийException”.
Приклад коду показує, як вставити ці форми в документ:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Shape shape = builder.insertShape(ShapeType.TOP_CORNERS_SNIPPED, 50, 50); | |
OoxmlSaveOptions so = new OoxmlSaveOptions(SaveFormat.DOCX); | |
so.setCompliance(OoxmlCompliance.ISO_29500_2008_TRANSITIONAL); | |
dataDir = dataDir + "AddCornersSnipped_out.docx"; | |
//Save the document to disk. | |
doc.save(dataDir, so); |
Отримувати Фактичні точки фігури
Використання Aspose.Words API, Ви можете отримати місце розташування і розмір форми, що містить блок в точках, відносно анкеру верхньої форми. Для цього використовуйте BoundsInPoints майно.
Приклад коду показує, як працювати з BoundsInPoints майно:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Shape shape = builder.insertImage(dataDir + "Test.png"); | |
shape.setAspectRatioLocked(false); | |
System.out.print("\nGets the actual bounds of the shape in points. "); | |
System.out.println(shape.getShapeRenderer().getBoundsInPoints()); |
Вказати Вертикальний Якір
Ви можете вказати текст вертикального вирівнювання у вигляді форми за допомогою VerticalAnchor майно.
Приклад коду показує, як працювати з VerticalAnchor майно:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "VerticalAnchor.docx"); | |
NodeCollection shapes = doc.getChildNodes(NodeType.SHAPE, true); | |
int imageIndex = 0; | |
for (Shape textBoxShape : (Iterable<Shape>) shapes) { | |
if (textBoxShape != null) { | |
textBoxShape.getTextBox().setVerticalAnchor(TextBoxAnchor.BOTTOM); | |
} | |
} | |
doc.save(dataDir + "VerticalAnchor_out.docx"); |
Детект Смарт Арт форма
Aspose.Words також дозволяє виявити, чи має форму SmartArt
об’єкт. Для цього використовуйте HasSmartArt майно.
Приклад коду показує, як працювати з HasSmartArt майно:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "input.docx"); | |
NodeCollection shapes = doc.getChildNodes(NodeType.SHAPE, true); | |
int count = 0; | |
for (Shape textBoxShape : (Iterable<Shape>) shapes) { | |
if (textBoxShape.hasSmartArt()) { | |
count++; | |
} | |
} | |
System.out.println("The document has " + count + " shapes with SmartArt."); |
Горизонтальний формат Rule
Ви можете вставити форму горизонтального правила в документ, використовуючи InsertHorizontalRule метод.
Aspose.Words API Послуги HorizontalRuleFormat властивість доступу до властивостей горизонтальної форми правила. Про нас HorizontalRuleFormat клас визначає основні властивості, такі як Висота, колір, NoShade тощо для форматування горизонтального правила.
Приклад наступного коду показує, як встановити HorizontalRuleFormat:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
DocumentBuilder builder = new DocumentBuilder(); | |
Shape shape = builder.insertHorizontalRule(); | |
HorizontalRuleFormat horizontalRuleFormat = shape.getHorizontalRuleFormat(); | |
horizontalRuleFormat.setAlignment(HorizontalRuleAlignment.CENTER); | |
horizontalRuleFormat.setWidthPercent(70); | |
horizontalRuleFormat.setHeight(3); | |
horizontalRuleFormat.setColor(Color.BLUE); | |
horizontalRuleFormat.setNoShade(true); | |
builder.getDocument().save("HorizontalRuleFormat.docx"); |