Робота з управління контентом SDT

У Microsoft Word, Ви можете створити форму, починаючи з шаблону і додаючи контроль вмісту, включаючи прапорці, текстові коробки, дати пікселики і випадаючі списки. У Aspose.Words, > Конструктивний тег документа або контроль вмісту з будь-якого документа, завантаженого в Aspose.Words імпортується як СтруктурованийDocumentTag node. Структуровані теги документів (SDT або контроль вмісту) дозволяють вбудовувати індивідуальну семантику, а також її поведінку та зовнішній вигляд у документ.

СтруктурованийДокумент Тег може статися в документі в наступних місцях:

  • Блок-рівень - Серед абзаців і таблиць, як дитина тіла, заголовок, коментар, Футнот або вершина
  • Рів-рівень - Серед рядків у таблиці, як дитина настільного вузла
  • Рівень клітинки - Серед клітинок в рядку столу, як дитина вузла роу
  • Внутрішньорівневе - Внутрішнє наповнення всередині, як дитина Параграфа
  • Випробувано в інший структурований документ Навігація

Вставте контроль вмісту в документ

У цій версії Aspose.Words, можуть бути створені такі типи SDT або управління контентом:

  • Checkbox
  • DropDownList
  • ComboBox
  • Date
  • BuildingBlockGallery
  • Group
  • Picture
  • RichText
  • PlainText

Приклад коду показує, як створити контроль вмісту прапорця типу:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
// Open the empty document
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
StructuredDocumentTag SdtCheckBox = new StructuredDocumentTag(doc, SdtType.Checkbox, MarkupLevel.Inline);
// Insert content control into the document
builder.InsertNode(SdtCheckBox);
dataDir = dataDir + "CheckBoxTypeContentControl_out.docx";
doc.Save(dataDir, SaveFormat.Docx);

Приклад коду показує, як створити контроль вмісту багатого тексту:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
Document doc = new Document();
StructuredDocumentTag sdtRichText = new StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Block);
Paragraph para = new Paragraph(doc);
Run run = new Run(doc);
run.Text = "Hello World";
run.Font.Color = Color.Green;
para.Runs.Add(run);
sdtRichText.ChildNodes.Add(para);
doc.FirstSection.Body.AppendChild(sdtRichText);
dataDir = dataDir + "RichTextBoxContentControl_out.docx";
doc.Save(dataDir);

Приклад наступного коду показує, як створити контроль вмісту коробки типу combo:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
Document doc = new Document();
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.ComboBox, MarkupLevel.Block);
sdt.ListItems.Add(new SdtListItem("Choose an item", "-1"));
sdt.ListItems.Add(new SdtListItem("Item 1", "1"));
sdt.ListItems.Add(new SdtListItem("Item 2", "2"));
doc.FirstSection.Body.AppendChild(sdt);
dataDir = dataDir + "ComboBoxContentControl_out.docx";
doc.Save(dataDir);

Як оновити контроль вмісту

Цей розділ пояснює, як оновити значення програми керування SDT або контентом.

