Работа с формами

Эта тема обсуждает, как программно работать с формами, используя Aspose.Words.

Формы в Aspose.Words представляют собой объект в слое рисунка, такой как AutoShape, текстовый ящик, свободная форма, объект OLE, управление ActiveX или изображение. Документ Word может содержать одну или несколько различных форм. Формы в Aspose.Words представлены в виде Shape класс.

Вставка форм с помощью конструктора документов

Вы можете вставить встроенную форму с указанным типом и размером и свободно плавающую форму с указанным положением, размером и типом текстовой обертки в документ, используя InsertShape метод. The InsertShape Способ позволяет вставить форму DML в модель документа. Документ должен быть сохранен в формате, который поддерживает формы DML, в противном случае такие узлы будут преобразованы в форму VML, при этом сохраняется документ.

Следующий пример кода показывает, как вставить эти типы фигур в документ:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
//Free-floating shape insertion.
Shape shape = builder.InsertShape(ShapeType.TextBox, RelativeHorizontalPosition.Page, 100, RelativeVerticalPosition.Page, 100, 50, 50, WrapType.None);
shape.Rotation = 30.0;
builder.Writeln();
//Inline shape insertion.
shape = builder.InsertShape(ShapeType.TextBox, 50, 50);
shape.Rotation = 30.0;
OoxmlSaveOptions so = new OoxmlSaveOptions(SaveFormat.Docx);
// "Strict" or "Transitional" compliance allows to save shape as DML.
so.Compliance = OoxmlCompliance.Iso29500_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-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
var shape = builder.InsertImage(dataDir + "Test.png");
shape.AspectRatioLocked = false;
dataDir = dataDir + "Shape_AspectRatioLocked_out.doc";
// Save the document to disk.
doc.Save(dataDir);

Настройка формы Layout in Cell

Вы также можете указать, отображается ли форма внутри стола или снаружи стола. IsLayoutInCell собственность.

Следующий пример показывает, как работать с IsLayoutInCell имущество:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + @"LayoutInCell.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
Shape watermark = new Shape(doc, ShapeType.TextPlainText);
watermark.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
watermark.RelativeVerticalPosition = RelativeVerticalPosition.Page;
watermark.IsLayoutInCell = true; // Display the shape outside of table cell if it will be placed into a cell.
watermark.Width = 300;
watermark.Height = 70;
watermark.HorizontalAlignment = HorizontalAlignment.Center;
watermark.VerticalAlignment = VerticalAlignment.Center;
watermark.Rotation = -40;
watermark.Fill.Color = Color.Gray;
watermark.StrokeColor = Color.Gray;
watermark.TextPath.Text = "watermarkText";
watermark.TextPath.FontFamily = "Arial";
watermark.Name = string.Format("WaterMark_{0}", Guid.NewGuid());
watermark.WrapType = WrapType.None;
Run run = doc.GetChildNodes(NodeType.Run, true)[doc.GetChildNodes(NodeType.Run, true).Count - 1] as Run;
builder.MoveTo(run);
builder.InsertNode(watermark);
doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2010);
dataDir = dataDir + "Shape_IsLayoutInCell_out.docx";
// Save the document to disk.
doc.Save(dataDir);

Создайте прямоугольник Snip Corner

Вы можете создать угловой прямоугольник с помощью Aspose.Words. Типы фигур: *SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped, TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, * и DiagonalCornersRounded.

Форма DML создается с использованием InsertShape Метод с этими типами форм. Эти типы не могут быть использованы для создания форм VML. Попытка создать форму с помощью общественного конструктора класса “Форма” поднимает исключение “Неподдерживаемый Исключение”.

Следующий пример кода показывает, как вставить эти типы фигур в документ:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.InsertShape(ShapeType.TopCornersSnipped, 50, 50);
OoxmlSaveOptions so = new OoxmlSaveOptions(SaveFormat.Docx);
so.Compliance = OoxmlCompliance.Iso29500_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-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
var shape = builder.InsertImage(dataDir + "Test.png");
shape.AspectRatioLocked = false;
Console.Write("\nGets the actual bounds of the shape in points.");
Console.WriteLine(shape.GetShapeRenderer().BoundsInPoints);

Укажите вертикальный якорь

Вы можете указать вертикальное выравнивание текста в форме, используя VerticalAnchor собственность.

Следующий пример показывает, как работать с VerticalAnchor имущество:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + @"VerticalAnchor.docx");
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
Shape textBoxShape = shapes[0] as Shape;
if (textBoxShape != null)
{
textBoxShape.TextBox.VerticalAnchor = TextBoxAnchor.Bottom;
}
doc.Save(dataDir + "VerticalAnchor_out.docx");

Обнаружение Smart Форма искусства

Aspose.Words Также можно определить, имеет ли форма SmartArt объект. Чтобы сделать это, используйте HasSmartArt собственность.

Следующий пример показывает, как работать с HasSmartArt имущество:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "input.docx");
int count = 0;
foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true))
{
if (shape.HasSmartArt)
count++;
}
Console.WriteLine("The document has {0} shapes with SmartArt.", count);

Включить горизонтальный Правило в документе

Вы можете вставить горизонтальную форму правила в документ, используя InsertHorizontalRule метод.

Следующий пример кода показывает, как это сделать:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Insert a horizontal rule shape into the document.");
builder.InsertHorizontalRule();
dataDir = dataDir + "DocumentBuilder.InsertHorizontalRule_out.doc";
doc.Save(dataDir);

Aspose.Words API обеспечивает HorizontalRuleFormat свойство доступа к свойствам горизонтальной формы правила. The HorizontalRuleFormat Класс раскрывает основные свойства, такие как высота, цвет, NoShade и т.д. для форматирования горизонтального правила.

Следующий пример кода показывает, как установить HorizontalRuleFormat:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
DocumentBuilder builder = new DocumentBuilder();
Shape shape = builder.InsertHorizontalRule();
HorizontalRuleFormat horizontalRuleFormat = shape.HorizontalRuleFormat;
horizontalRuleFormat.Alignment = HorizontalRuleAlignment.Center;
horizontalRuleFormat.WidthPercent = 70;
horizontalRuleFormat.Height = 3;
horizontalRuleFormat.Color = Color.Blue;
horizontalRuleFormat.NoShade = true;
builder.Document.Save("HorizontalRuleFormat.docx");

Импорт форм с помощью Math XML в виде форм DOM

Вы можете использовать ConvertShapeToOfficeMath свойство преобразовывать формы с помощью EquationXML в объекты Office Math. По умолчанию стоимость этого имущества соответствует Microsoft Word Формы с уравнением XML не преобразуются в объекты Office.

Следующий пример кода показывает, как конвертировать формы в объекты Office Math:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
LoadOptions lo = new LoadOptions();
lo.ConvertShapeToOfficeMath = true;
// Specify load option to use previous default behaviour i.e. convert math shapes to office math ojects on loading stage.
Document doc = new Document(dataDir + @"OfficeMath.docx", lo);
//Save the document into DOCX
doc.Save(dataDir + "ConvertShapeToOfficeMath_out.docx", SaveFormat.Docx);