public static void Run()
        {
            // ExStart:ComboBoxContentControl
            // 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);
            // ExEnd:ComboBoxContentControl
            Console.WriteLine("\nCombo box type content control created successfully.\nFile saved at " + dataDir);
        }        
        public static void Run()
        {
            // ExStart:CheckBoxTypeContentControl
            // 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);
            // ExEnd:CheckBoxTypeContentControl
            Console.WriteLine("\nCheckBox type content control created successfully.\nFile saved at " + dataDir);
        }        
        public void CheckBox()
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
            
            StructuredDocumentTag sdtCheckBox = new StructuredDocumentTag(doc, SdtType.Checkbox, MarkupLevel.Inline);
            sdtCheckBox.Checked = true;

            //Insert content control into the document
            builder.InsertNode(sdtCheckBox);

            MemoryStream dstStream = new MemoryStream();
            doc.Save(dstStream, SaveFormat.Docx);

            NodeCollection sdts = doc.GetChildNodes(NodeType.StructuredDocumentTag, true);
            
            StructuredDocumentTag sdt = (StructuredDocumentTag)sdts[0];
            Assert.AreEqual(true, sdt.Checked);
        }
        public static void Run()
        {
            // ExStart:RichTextBoxContentControl
            // 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);
            // ExEnd:RichTextBoxContentControl
            Console.WriteLine("\nRich text box type content control created successfully.\nFile saved at " + dataDir);
        }        
        public void XmlMapping()
        {
            //ExStart
            //ExFor:XmlMapping
            //ExFor:XmlMapping.CustomXmlPart
            //ExFor:XmlMapping.Delete
            //ExFor:XmlMapping.IsMapped
            //ExFor:XmlMapping.PrefixMappings
            //ExFor:XmlMapping.XPath
            //ExSummary:Shows how to set XML mappings for CustomXmlParts.
            Document doc = new Document();

            // Construct an XML part that contains data and add it to the document's CustomXmlPart collection
            string        xmlPartId      = Guid.NewGuid().ToString("B");
            string        xmlPartContent = "<root><text>Text element #1</text><text>Text element #2</text></root>";
            CustomXmlPart xmlPart        = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

            Console.WriteLine(Encoding.UTF8.GetString(xmlPart.Data));

            // Create a StructuredDocumentTag that will display the contents of our CustomXmlPart in the document
            StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);

            // If we set a mapping for our StructuredDocumentTag,
            // it will only display a part of the CustomXmlPart that the XPath points to
            // This XPath will point to the contents second "<text>" element of the first "<root>" element of our CustomXmlPart
            sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[2]", "xmlns:ns='http://www.w3.org/2001/XMLSchema'");

            Assert.True(sdt.XmlMapping.IsMapped);
            Assert.AreEqual(xmlPart, sdt.XmlMapping.CustomXmlPart);
            Assert.AreEqual("/root[1]/text[2]", sdt.XmlMapping.XPath);
            Assert.AreEqual("xmlns:ns='http://www.w3.org/2001/XMLSchema'", sdt.XmlMapping.PrefixMappings);

            // Add the StructuredDocumentTag to the document to display the content from our CustomXmlPart
            doc.FirstSection.Body.AppendChild(sdt);
            doc.Save(ArtifactsDir + "SDT.XmlMapping.docx");
            //ExEnd
        }
예제 #6
0
        public void AccessToBuildingBlockPropertiesFromBuildingBlockGallerySdtType()
        {
            Document doc = new Document();

            StructuredDocumentTag buildingBlockSdt =
                new StructuredDocumentTag(doc, SdtType.BuildingBlockGallery, MarkupLevel.Block)
            {
                BuildingBlockCategory = "Built-in",
                BuildingBlockGallery  = "Table of Contents"
            };

            doc.FirstSection.Body.AppendChild(buildingBlockSdt);

            MemoryStream dstStream = new MemoryStream();

            doc.Save(dstStream, SaveFormat.Docx);

            buildingBlockSdt =
                (StructuredDocumentTag)doc.FirstSection.Body.GetChild(NodeType.StructuredDocumentTag, 0, true);

            Assert.AreEqual(SdtType.BuildingBlockGallery, buildingBlockSdt.SdtType);
            Assert.AreEqual("Table of Contents", buildingBlockSdt.BuildingBlockGallery);
            Assert.AreEqual("Built-in", buildingBlockSdt.BuildingBlockCategory);
        }
