Работа с контрол на съдържанието SDT

В Microsoft Word, можете да създадете форма, като започнете с шаблон и да добавите контрол на съдържанието, включително чекови кутии, текстови кутии, берачи на дати и падащи списъци. В Aspose.Words структуриран документ Етикет или контрол на съдържанието от всеки документ, зареден в Aspose.Words е внесен като Structured DocumentTag възел. Структурираните тагове на документи (SDT или контрол на съдържанието) позволяват вграждането на семантика, дефинирана от клиента, както и неговото поведение и появяване в документ.

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

  • Ниво на блок по точки и маси, като дете на тяло, HeaderFooter, Коментар, бележка под линия или възел на форма
  • Ниво на гребане сред редове в таблица, като дете на възел на маса
  • Ниво на клетки готварски клетки в таблица ред, като дете на ред възел
  • Inline-level
  • Заседнал в друг структуриран документ Етикет

Вмъкване на контрол на съдържанието в документ

В тази версия на 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);

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

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

Свързване контрол на съдържанието към потребителски XML части

Можете да свържете контрол на съдържанието с XML данни (custom XML част) в 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);

Name

Можете да получите картографиране на този набор от структурирани документи за XML данни в персонализирана XML част от текущия документ, използвайки Структуриран DocumentTagRangeStart.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 метод изчиства съдържанието на този структуриран документ таг и показва placeholder, ако тя е определена. Все пак, Не е възможно да се изчисти съдържанието на контрол върху съдържанието, ако има ревизии. Ако контролът на съдържанието няма място, се поставят пет пространства като в 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. MS Word подчертава фона на контрола на съдържанието, когато мишката се движи над контрол на съдържанието. Това помага за идентифициране на контрола върху съдържанието. Цветът на подчертаването е малко по-мек от Color. Например, MS Word подчертава фона с розов цвят, когато Color е Ред.
  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 имоти. Когато въведете текста в контрол на съдържанието в изходния документ, напечатаният текст ще има стила “Quote.”

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

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