Приклад коду показує, як встановити поточний стан прапорця:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Open an existing document
Document doc = new Document(dataDir + "CheckBoxTypeContentControl.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
// Get the first content control from the document
StructuredDocumentTag SdtCheckBox = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
// StructuredDocumentTag.Checked property gets/sets current state of the Checkbox SDT
if (SdtCheckBox.SdtType == SdtType.Checkbox)
SdtCheckBox.Checked = true;
dataDir = dataDir + "SetCurrentStateOfCheckBox_out.docx";
doc.Save(dataDir);

Наприклад, наступний код показує, як змінити контроль вмісту звичайної текстової коробки типу, випадаючий список та зображення:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Open an existing document
Document doc = new Document(dataDir + "CheckBoxTypeContentControl.docx");
foreach (StructuredDocumentTag sdt in doc.GetChildNodes(NodeType.StructuredDocumentTag, true))
{
if (sdt.SdtType == SdtType.PlainText)
{
sdt.RemoveAllChildren();
Paragraph para = sdt.AppendChild(new Paragraph(doc)) as Paragraph;
Run run = new Run(doc, "new text goes here");
para.AppendChild(run);
}
else if (sdt.SdtType == SdtType.DropDownList)
{
SdtListItem secondItem = sdt.ListItems[2];
sdt.ListItems.SelectedValue = secondItem;
}
else if (sdt.SdtType == SdtType.Picture)
{
Shape shape = (Shape)sdt.GetChild(NodeType.Shape, 0, true);
if (shape.HasImage)
{
shape.ImageData.SetImage(dataDir + "Watermark.png");
}
}
}
dataDir = dataDir + "ModifyContentControls_out.docx";
doc.Save(dataDir);

Binding Content Control для користувальницьких XML частин

Ви можете зв’язатися з даними XML (custom XML part) у документах Word.

Приклад коду показує, як підключити контроль вмісту на користувацьких частинах XML:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(Guid.NewGuid().ToString("B"), "<root><text>Hello, World!</text></root>");
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(sdt);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");
dataDir = dataDir + "BindSDTtoCustomXmlPart_out.doc";
// Save the document to disk.
doc.Save(dataDir);

XMLMapping структурований діапазон тегів документів

Ви можете отримати копію цього структурованого діапазону тегів для XML даних у користувальницькому XML частини поточного документа з використанням поточного документа СтруктураdDocumentTagRangeStart.XmlMapping майной Однак, SetMapping метод може бути використаний для копіювання структурованого діапазону тегів до даних XML.

Приклад наступного коду показує, як встановити XML-картування:

// 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");
StructuredDocumentTagRangeStart sdtRangeStart = (StructuredDocumentTagRangeStart)doc.GetChild(NodeType.StructuredDocumentTagRangeStart, 0, true);
sdtRangeStart.XmlMapping.SetMapping(doc.CustomXmlParts[0], "/Root/Element", null);
doc.Save(dataDir + "output.docx");

Очистити вміст контенту

Ви можете очистити вміст контрольного вмісту з відображенням власника місця. Про нас StructuredDocumentTag.Clear метод очищає вміст цього структурованого тегу документа і відображає статус, якщо він визначений. Однак Неможливо очистити вміст контенту, якщо він має версії. Якщо контент-контроль не має резидента, вставляється п’ять пробілів Microsoft Word (крім повторюваних розділів, елементів, груп, контрольних скриньок, цитування). Якщо керування контентом налаштовується на користувацьку XML, позначений вузол XML.

Приклад коду показує, як очистити вміст контенту:

// 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");
StructuredDocumentTag sdt = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
sdt.Clear();
dataDir = dataDir + "ClearContentsControl_out.doc";
// Save the document to disk.
doc.Save(dataDir);

Зміна вмісту управління фоном та прикордонними кольорами

Про нас StructuredDocumentTag.Color Зручність в об’єкті дозволяє отримати або встановити колір управління контентом. Колір впливає на контроль вмісту в двох ситуаціях:

1,1 км MS Word висвітлює фон управління контентом, коли миша рухається над контролем вмісту. Це допомагає визначити контроль вмісту. Колір висвітлення трохи “м’якше” ніж Colorй Наприклад, MS Word висвітлює фон з рожевим кольором, коли Color червоний. 2,2 км Коли ви взаємодієте (видалення, забір і т.д.) з контролем вмісту, кордон управління контентом кольоровий з Colorй

Приклад коду показує, як змінити колір управління контентом:

// 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");
StructuredDocumentTag sdt = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
sdt.Color = Color.Red;
dataDir = dataDir + "SetContentControlColor_out.docx";
// Save the document to disk.
doc.Save(dataDir);

Як встановити стиль для форматування тексту, що виводиться в контроль вмісту

Якщо ви хочете встановити стиль управління контентом, ви можете використовувати StructuredDocumentTag.Style або StructuredDocumentTag.StyleName властивості. Коли ви набираєте текст у контроль вмісту у вихідному документі, типований текст буде мати стиль “Швидке”.

Приклад коду показує, як встановити стиль управління контентом:

// 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");
StructuredDocumentTag sdt = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
Style style = doc.Styles[StyleIdentifier.Quote];
sdt.Style = style;
dataDir = dataDir + "SetContentControlStyle_out.docx";
// Save the document to disk.
doc.Save(dataDir);

Робота з повторним управлінням контенту

Контроль вмісту повторення дозволяє повторювати вміст, що міститься в ньому. Використання Aspose.Words, структуровані типи тегів документів, що повторюють розділ, можуть бути створені та для цього, Тип обмотки SdtType Послуги RepeatingSectionItem майно.

Приклад наступного коду показує, як зв’язати контроль вмісту повторюваного розділу до таблиці.

// 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);
CustomXmlPart xmlPart = doc.CustomXmlParts.Add("Books",
"<books><book><title>Everyday Italian</title><author>Giada De Laurentiis</author></book>" +
"<book><title>Harry Potter</title><author>J K. Rowling</author></book>" +
"<book><title>Learning XML</title><author>Erik T. Ray</author></book></books>");
Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Title");
builder.InsertCell();
builder.Write("Author");
builder.EndRow();
builder.EndTable();
StructuredDocumentTag repeatingSectionSdt =
new StructuredDocumentTag(doc, SdtType.RepeatingSection, MarkupLevel.Row);
repeatingSectionSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book", "");
table.AppendChild(repeatingSectionSdt);
StructuredDocumentTag repeatingSectionItemSdt =
new StructuredDocumentTag(doc, SdtType.RepeatingSectionItem, MarkupLevel.Row);
repeatingSectionSdt.AppendChild(repeatingSectionItemSdt);
Row row = new Row(doc);
repeatingSectionItemSdt.AppendChild(row);
StructuredDocumentTag titleSdt =
new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell);
titleSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/title[1]", "");
row.AppendChild(titleSdt);
StructuredDocumentTag authorSdt =
new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell);
authorSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/author[1]", "");
row.AppendChild(authorSdt);
doc.Save(dataDir + "Document.docx");