예제 #7
0
        public void IsTemporary()
        {
            //ExStart
            //ExFor:StructuredDocumentTag.IsTemporary
            //ExSummary:Demonstrates the effects of making a StructuredDocumentTag temporary.
            Document doc = new Document();

            // Insert a plain text StructuredDocumentTag, which will prompt the user to enter text
            // and allow them to edit it like a text box
            StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

            // If we set its Temporary attribute to true, as soon as we start typing,
            // the tag will disappear, and its contents will be assimilated into the parent Paragraph
            tag.IsTemporary = true;

            // Insert the StructuredDocumentTag with a DocumentBuilder
            DocumentBuilder builder = new DocumentBuilder(doc);

            builder.Write("Temporary text box: ");
            builder.InsertNode(tag);

            // A StructuredDocumentTag in the form of a check box will let the user a square to check and uncheck
            // Setting it to temporary will freeze its value after the first time it is clicked
            tag             = new StructuredDocumentTag(doc, SdtType.Checkbox, MarkupLevel.Inline);
            tag.IsTemporary = true;

            builder.Write("\nTemporary checkbox: ");
            builder.InsertNode(tag);

            doc.Save(ArtifactsDir + "StructuredDocumentTag.IsTemporary.docx");
            //ExEnd

            doc = new Document(ArtifactsDir + "StructuredDocumentTag.IsTemporary.docx");

            Assert.AreEqual(2, doc.GetChildNodes(NodeType.StructuredDocumentTag, true).Count(sdt => ((StructuredDocumentTag)sdt).IsTemporary));
        }
예제 #8
0
        public void CreatingCustomXml()
        {
            //ExStart
            //ExFor:CustomXmlPart
            //ExFor:CustomXmlPartCollection.Add(String, String)
            //ExFor:Document.CustomXmlParts
            //ExFor:XmlMapping.SetMapping(CustomXmlPart, String, String)
            //ExSummary:Shows how to create structured document tag with a custom XML data.
            Document doc = new Document();
            // Add test XML data part to the collection.
            CustomXmlPart xmlPart =
                doc.CustomXmlParts.Add(Guid.NewGuid().ToString("B"), "<root><text>Hello, World!</text></root>");

            StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);

            sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

            doc.FirstSection.Body.AppendChild(sdt);

            doc.Save(MyDir + @"\Artifacts\SDT.CustomXml.docx");
            //ExEnd
            Assert.IsTrue(DocumentHelper.CompareDocs(MyDir + @"\Artifacts\SDT.CustomXml.docx",
                                                     MyDir + @"\Golds\SDT.CustomXml Gold.docx"));
        }
 public override VisitorAction VisitStructuredDocumentTagEnd(StructuredDocumentTag sdt)
 {
     SplitComposite(sdt);
     return(VisitorAction.Continue);
 }
 public override VisitorAction VisitStructuredDocumentTagStart(StructuredDocumentTag sdt)
 {
     return(ContinueIfCompositeAcrossPageElseSkip(sdt));
 }
예제 #11
0
        public void FillTableUsingRepeatingSectionItem()
        {
            //ExStart
            //ExFor:SdtType
            //ExSummary:Shows how to fill the table with data contained in the XML part.
            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>");
             
            // Create headers for data from xml content
            Table table = builder.StartTable();

            builder.InsertCell();
            builder.Write("Title");
            builder.InsertCell();
            builder.Write("Author");
            builder.EndRow();
            builder.EndTable();
             
            // Create table with RepeatingSection inside
            StructuredDocumentTag repeatingSectionSdt =
                new StructuredDocumentTag(doc, SdtType.RepeatingSection, MarkupLevel.Row);

            repeatingSectionSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book", string.Empty);
            table.AppendChild(repeatingSectionSdt);
             
            // Add RepeatingSectionItem inside RepeatingSection and mark it as a row
            StructuredDocumentTag repeatingSectionItemSdt =
                new StructuredDocumentTag(doc, SdtType.RepeatingSectionItem, MarkupLevel.Row);

            repeatingSectionSdt.AppendChild(repeatingSectionItemSdt);
             
            Row row = new Row(doc);

            repeatingSectionItemSdt.AppendChild(row);
             
            // Map xml data with created table cells for book title and author
            StructuredDocumentTag titleSdt =
                new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell);

            titleSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/title[1]", string.Empty);
            row.AppendChild(titleSdt);
             
            StructuredDocumentTag authorSdt =
                new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell);

            authorSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/author[1]", string.Empty);
            row.AppendChild(authorSdt);
             
            doc.Save(ArtifactsDir + "StructuredDocumentTag.RepeatingSectionItem.docx");

            //ExEnd

            doc = new Document(ArtifactsDir + "StructuredDocumentTag.RepeatingSectionItem.docx");
            List <StructuredDocumentTag> tags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true).OfType <StructuredDocumentTag>().ToList();

            Assert.AreEqual("/books[1]/book", tags[0].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[0].XmlMapping.PrefixMappings);

            Assert.AreEqual(string.Empty, tags[1].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[1].XmlMapping.PrefixMappings);

            Assert.AreEqual("/books[1]/book[1]/title[1]", tags[2].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[2].XmlMapping.PrefixMappings);

            Assert.AreEqual("/books[1]/book[1]/author[1]", tags[3].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[3].XmlMapping.PrefixMappings);

            Assert.AreEqual("Title\u0007Author\u0007\u0007" +
                            "Everyday Italian\u0007Giada De Laurentiis\u0007\u0007" +
                            "Harry Potter\u0007J. K. Rowling\u0007\u0007" +
                            "Learning XML\u0007Erik T. Ray\u0007\u0007", doc.GetChild(NodeType.Table, 0, true).GetText().Trim());
        }
