Работа с формами
В этом разделе обсуждается, как программно работать с фигурами, используя 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); |
Установите фиксированное соотношение сторон
Используя 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); |
Установите Расположение Фигуры В Ячейке
Вы также можете указать, будет ли фигура отображаться внутри таблицы или за ее пределами, используя свойство 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); |
Добавьте обрезанные углы
Вы можете создать прямоугольник с отрезанным углом, используя Aspose.Words. Типы фигур - SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped, TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, и DiagonalCornersRounded.
Фигура DML создается с помощью метода InsertShape с использованием этих типов фигур. Эти типы не могут быть использованы для создания фигур VML. Попытка создать фигуру с помощью открытого конструктора класса “Shape” приводит к возникновению исключения “NotSupportedException”.
В следующем примере кода показано, как вставить фигуры такого типа в документ:
// 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"); |
Определить форму SmartArt
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."); |
Формат горизонтального правила
Вы можете вставить горизонтальную линейчатую фигуру в документ, используя метод 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"); |