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

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

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

  • Ниво на блока - Сред параграфи и маси, като дете на тяло, HeaderFooter, Коментар, бележка под линия или възел на форма.
  • На ниво ред - сред редове в маса, като дете на възел на маса.
  • Ниво на клетките - между килиите в ред маси, като дете на възел.
  • Inline-ниво - Сред съдържанието вътре, като дете на §.
  • Заседнали в друга структура на документ Tag.

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

В тази версия на 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-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CheckBoxTypeContentControl.class);
// Open the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
StructuredDocumentTag stdCheckBox = new StructuredDocumentTag(doc, SdtType.CHECKBOX, MarkupLevel.INLINE);
builder.insertNode(stdCheckBox);
doc.save(dataDir + "output.doc");

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(RichTextBoxContentControl.class);
// Open the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
StructuredDocumentTag sdtRichText = new StructuredDocumentTag(doc, SdtType.RICH_TEXT, MarkupLevel.BLOCK);
Paragraph para = new Paragraph(doc);
Run run = new Run(doc);
run.setText("Hello World");
run.getFont().setColor(Color.MAGENTA);
para.getRuns().add(run);
sdtRichText.getChildNodes().add(para);
doc.getFirstSection().getBody().appendChild(sdtRichText);
doc.save(dataDir + "output.doc");

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ComboBoxContentControl.class);
// Open the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.COMBO_BOX, MarkupLevel.BLOCK);
sdt.getListItems().add(new SdtListItem("Choose an item", "3"));
sdt.getListItems().add(new SdtListItem("Item 1", "1"));
sdt.getListItems().add(new SdtListItem("Item 2", "2"));
doc.getFirstSection().getBody().appendChild(sdt);
doc.save(dataDir + "output.doc");

Как да актуализирате контрола на съдържанието

Този раздел обяснява как да се актуализират стойностите на SDT или контрол на съдържанието програмично.

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SetCurrentStateOfCheckBox.class);
// Open the document.
Document doc = new Document(dataDir + "CheckBoxTypeContentControl.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
StructuredDocumentTag SdtCheckBox = (StructuredDocumentTag) doc.getChild(NodeType.STRUCTURED_DOCUMENT_TAG, 0, true);
//StructuredDocumentTag.Checked property gets/sets current state of the Checkbox SDT
if (SdtCheckBox.getSdtType() == SdtType.CHECKBOX)
SdtCheckBox.setChecked(true);
doc.save(dataDir + "output.doc");

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ModifyContentControls.class);
// Open the document.
Document doc = new Document(dataDir + "CheckBoxTypeContentControl.docx");
for (Object t : doc.getChildNodes(NodeType.STRUCTURED_DOCUMENT_TAG, true)) {
StructuredDocumentTag std = (StructuredDocumentTag) t;
if (std.getSdtType() == SdtType.PLAIN_TEXT) {
std.removeAllChildren();
Paragraph para = (Paragraph) std.appendChild(new Paragraph(doc));
Run run = new Run(doc, "new text goes here");
para.appendChild(run);
}
if (std.getSdtType() == SdtType.DROP_DOWN_LIST) {
SdtListItem secondItem = std.getListItems().get(2);
std.getListItems().setSelectedValue(secondItem);
}
if (std.getSdtType() == SdtType.PICTURE) {
Shape shape = (Shape) std.getChild(NodeType.SHAPE, 0, true);
if (shape.hasImage()) {
shape.getImageData().setImage(dataDir + "Watermark.png");
}
}
doc.save(dataDir + "output.doc");

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

Можете да свържете контрол на съдържанието с XML данни (custom XML част) в Word документи

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(BindingContentControlwithXML.class);
Document doc = new Document();
CustomXmlPart xmlPart = doc.getCustomXmlParts().add(UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d").toString(), "<root><text>Hello, World!</text></root>");
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PLAIN_TEXT, MarkupLevel.BLOCK);
doc.getFirstSection().getBody().appendChild(sdt);
sdt.getXmlMapping().setMapping(xmlPart, "/root[1]/text[1]", "");
dataDir = dataDir + "BindSDTtoCustomXmlPart_out.doc";
// Save the document to disk.
doc.save(dataDir);

Изчистване на съдържанието на контрол на съдържанието

Можете да изчистите съдържанието на контрол върху съдържанието с показване на държател. Структурирани DocumentTag.clear() метод изчиства съдържанието на този структуриран документ таг и показва placeholder, ако тя е определена. Обаче, Не е възможно да се изчисти съдържанието на контрол върху съдържанието, ако има ревизии. Ако контролът на съдържанието няма място, се добавят пет пространства като в MS Word (с изключение на повтарящите се раздели, повтарящи се раздели елементи, групи, чекови кутии, цитати). Ако контролът на съдържанието е картографиран към потребителски XML, съответният XML възел е изчистен.

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ClearContentsControl.class);
Document doc = new Document(dataDir + "input.docx");
StructuredDocumentTag sdt = (StructuredDocumentTag) doc.getChild(NodeType.STRUCTURED_DOCUMENT_TAG, 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-Java
// The path to the documents directory.
Document doc = new Document(dataDir + "input.docx");
StructuredDocumentTag sdt = (StructuredDocumentTag) doc.getChild(NodeType.STRUCTURED_DOCUMENT_TAG, 0, true);
sdt.setColor(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-Java
Document doc = new Document(dataDir + "input.docx");
StructuredDocumentTag sdt = (StructuredDocumentTag) doc.getChild(NodeType.STRUCTURED_DOCUMENT_TAG, 0, true);
Style style = doc.getStyles().getByStyleIdentifier(StyleIdentifier.QUOTE);
sdt.setStyle(style);
dataDir = dataDir + "SetContentControlStyle_out.docx";
doc.save(dataDir);

Работа с контрол на съдържанието в раздела за повтаряне

Контролът на съдържанието на повтарящия се раздел позволява повтаряне на съдържанието, съдържащо се в него. Използване Aspose.Words, Могат да бъдат създадени структурираните възли на таговете на документа на повтарящия се раздел и повтарящите се типове елементи от раздел и за тази цел, Тип на изброяното на SdtType осигурява repeating_SECION_ITEM член.

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
CustomXmlPart xmlPart = doc.getCustomXmlParts().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.REPEATING_SECTION, MarkupLevel.ROW);
repeatingSectionSdt.getXmlMapping().setMapping(xmlPart, "/books[1]/book", "");
table.appendChild(repeatingSectionSdt);
StructuredDocumentTag repeatingSectionItemSdt =
new StructuredDocumentTag(doc, SdtType.REPEATING_SECTION_ITEM, MarkupLevel.ROW);
repeatingSectionSdt.appendChild(repeatingSectionItemSdt);
Row row = new Row(doc);
repeatingSectionItemSdt.appendChild(row);
StructuredDocumentTag titleSdt =
new StructuredDocumentTag(doc, SdtType.PLAIN_TEXT, MarkupLevel.CELL);
titleSdt.getXmlMapping().setMapping(xmlPart, "/books[1]/book[1]/title[1]", "");
row.appendChild(titleSdt);
StructuredDocumentTag authorSdt =
new StructuredDocumentTag(doc, SdtType.PLAIN_TEXT, MarkupLevel.CELL);
authorSdt.getXmlMapping().setMapping(xmlPart, "/books[1]/book[1]/author[1]", "");
row.appendChild(authorSdt);
doc.save(dataDir + "Document.docx");