예제 #12
0
        public void CreatingCustomXml()
        {
            //ExStart
            //ExFor:CustomXmlPart
            //ExFor:CustomXmlPart.Clone
            //ExFor:CustomXmlPart.Data
            //ExFor:CustomXmlPart.Id
            //ExFor:CustomXmlPart.Schemas
            //ExFor:CustomXmlPartCollection
            //ExFor:CustomXmlPartCollection.Add(CustomXmlPart)
            //ExFor:CustomXmlPartCollection.Add(String, String)
            //ExFor:CustomXmlPartCollection.Clear
            //ExFor:CustomXmlPartCollection.Clone
            //ExFor:CustomXmlPartCollection.Count
            //ExFor:CustomXmlPartCollection.GetById(String)
            //ExFor:CustomXmlPartCollection.GetEnumerator
            //ExFor:CustomXmlPartCollection.Item(Int32)
            //ExFor:CustomXmlPartCollection.RemoveAt(Int32)
            //ExFor:Document.CustomXmlParts
            //ExFor:StructuredDocumentTag.XmlMapping
            //ExFor:XmlMapping.SetMapping(CustomXmlPart, String, String)
            //ExSummary:Shows how to create structured document tag with a custom XML data.
            Document doc = new Document();

            // Construct an XML part that contains data and add it to the document's collection
            // Once the "Developer" tab in Microsoft Word is enabled,
            // we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
            string        xmlPartId      = Guid.NewGuid().ToString("B");
            string        xmlPartContent = "<root><text>Hello world!</text></root>";
            CustomXmlPart xmlPart        = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

            // The data we entered is stored in these attributes
            Assert.AreEqual(Encoding.ASCII.GetBytes(xmlPartContent), xmlPart.Data);
            Assert.AreEqual(xmlPartId, xmlPart.Id);

            // XML parts can be referenced by collection index or GUID
            Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
            Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

            // Once the part is created, we can add XML schema associations like this
            xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

            // We can also clone parts and insert them into the collection directly
            CustomXmlPart xmlPartClone = xmlPart.Clone();

            xmlPartClone.Id = Guid.NewGuid().ToString("B");
            doc.CustomXmlParts.Add(xmlPartClone);

            Assert.AreEqual(2, doc.CustomXmlParts.Count);

            // Iterate through collection with an enumerator and print the contents of each part
            using (IEnumerator <CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
            {
                int index = 0;
                while (enumerator.MoveNext())
                {
                    Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
                    Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
                    index++;
                }
            }

            // XML parts can be removed by index
            doc.CustomXmlParts.RemoveAt(1);

            Assert.AreEqual(1, doc.CustomXmlParts.Count);

            // The XML part collection itself can be cloned also
            CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

            // And all elements can be cleared like this
            customXmlParts.Clear();

            // Create a StructuredDocumentTag that will display the contents of our part,
            // insert it into the document and save the document
            StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);

            tag.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", string.Empty);

            doc.FirstSection.Body.AppendChild(tag);

            doc.Save(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx");
            //ExEnd

            Assert.IsTrue(DocumentHelper.CompareDocs(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx", GoldsDir + "StructuredDocumentTag.CustomXml Gold.docx"));

            doc     = new Document(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx");
            xmlPart = doc.CustomXmlParts[0];

            Assert.True(Guid.TryParse(xmlPart.Id, out Guid temp));
            Assert.AreEqual("<root><text>Hello world!</text></root>", Encoding.UTF8.GetString(xmlPart.Data));
            Assert.AreEqual("http://www.w3.org/2001/XMLSchema", xmlPart.Schemas[0]);

            tag = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
            Assert.AreEqual("Hello world!", tag.GetText().Trim());
            Assert.AreEqual("/root[1]/text[1]", tag.XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tag.XmlMapping.PrefixMappings);
        }
예제 #13
0
        public void ListItemCollection()
        {
            //ExStart
            //ExFor:SdtListItem
            //ExFor:SdtListItem.#ctor(System.String)
            //ExFor:SdtListItem.#ctor(System.String,System.String)
            //ExFor:SdtListItem.DisplayText
            //ExFor:SdtListItem.Value
            //ExFor:SdtListItemCollection
            //ExFor:SdtListItemCollection.Add(Aspose.Words.Markup.SdtListItem)
            //ExFor:SdtListItemCollection.Clear
            //ExFor:SdtListItemCollection.Count
            //ExFor:SdtListItemCollection.GetEnumerator
            //ExFor:SdtListItemCollection.Item(System.Int32)
            //ExFor:SdtListItemCollection.RemoveAt(System.Int32)
            //ExFor:SdtListItemCollection.SelectedValue
            //ExFor:StructuredDocumentTag.ListItems
            //ExSummary:Shows how to work with StructuredDocumentTag nodes of the DropDownList type.
            // Create a blank document and insert a StructuredDocumentTag that will contain a drop-down list
            Document doc = new Document();
            StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);

            doc.FirstSection.Body.AppendChild(tag);

            // A drop-down list needs elements, each of which will be a SdtListItem
            SdtListItemCollection listItems = tag.ListItems;

            listItems.Add(new SdtListItem("Value 1"));

            // Each SdtListItem has text that will be displayed when the drop-down list is opened, and also a value
            // When we initialize with one string, we are providing just the value
            // Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
            Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

            // Add 3 more SdtListItems with non-empty strings passed to DisplayText
            listItems.Add(new SdtListItem("Item 2", "Value 2"));
            listItems.Add(new SdtListItem("Item 3", "Value 3"));
            listItems.Add(new SdtListItem("Item 4", "Value 4"));

            // We can obtain a count of the SdtListItems and also set the drop-down list's SelectedValue attribute to
            // automatically have one of them pre-selected when we open the document in Microsoft Word
            Assert.AreEqual(4, listItems.Count);
            listItems.SelectedValue = listItems[3];

            Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

            // We can enumerate over the collection and print each element
            using (IEnumerator <SdtListItem> enumerator = listItems.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    if (enumerator.Current != null)
                    {
                        Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
                    }
                }
            }

            // We can also remove elements one at a time
            listItems.RemoveAt(3);
            Assert.AreEqual(3, listItems.Count);

            // Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
            listItems.SelectedValue = listItems[1];

            doc.Save(ArtifactsDir + "StructuredDocumentTag.ListItemCollection.docx");

            // We can clear the whole collection at once too
            listItems.Clear();
            Assert.AreEqual(0, listItems.Count);
            //ExEnd
        }
예제 #14
0
        public void PlainText()
        {
            //ExStart
            //ExFor:StructuredDocumentTag.Color
            //ExFor:StructuredDocumentTag.ContentsFont
            //ExFor:StructuredDocumentTag.EndCharacterFont
            //ExFor:StructuredDocumentTag.Id
            //ExFor:StructuredDocumentTag.Level
            //ExFor:StructuredDocumentTag.Multiline
            //ExFor:StructuredDocumentTag.Tag
            //ExFor:StructuredDocumentTag.Title
            //ExFor:StructuredDocumentTag.RemoveSelfOnly
            //ExSummary:Shows how to create a StructuredDocumentTag in the form of a plain text box and modify its appearance.
            // Create a new document
            Document doc = new Document();

            // Create a StructuredDocumentTag that will contain plain text
            StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

            // Set the title and color of the frame that appears when you mouse over it
            tag.Title = "My plain text";
            tag.Color = Color.Magenta;

            // Set a programmatic tag for this StructuredDocumentTag
            // Unlike the title, this value will not be visible in the document but will be programmatically obtainable
            // as an XML element named "tag", with the string below in its "@val" attribute
            tag.Tag = "MyPlainTextSDT";

            // Every StructuredDocumentTag gets a random unique ID
            Assert.That(tag.Id, Is.Positive);

            // Set the font for the text inside the StructuredDocumentTag
            tag.ContentsFont.Name = "Arial";

            // Set the font for the text at the end of the StructuredDocumentTag
            // Any text that is typed in the document body after moving out of the tag with arrow keys will keep this font
            tag.EndCharacterFont.Name = "Arial Black";

            // By default, this is false and pressing enter while inside a StructuredDocumentTag does nothing
            // When set to true, our StructuredDocumentTag can have multiple lines
            tag.Multiline = true;

            // Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document to a file
            DocumentBuilder builder = new DocumentBuilder(doc);

            builder.InsertNode(tag);

            // Insert a clone of our StructuredDocumentTag in a new paragraph
            StructuredDocumentTag tagClone = (StructuredDocumentTag)tag.Clone(true);

            builder.InsertParagraph();
            builder.InsertNode(tagClone);

            // We can remove the tag while keeping its contents where they were in the Paragraph by calling RemoveSelfOnly()
            tagClone.RemoveSelfOnly();

            doc.Save(ArtifactsDir + "StructuredDocumentTag.PlainText.docx");
            //ExEnd

            doc = new Document(ArtifactsDir + "StructuredDocumentTag.PlainText.docx");
            tag = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);

            Assert.AreEqual("My plain text", tag.Title);
            Assert.AreEqual(Color.Magenta.ToArgb(), tag.Color.ToArgb());
            Assert.AreEqual("MyPlainTextSDT", tag.Tag);
            Assert.That(tag.Id, Is.Positive);
            Assert.AreEqual("Arial", tag.ContentsFont.Name);
            Assert.AreEqual("Arial Black", tag.EndCharacterFont.Name);
            Assert.True(tag.Multiline);
        }
        public void PlainText()
        {
            //ExStart
            //ExFor:StructuredDocumentTag.Color
            //ExFor:StructuredDocumentTag.ContentsFont
            //ExFor:StructuredDocumentTag.EndCharacterFont
            //ExFor:StructuredDocumentTag.Id
            //ExFor:StructuredDocumentTag.Level
            //ExFor:StructuredDocumentTag.Multiline
            //ExFor:StructuredDocumentTag.Tag
            //ExFor:StructuredDocumentTag.Title
            //ExFor:StructuredDocumentTag.RemoveSelfOnly
            //ExSummary:Shows how to create a structured document tag in a plain text box and modify its appearance.
            Document doc = new Document();

            // Create a structured document tag that will contain plain text.
            StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

            // Set the title and color of the frame that appears when you mouse over the structured document tag in Microsoft Word.
            tag.Title = "My plain text";
            tag.Color = Color.Magenta;

            // Set a tag for this structured document tag, which is obtainable
            // as an XML element named "tag", with the string below in its "@val" attribute.
            tag.Tag = "MyPlainTextSDT";

            // Every structured document tag has a random unique ID.
            Assert.That(tag.Id, Is.Positive);

            // Set the font for the text inside the structured document tag.
            tag.ContentsFont.Name = "Arial";

            // Set the font for the text at the end of the structured document tag.
            // Any text that we type in the document body after moving out of the tag with arrow keys will use this font.
            tag.EndCharacterFont.Name = "Arial Black";

            // By default, this is false and pressing enter while inside a structured document tag does nothing.
            // When set to true, our structured document tag can have multiple lines.

            // Set the "Multiline" property to "false" to only allow the contents
            // of this structured document tag to span a single line.
            // Set the "Multiline" property to "true" to allow the tag to contain multiple lines of content.
            tag.Multiline = true;

            DocumentBuilder builder = new DocumentBuilder(doc);

            builder.InsertNode(tag);

            // Insert a clone of our structured document tag in a new paragraph.
            StructuredDocumentTag tagClone = (StructuredDocumentTag)tag.Clone(true);

            builder.InsertParagraph();
            builder.InsertNode(tagClone);

            // Use the "RemoveSelfOnly" method to remove a structured document tag, while keeping its contents in the document.
            tagClone.RemoveSelfOnly();

            doc.Save(ArtifactsDir + "StructuredDocumentTag.PlainText.docx");
            //ExEnd

            doc = new Document(ArtifactsDir + "StructuredDocumentTag.PlainText.docx");
            tag = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);

            Assert.AreEqual("My plain text", tag.Title);
            Assert.AreEqual(Color.Magenta.ToArgb(), tag.Color.ToArgb());
            Assert.AreEqual("MyPlainTextSDT", tag.Tag);
            Assert.That(tag.Id, Is.Positive);
            Assert.AreEqual("Arial", tag.ContentsFont.Name);
            Assert.AreEqual("Arial Black", tag.EndCharacterFont.Name);
            Assert.True(tag.Multiline);
        }
