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

Тази тема обсъжда как да се работи програмно с форми, използвайки Aspose.Words.

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

Вмъкване на форма чрез създаване на документ

Можете да въведете в линия форма с определен тип и размер и свободно плаваща форма с определено положение, размер и текстова обвивка в документ с помощта на InsertShape метод. На 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);

Задаване на форма в клетка

Можете също така да посочите дали формата се показва в таблица или извън нея с помощта на 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);

Създаване на наклонен ъгъл

Можете да създадете ъглов правоъгълник с помощта на Aspose.Words. Типовете форма са SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped, TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, and DiagonalCornersRounded.

Формата DML е създадена с помощта на InsertShape метод с тези видове форма. Тези видове не могат да бъдат използвани за създаване на VML форми. Опит за създаване на форма чрез използване на обществения конструктор на класа “Shape” повдига изключението “NotSupportedException.”

Следният пример за код показва как да се вкарат тези форми в документа:

// 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");

Открий умно Форма на изкуството

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 собственост за достъп до свойствата на хоризонталното правило. На 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 Имотът да конвертирате формите с уравнениеXML да Office Математически обекти. По подразбиране стойността на този имот съответства на Microsoft Word поведение, т.е. форми с уравнение XML не се преобразуват в офис математически обекти.

Следният пример за код показва как да конвертирате форми в Office Математически обекти:

// 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);