Работа с формами
В этом разделе обсуждается, как программно работать с фигурами, используя 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-C | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(); | |
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc); | |
//Free-floating shape insertion. | |
System::SharedPtr<Shape> shape = builder->InsertShape(ShapeType::TextBox, RelativeHorizontalPosition::Page, 100, RelativeVerticalPosition::Page, 100, 50, 50, WrapType::None); | |
shape->set_Rotation(30.0); | |
builder->Writeln(); | |
//Inline shape insertion. | |
shape = builder->InsertShape(ShapeType::TextBox, 50, 50); | |
shape->set_Rotation(30.0); | |
System::SharedPtr<OoxmlSaveOptions> so = System::MakeObject<OoxmlSaveOptions>(SaveFormat::Docx); | |
// "Strict" or "Transitional" compliance allows to save shape as DML. | |
so->set_Compliance(OoxmlCompliance::Iso29500_2008_Transitional); | |
System::String outputPath = outputDataDir + u"WorkingWithShapes.InsertShapeUsingDocumentBuilder.docx"; | |
// Save the document to disk. | |
doc->Save(outputPath, so); |
Установите фиксированное соотношение сторон
Используя Aspose.Words, вы можете указать, будет ли зафиксировано соотношение сторон фигуры с помощью свойства AspectRatioLocked.
В следующем примере кода показано, как работать со свойством AspectRatioLocked:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(); | |
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc); | |
System::SharedPtr<Shape> shape = builder->InsertImage(inputDataDir + u"Test.png"); | |
shape->set_AspectRatioLocked(false); | |
System::String outputPath = outputDataDir + u"WorkingWithShapes.SetAspectRatioLocked.doc"; | |
// Save the document to disk. | |
doc->Save(outputPath); |
Установите Расположение Фигуры В Ячейке
Вы также можете указать, будет ли фигура отображаться внутри таблицы или за ее пределами, используя свойство IsLayoutInCell.
В следующем примере кода показано, как работать со свойством IsLayoutInCell:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"LayoutInCell.docx"); | |
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc); | |
System::SharedPtr<Shape> watermark = System::MakeObject<Shape>(doc, ShapeType::TextPlainText); | |
watermark->set_RelativeHorizontalPosition(RelativeHorizontalPosition::Page); | |
watermark->set_RelativeVerticalPosition(RelativeVerticalPosition::Page); | |
watermark->set_IsLayoutInCell(true); | |
// Display the shape outside of table cell if it will be placed into a cell. | |
watermark->set_Width(300); | |
watermark->set_Height(70); | |
watermark->set_HorizontalAlignment(HorizontalAlignment::Center); | |
watermark->set_VerticalAlignment(VerticalAlignment::Center); | |
watermark->set_Rotation(-40); | |
watermark->get_Fill()->set_Color(System::Drawing::Color::get_Gray()); | |
watermark->set_StrokeColor(System::Drawing::Color::get_Gray()); | |
watermark->get_TextPath()->set_Text(u"watermarkText"); | |
watermark->get_TextPath()->set_FontFamily(u"Arial"); | |
watermark->set_Name(System::String::Format(u"WaterMark_{0}",System::Guid::NewGuid())); | |
watermark->set_WrapType(WrapType::None); | |
System::SharedPtr<Run> run = System::DynamicCast_noexcept<Run>(doc->GetChildNodes(NodeType::Run, true)->idx_get(doc->GetChildNodes(NodeType::Run, true)->get_Count() - 1)); | |
builder->MoveTo(run); | |
builder->InsertNode(watermark); | |
doc->get_CompatibilityOptions()->OptimizeFor(MsWordVersion::Word2010); | |
System::String outputPath = outputDataDir + u"WorkingWithShapes.SetShapeLayoutInCell.docx"; | |
// Save the document to disk. | |
doc->Save(outputPath); |
Создайте прямоугольник с отрезанным углом
Вы можете создать прямоугольник с отрезанным углом, используя 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-C | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(); | |
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc); | |
System::SharedPtr<Shape> shape = builder->InsertShape(ShapeType::TopCornersSnipped, 50, 50); | |
System::SharedPtr<OoxmlSaveOptions> so = System::MakeObject<OoxmlSaveOptions>(SaveFormat::Docx); | |
so->set_Compliance(OoxmlCompliance::Iso29500_2008_Transitional); | |
System::String outputPath = outputDataDir + u"WorkingWithShapes.AddCornersSnipped.docx"; | |
//Save the document to disk. | |
doc->Save(outputPath, so); |
Получите реальные точки границ формы
Используя Aspose.Words API, вы можете получить местоположение и размер фигуры, содержащей блок, в точках относительно привязки самой верхней фигуры. Для этого используйте свойство BoundsInPoints.
В следующем примере кода показано, как работать со свойством BoundsInPoints:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(); | |
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc); | |
System::SharedPtr<Shape> shape = builder->InsertImage(inputDataDir + u"Test.png"); | |
shape->set_AspectRatioLocked(false); | |
std::cout << "Gets the actual bounds of the shape in points." << shape->GetShapeRenderer()->get_BoundsInPoints().ToString().ToUtf8String() << std::endl; |
Формат горизонтального правила
Aspose.Words API предоставляет свойство HorizontalRuleFormat для доступа к свойствам формы горизонтального правила. Класс HorizontalRuleFormat предоставляет базовые свойства, такие как высота, цвет, оттенок и т.д. для форматирования горизонтального правила.
В следующем примере кода показано, как установить HorizontalRuleFormat:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
auto doc = MakeObject<Document>(); | |
auto builder = MakeObject<DocumentBuilder>(doc); | |
builder->Writeln(u"Insert a horizontal rule shape into the document."); | |
builder->InsertHorizontalRule(); | |
doc->Save(ArtifactsDir + u"AddContentUsingDocumentBuilder.InsertHorizontalRule.docx"); |
Вставить OLE-объект в виде значка
Aspose.Words API предоставляет функцию Shape → InsertOleObjectAsIcon для вставки встроенного или связанного OLE-объекта в виде значка в документ. Эта функция позволяет указать файл значка и заголовок. Тип объекта OLE
определяется с помощью расширения файла.
В следующем примере кода показано, как настроить вставку OLE-объекта в качестве значка в документ:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(); | |
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc); | |
System::SharedPtr<Shape> shape = builder->InsertOleObjectAsIcon(inputDataDir + u"embedded.xlsx", false, inputDataDir + u"icon.ico", u"My embedded file"); | |
doc->Save(outputDataDir + u"WorkingWithShapes.InsertOLEObjectAsIcon.docx"); | |
std::cout << "The document has been saved with OLE Object as an Icon." << std::endl; |