예제 #16
0
        public override VisitorAction VisitStructuredDocumentTagEnd(StructuredDocumentTag sdt)
        {
            if (IsCompositeAcrossPage(sdt))
                SplitComposite(sdt);

            return VisitorAction.Continue;
        }
예제 #17
0
        //public List<string> GetDocumentTags(byte[] buffer)
        //{
        //    if (buffer == null) throw new ArgumentNullException(nameof(buffer));

        //    Document document;
        //    using (var ms = new MemoryStream(buffer))
        //    {
        //        document = new Document(ms);
        //    }

        //    return document
        //        .GetChildNodes(NodeType.StructuredDocumentTag, true)
        //        .ToArray()
        //        .Select(x => ((StructuredDocumentTag)x).Title)
        //        .ToList();
        //}

        private void FillUserInputControl(StructuredDocumentTag std,
                                          Dictionary <string, string> userInputFieldsDictionaty, Document document,
                                          DocumentBuilder builder, string defaultValue)
        {
            //std.RemoveAllChildren();

            Paragraph paragraph;
            var       html = userInputFieldsDictionaty[std.Title.Trim()];

            if (string.IsNullOrEmpty(html))
            {
                return;
            }
            html = TrimParagraphTag(html);
            html = ResizeBase64Images(html);

            //была проблема при вставке html если тег находился в параграфе
            //если Content Control находится не в Body, а во вложенном теге
            if (std.ParentNode.NodeType != NodeType.Body)
            {
                //проверяем текущее поле на простой текст без форматирования
                if (std.Title.Trim().EndsWith("_UserInput"))
                {
                    if (std.ParentNode.NodeType == NodeType.Paragraph)
                    {
                        var run = new Run(document, html);

                        // set font
                        Inline inlineElement = GetFirstInline(std.ChildNodes);
                        if (inlineElement != null)
                        {
                            CopyFont(run.Font, inlineElement.Font);
                        }

                        std.RemoveAllChildren();
                        std.AppendChild(run);
                        std.RemoveSelfOnly();
                    }
                    else
                    {
                        paragraph = (Paragraph)std.ParentNode.InsertAfter(new Paragraph(document), std);

                        // set font
                        Paragraph paragraphSource = (Paragraph)std.FirstChild;
                        Inline    inlineElement   = GetFirstInline(paragraphSource.ChildNodes);
                        var       run             = new Run(document, html);
                        if (inlineElement != null)
                        {
                            CopyFont(run.Font, inlineElement.Font);
                        }

                        paragraph.AppendChild(run);
                        std.Remove();
                    }
                }
                //если поле со значение по умолчанию
                else if (std.Title.Trim().EndsWith("_UserInputDefault"))
                {
                    html = html.Equals(string.Empty) ? defaultValue : html;
                    if (std.ParentNode.NodeType == NodeType.Paragraph)
                    {
                        var run = new Run(document, html);

                        // set font
                        Inline inlineElement = GetFirstInline(std.ChildNodes);
                        if (inlineElement != null)
                        {
                            CopyFont(run.Font, inlineElement.Font);
                        }

                        std.RemoveAllChildren();
                        std.AppendChild(run);
                        std.RemoveSelfOnly();
                    }
                    else
                    {
                        paragraph = (Paragraph)std.ParentNode.InsertAfter(new Paragraph(document), std);

                        // set font
                        Paragraph paragraphSource = (Paragraph)std.FirstChild;
                        Inline    inlineElement   = GetFirstInline(paragraphSource.ChildNodes);
                        var       run             = new Run(document, html);
                        if (inlineElement != null)
                        {
                            CopyFont(run.Font, inlineElement.Font);
                        }

                        paragraph.AppendChild(run);
                        std.Remove();
                    }
                }
                //если текст из wysiwyg редактора
                else
                {
                    std.RemoveAllChildren();

                    if (std.ParentNode.NodeType == NodeType.Paragraph)
                    {
                        builder.MoveTo(std);
                        builder.InsertHtml(html, true);
                        std.RemoveSelfOnly();
                    }
                    else
                    {
                        paragraph = (Paragraph)std.ParentNode.InsertAfter(new Paragraph(document), std);
                        builder.MoveTo(paragraph);
                        builder.InsertHtml(html, true);

                        std.AppendChild(paragraph);
                        std.RemoveSelfOnly();
                    }
                }
            }
            //если Content Control находится в корне тега Body
            else
            {
                if (std.Title.Trim().EndsWith("_UserInput"))
                {
                    paragraph = (Paragraph)std.ParentNode.InsertAfter(new Paragraph(document), std);

                    // set font
                    Paragraph paragraphSource = (Paragraph)std.FirstChild;
                    Inline    inlineElement   = GetFirstInline(paragraphSource.ChildNodes);
                    var       run             = new Run(document, html);
                    if (inlineElement != null)
                    {
                        CopyFont(run.Font, inlineElement.Font);
                    }

                    paragraph.AppendChild(run);
                    std.Remove();
                }
                else if (std.Title.Trim().EndsWith("_UserInputDefault"))
                {
                    html      = html.Equals(string.Empty) ? defaultValue : html;
                    paragraph = (Paragraph)std.ParentNode.InsertAfter(new Paragraph(document), std);

                    // set font
                    Paragraph paragraphSource = (Paragraph)std.FirstChild;
                    Inline    inlineElement   = GetFirstInline(paragraphSource.ChildNodes);
                    var       run             = new Run(document, html);
                    if (inlineElement != null)
                    {
                        CopyFont(run.Font, inlineElement.Font);
                    }

                    paragraph.AppendChild(run);
                    std.Remove();
                }
                //если текст из wysiwyg редактора
                else
                {
                    paragraph = (Paragraph)std.ParentNode.InsertAfter(new Paragraph(document), std);

                    builder.MoveTo(paragraph);
                    builder.InsertHtml(html, true);
                    std.Remove();
                }
            }
        }
        public void FillTableUsingRepeatingSectionItem()
        {
            //ExStart
            //ExFor:SdtType
            //ExSummary:Shows how to fill the table with data contained in the XML part.
            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>");
             
            // Create headers for data from xml content
            Table table = builder.StartTable();

            builder.InsertCell();
            builder.Write("Title");
            builder.InsertCell();
            builder.Write("Author");
            builder.EndRow();
            builder.EndTable();
             
            // Create table with RepeatingSection inside
            StructuredDocumentTag repeatingSectionSdt =
                new StructuredDocumentTag(doc, SdtType.RepeatingSection, MarkupLevel.Row);

            repeatingSectionSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book", "");
            table.AppendChild(repeatingSectionSdt);
             
            // Add RepeatingSectionItem inside RepeatingSection and mark it as a row
            StructuredDocumentTag repeatingSectionItemSdt =
                new StructuredDocumentTag(doc, SdtType.RepeatingSectionItem, MarkupLevel.Row);

            repeatingSectionSdt.AppendChild(repeatingSectionItemSdt);
             
            Row row = new Row(doc);

            repeatingSectionItemSdt.AppendChild(row);
             
            // Map xml data with created table cells for book title and author
            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(ArtifactsDir + "StructuredDocumentTag.RepeatingSectionItem.docx");

            //ExEnd
        }
        public void ListItemCollection()
        {
            //ExStart
            //ExFor:SdtListItem
            //ExFor:SdtListItem.#ctor(System.String)
            //ExFor:SdtListItem.#ctor(System.String,System.String)
            //ExFor:SdtListItem.DisplayText
            //ExFor:SdtListItem.Value
            //ExFor:SdtListItemCollection
            //ExFor:SdtListItemCollection.Add(Aspose.Words.Markup.SdtListItem)
            //ExFor:SdtListItemCollection.Clear
            //ExFor:SdtListItemCollection.Count
            //ExFor:SdtListItemCollection.GetEnumerator
            //ExFor:SdtListItemCollection.Item(System.Int32)
            //ExFor:SdtListItemCollection.RemoveAt(System.Int32)
            //ExFor:SdtListItemCollection.SelectedValue
            //ExFor:StructuredDocumentTag.ListItems
            //ExSummary:Shows how to work with drop down-list structured document tags.
            Document doc = new Document();
            StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);

            doc.FirstSection.Body.AppendChild(tag);

            // A drop-down list structured document tag is a form that allows the user to
            // select an option from a list by left-clicking and opening the form in Microsoft Word.
            // The "ListItems" property contains all list items, and each list item is an "SdtListItem".
            SdtListItemCollection listItems = tag.ListItems;

            listItems.Add(new SdtListItem("Value 1"));

            Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

            // Add 3 more list items. Initialize these items using a different constructor to the first item
            // to display strings that are different from their values.
            listItems.Add(new SdtListItem("Item 2", "Value 2"));
            listItems.Add(new SdtListItem("Item 3", "Value 3"));
            listItems.Add(new SdtListItem("Item 4", "Value 4"));

            Assert.AreEqual(4, listItems.Count);

            // The drop-down list is displaying the first item. Assign a different list item to the "SelectedValue" to display it.
            listItems.SelectedValue = listItems[3];

            Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

            // Enumerate over the collection and print each element.
            using (IEnumerator <SdtListItem> enumerator = listItems.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    if (enumerator.Current != null)
                    {
                        Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
                    }
                }
            }

            // Remove the last list item.
            listItems.RemoveAt(3);

            Assert.AreEqual(3, listItems.Count);

            // Since our drop-down control is set to display the removed item by default, give it an item to display which exists.
            listItems.SelectedValue = listItems[1];

            doc.Save(ArtifactsDir + "StructuredDocumentTag.ListItemCollection.docx");

            // Use the "Clear" method to empty the entire drop-down item collection at once.
            listItems.Clear();

            Assert.AreEqual(0, listItems.Count);
            //ExEnd
        }
        public void CreatingCustomXml()
        {
            //ExStart
            //ExFor:CustomXmlPart
            //ExFor:CustomXmlPart.Clone
            //ExFor:CustomXmlPart.Data
            //ExFor:CustomXmlPart.Id
            //ExFor:CustomXmlPart.Schemas
            //ExFor:CustomXmlPartCollection
            //ExFor:CustomXmlPartCollection.Add(CustomXmlPart)
            //ExFor:CustomXmlPartCollection.Add(String, String)
            //ExFor:CustomXmlPartCollection.Clear
            //ExFor:CustomXmlPartCollection.Clone
            //ExFor:CustomXmlPartCollection.Count
            //ExFor:CustomXmlPartCollection.GetById(String)
            //ExFor:CustomXmlPartCollection.GetEnumerator
            //ExFor:CustomXmlPartCollection.Item(Int32)
            //ExFor:CustomXmlPartCollection.RemoveAt(Int32)
            //ExFor:Document.CustomXmlParts
            //ExFor:StructuredDocumentTag.XmlMapping
            //ExFor:XmlMapping.SetMapping(CustomXmlPart, String, String)
            //ExSummary:Shows how to create a structured document tag with custom XML data.
            Document doc = new Document();

            // Construct an XML part that contains data and add it to the document's collection.
            // If we enable the "Developer" tab in Microsoft Word,
            // we can find elements from this collection in the "XML Mapping Pane", along with a few default elements.
            string        xmlPartId      = Guid.NewGuid().ToString("B");
            string        xmlPartContent = "<root><text>Hello world!</text></root>";
            CustomXmlPart xmlPart        = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

            Assert.AreEqual(Encoding.ASCII.GetBytes(xmlPartContent), xmlPart.Data);
            Assert.AreEqual(xmlPartId, xmlPart.Id);

            // Below are two ways to refer to XML parts.
            // 1 -  By an index in the custom XML part collection:
            Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);

            // 2 -  By GUID:
            Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

            // Add an XML schema association.
            xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

            // Clone a part, and then insert it into the collection.
            CustomXmlPart xmlPartClone = xmlPart.Clone();

            xmlPartClone.Id = Guid.NewGuid().ToString("B");
            doc.CustomXmlParts.Add(xmlPartClone);

            Assert.AreEqual(2, doc.CustomXmlParts.Count);

            // Iterate through the collection and print the contents of each part.
            using (IEnumerator <CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
            {
                int index = 0;
                while (enumerator.MoveNext())
                {
                    Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
                    Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
                    index++;
                }
            }

            // Use the "RemoveAt" method to remove the cloned part by index.
            doc.CustomXmlParts.RemoveAt(1);

            Assert.AreEqual(1, doc.CustomXmlParts.Count);

            // Clone the XML parts collection, and then use the "Clear" method to remove all its elements at once.
            CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

            customXmlParts.Clear();

            // Create a structured document tag that will display our part's contents and insert it into the document body.
            StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);

            tag.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", string.Empty);

            doc.FirstSection.Body.AppendChild(tag);

            doc.Save(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx");
            //ExEnd

            Assert.IsTrue(DocumentHelper.CompareDocs(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx", GoldsDir + "StructuredDocumentTag.CustomXml Gold.docx"));

            doc     = new Document(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx");
            xmlPart = doc.CustomXmlParts[0];

            Assert.True(Guid.TryParse(xmlPart.Id, out Guid temp));
            Assert.AreEqual("<root><text>Hello world!</text></root>", Encoding.UTF8.GetString(xmlPart.Data));
            Assert.AreEqual("http://www.w3.org/2001/XMLSchema", xmlPart.Schemas[0]);

            tag = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
            Assert.AreEqual("Hello world!", tag.GetText().Trim());
            Assert.AreEqual("/root[1]/text[1]", tag.XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tag.XmlMapping.PrefixMappings);
        }
        public void FillTableUsingRepeatingSectionItem()
        {
            //ExStart
            //ExFor:SdtType
            //ExSummary:Shows how to fill a table with data from in an XML part.
            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>The C Programming Language</title>" +
                                                           "<author>Brian W. Kernighan, Dennis M. Ritchie</author>" +
                                                           "</book>" +
                                                           "<book>" +
                                                           "<title>Learning XML</title>" +
                                                           "<author>Erik T. Ray</author>" +
                                                           "</book>" +
                                                           "</books>");
             
            // Create headers for data from the XML content.
            Table table = builder.StartTable();

            builder.InsertCell();
            builder.Write("Title");
            builder.InsertCell();
            builder.Write("Author");
            builder.EndRow();
            builder.EndTable();

            // Create a table with a repeating section inside.
            StructuredDocumentTag repeatingSectionSdt =
                new StructuredDocumentTag(doc, SdtType.RepeatingSection, MarkupLevel.Row);

            repeatingSectionSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book", string.Empty);
            table.AppendChild(repeatingSectionSdt);

            // Add repeating section item inside the repeating section and mark it as a row.
            // This table will have a row for each element that we can find in the XML document
            // using the "/books[1]/book" XPath, of which there are three.
            StructuredDocumentTag repeatingSectionItemSdt =
                new StructuredDocumentTag(doc, SdtType.RepeatingSectionItem, MarkupLevel.Row);

            repeatingSectionSdt.AppendChild(repeatingSectionItemSdt);
             
            Row row = new Row(doc);

            repeatingSectionItemSdt.AppendChild(row);

            // Map XML data with created table cells for the title and author of each book.
            StructuredDocumentTag titleSdt =
                new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell);

            titleSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/title[1]", string.Empty);
            row.AppendChild(titleSdt);
             
            StructuredDocumentTag authorSdt =
                new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell);

            authorSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/author[1]", string.Empty);
            row.AppendChild(authorSdt);
             
            doc.Save(ArtifactsDir + "StructuredDocumentTag.RepeatingSectionItem.docx");

            //ExEnd

            doc = new Document(ArtifactsDir + "StructuredDocumentTag.RepeatingSectionItem.docx");
            List <StructuredDocumentTag> tags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true).OfType <StructuredDocumentTag>().ToList();

            Assert.AreEqual("/books[1]/book", tags[0].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[0].XmlMapping.PrefixMappings);

            Assert.AreEqual(string.Empty, tags[1].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[1].XmlMapping.PrefixMappings);

            Assert.AreEqual("/books[1]/book[1]/title[1]", tags[2].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[2].XmlMapping.PrefixMappings);

            Assert.AreEqual("/books[1]/book[1]/author[1]", tags[3].XmlMapping.XPath);
            Assert.AreEqual(string.Empty, tags[3].XmlMapping.PrefixMappings);

            Assert.AreEqual("Title\u0007Author\u0007\u0007" +
                            "Everyday Italian\u0007Giada De Laurentiis\u0007\u0007" +
                            "The C Programming Language\u0007Brian W. Kernighan, Dennis M. Ritchie\u0007\u0007" +
                            "Learning XML\u0007Erik T. Ray\u0007\u0007", doc.FirstSection.Body.Tables[0].GetText().Trim());
        }