/// <summary>
        /// Creates word document with built - in styles
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                WordDocument document = new WordDocument();
                WSection     section  = document.AddSection() as WSection;
                WParagraph   para     = section.AddParagraph() as WParagraph;
                section.AddColumn(100, 100);
                section.AddColumn(100, 100);
                section.MakeColumnsEqual();

                #region Built-in styles
                # region List Style

                //List
                para.AppendText("This para is written with style List").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
                para = section.AddParagraph() as WParagraph;
                para.ApplyStyle(BuiltinStyle.List);
                para.AppendText("Google Chrome\n");
                para.AppendText("Mozilla Firefox\n");
                para.AppendText("Internet Explorer");

                //List5 style
                para = section.AddParagraph() as WParagraph;
                para.AppendText("\nThis para is written with style List5").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
                para = section.AddParagraph() as WParagraph;
                para.ApplyStyle(BuiltinStyle.List5);
                para.AppendText("Google Chrome\n");
                para.AppendText("Mozilla Firefox\n");
                para.AppendText("Internet Explorer");

                # endregion

                # region ListNumber Style
Beispiel #2
0
        /// <summary>
        /// Removes the table of contents from Word document.
        /// </summary>
        /// <param name="toc"></param>
        private static void RemoveTableOfContents(TableOfContent toc)
        {
            //Finds the last TOC item.
            Entity lastItem = FindLastTOCItem(toc);

            //TOC field end mark wasn't exist.
            if (lastItem == null)
            {
                return;
            }

            //Inserts the bookmark start before the TOC instance.
            BookmarkStart bkmkStart = new BookmarkStart(toc.Document, "tableOfContent");

            toc.OwnerParagraph.Items.Insert(toc.OwnerParagraph.Items.IndexOf(toc), bkmkStart);

            //Inserts the bookmark end to next of TOC last item.
            BookmarkEnd bkmkEnd   = new BookmarkEnd(toc.Document, "tableOfContent");
            WParagraph  paragraph = lastItem.Owner as WParagraph;

            paragraph.Items.Insert(paragraph.Items.IndexOf(lastItem) + 1, bkmkEnd);

            //Delete all the items from bookmark start to end (TOC items) using Bookmark Navigator.
            DeleteBookmarkContents(bkmkEnd.Name, toc.Document);
        }
 static void Main(string[] args)
 {
     //Creates new Word document instance for Word processing
     using (WordDocument document = new WordDocument())
     {
         //Opens the input Word document
         Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
         document.Open(docStream, FormatType.Docx);
         docStream.Dispose();
         //Finds all the placeholder text enclosed within '«' and '»' in the Word document
         TextSelection[] textSelections       = document.FindAll(new Regex("«([(?i)image(?-i)]*:*[a-zA-Z0-9 ]*:*[a-zA-Z0-9 ]+)»"));
         string[]        searchedPlaceholders = new string[textSelections.Length];
         for (int i = 0; i < textSelections.Length; i++)
         {
             searchedPlaceholders[i] = textSelections[i].SelectedText;
         }
         for (int i = 0; i < searchedPlaceholders.Length; i++)
         {
             //Replaces the placeholder text enclosed within '«' and '»' with desired merge field
             WParagraph paragraph = new WParagraph(document);
             paragraph.AppendField(searchedPlaceholders[i].TrimStart('«').TrimEnd('»'), FieldType.FieldMergeField);
             TextSelection newSelection = new TextSelection(paragraph, 0, paragraph.Items.Count);
             TextBodyPart  bodyPart     = new TextBodyPart(document);
             bodyPart.BodyItems.Add(paragraph);
             document.Replace(searchedPlaceholders[i], bodyPart, true, true, true);
         }
         //Saves the resultant file in the given path
         docStream = File.Create(Path.GetFullPath(@"Result.docx"));
         document.Save(docStream, FormatType.Docx);
         docStream.Dispose();
     }
 }
 static void Main(string[] args)
 {
     //Creates new Word document instance for Word processing
     using (WordDocument document = new WordDocument())
     {
         //Opens the input Word document
         Stream docStream = File.OpenRead(Path.GetFullPath(@"../../../Template.docx"));
         document.Open(docStream, FormatType.Docx);
         docStream.Dispose();
         //Finds all the image placeholder text in the Word document.
         TextSelection[] textSelections = document.FindAll(new Regex("^//(.*)"));
         for (int i = 0; i < textSelections.Length; i++)
         {
             //Replaces the image placeholder text with desired image.
             Stream     imageStream = File.OpenRead(Path.GetFullPath(@"../../../" + textSelections[i].SelectedText + ".png"));
             WParagraph paragraph   = new WParagraph(document);
             WPicture   picture     = paragraph.AppendPicture(imageStream) as WPicture;
             imageStream.Dispose();
             TextSelection newSelection = new TextSelection(paragraph, 0, 1);
             TextBodyPart  bodyPart     = new TextBodyPart(document);
             bodyPart.BodyItems.Add(paragraph);
             document.Replace(textSelections[i].SelectedText, bodyPart, true, true);
         }
         //Saves the resultant file in the given path
         docStream = File.Create(Path.GetFullPath(@"Result.docx"));
         document.Save(docStream, FormatType.Docx);
         docStream.Dispose();
     }
 }
        /// <summary>
        /// Iterates into body items.
        /// </summary>
        private void RemoveFieldCodesInTextBody(WTextBody textBody)
        {
            for (int i = 0; i < textBody.ChildEntities.Count; i++)
            {
                //IEntity is the basic unit in DocIO DOM.
                IEntity bodyItemEntity = textBody.ChildEntities[i];

                //A Text body has 3 types of elements - Paragraph, Table, and Block Content Control
                //Decides the element type by using EntityType
                switch (bodyItemEntity.EntityType)
                {
                case EntityType.Paragraph:
                    WParagraph paragraph = bodyItemEntity as WParagraph;
                    //Iterates into paragraph items.
                    RemoveFieldCodesInParagraph(paragraph.Items);
                    break;

                case EntityType.Table:
                    //Table is a collection of rows and cells
                    //Iterates through table's DOM
                    RemoveFieldCodesInTable(bodyItemEntity as WTable);
                    break;

                case EntityType.BlockContentControl:
                    BlockContentControl blockContentControl = bodyItemEntity as BlockContentControl;
                    //Iterates to the body items of Block Content Control.
                    RemoveFieldCodesInTextBody(blockContentControl.TextBody);
                    break;
                }
            }
        }
        private static WListItemElement GetListItemElementFromXMLData(XmlNode ListItemNode)
        {
            if (ListItemNode != null)
            {
                WListItemElement wlie = new WListItemElement();

                if (ListItemNode.Name == WordXMLTags.WordTagName_Paragraph)
                {
                    WParagraph WPrg = WParagraphReader.GetParagraphFromParagraphXMLNode(ListItemNode);
                    wlie.ListItemElement = WPrg;
                    wlie.ListID          = WPrg.ListID;
                    wlie.ListItemLevel   = WPrg.ListItemLevel;
                }
                else if (ListItemNode.Name == WordXMLTags.WTN_Table)
                {
                    WTable LTable = WTableReader.GetTableFromTableXMLData(ListItemNode.OuterXml);
                    wlie.ListItemElement = LTable;
                    wlie.ListItemLevel   = -1;
                    wlie.ListID          = -1;
                }

                return(wlie);
            }
            return(null);
        }
Beispiel #7
0
        /// <summary>
        /// Finds the last TOC item from consequence text body items.
        /// </summary>
        /// <param name="toc"></param>
        /// <param name="fieldStack"></param>
        /// <returns></returns>
        private static Entity FindLastItemInTextBody(TableOfContent toc, Stack <Entity> fieldStack)
        {
            WTextBody tBody = toc.OwnerParagraph.OwnerTextBody;

            for (int i = tBody.ChildEntities.IndexOf(toc.OwnerParagraph) + 1; i < tBody.ChildEntities.Count; i++)
            {
                WParagraph paragraph = tBody.ChildEntities[i] as WParagraph;

                foreach (Entity item in paragraph.Items)
                {
                    if (item is WField)
                    {
                        fieldStack.Push(item);
                    }
                    else if (item is WFieldMark && (item as WFieldMark).Type == FieldMarkType.FieldEnd)
                    {
                        if (fieldStack.Count == 1)
                        {
                            fieldStack.Clear();
                            return(item);
                        }
                        else
                        {
                            fieldStack.Pop();
                        }
                    }
                }
            }
            return(null);
        }
 /// <summary>
 /// Applies formatting for image caption paragraph.
 /// </summary>
 private static void ApplyFormattingForCaption(WParagraph paragraph)
 {
     //Sets Alignment to the caption.
     paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
     //Sets after and before spacings.
     paragraph.ParagraphFormat.AfterSpacing  = 24f;
     paragraph.ParagraphFormat.BeforeSpacing = 8f;
 }
Beispiel #9
0
 /// <summary>
 /// Apply formattings for image caption paragraph
 /// </summary>
 private void ApplyFormattingForCaption(WParagraph paragraph)
 {
     //Align the caption
     paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
     //Sets after spacing
     paragraph.ParagraphFormat.AfterSpacing = 1.5f;
     //Sets before spacing
     paragraph.ParagraphFormat.BeforeSpacing = 1.5f;
 }
Beispiel #10
0
        private void InsertFirstPageHeaderFooter(WordDocument doc, IWSection section)
        {
            Assembly execAssm = typeof(HeadersAndFootersDemo).GetTypeInfo().Assembly;

            Stream inputStream = execAssm.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Assets.Northwind_logo.png");

            // Add a new paragraph for header to the document.
            IWParagraph headerPar = new WParagraph(doc);

            // Add a new table to the header.
            IWTable table = section.HeadersFooters.FirstPageHeader.AddTable();

            RowFormat format = new RowFormat();

            // Setting cleared table border style.
            format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Cleared;

            // Inserting table with a row and two columns.
            table.ResetCells(1, 2, format, 265);

            // Inserting logo image to the table first cell.
            headerPar = table[0, 0].AddParagraph() as WParagraph;
            headerPar.AppendPicture(inputStream);
            //Set Image size
            (headerPar.Items[0] as WPicture).Width  = 232.5f;
            (headerPar.Items[0] as WPicture).Height = 54.75f;
            // Inserting text to the table second cell.
            headerPar = table[0, 1].AddParagraph() as WParagraph;
            IWTextRange txt = headerPar.AppendText("Company Headquarters,\n2501 Aerial Center Parkway,\nSuite 110, Morrisville, NC 27560,\nTEL 1-888-936-8638.");

            txt.CharacterFormat.FontSize                  = 12;
            txt.CharacterFormat.CharacterSpacing          = 1.7f;
            headerPar.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
            // Add a new paragraph to the header with address text.
            headerPar = new WParagraph(doc);
            headerPar.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            txt = headerPar.AppendText("\nFirst Page Header");
            txt.CharacterFormat.CharacterSpacing = 1.7f;
            section.HeadersFooters.FirstPageHeader.Paragraphs.Add(headerPar);

            // Add a footer paragraph text to the document.
            WParagraph footerPar = new WParagraph(doc);

            footerPar.ParagraphFormat.Tabs.AddTab(523f, TabJustification.Right, TabLeader.NoLeader);
            // Add text.
            footerPar.AppendText("Copyright Northwind Inc. 2001 - 2015");
            // Add page and Number of pages field to the document.
            footerPar.AppendText("\tFirst Page ");
            footerPar.AppendField("Page", FieldType.FieldPage);
            section.HeadersFooters.FirstPageFooter.Paragraphs.Add(footerPar);
            #region Page Number Settings
            section.PageSetup.RestartPageNumbering = true;
            section.PageSetup.PageStartingNumber   = Convert.ToInt32(this.numericUpDown1.Value);
            section.PageSetup.PageNumberStyle      = (PageNumberStyle)Enum.Parse(typeof(PageNumberStyle), this.comboBox1.SelectedItem.ToString(), true);
            #endregion
        }
Beispiel #11
0
        private static void AddHeading(WSection section, string styleName, string headingText, string paragraghText)
        {
            WParagraph newPara = section.AddParagraph() as WParagraph;
            WTextRange text    = newPara.AppendText(headingText) as WTextRange;

            newPara.ApplyStyle(styleName);
            newPara = section.AddParagraph() as WParagraph;
            newPara.AppendText(paragraghText);
            section.AddParagraph();
        }
Beispiel #12
0
        private void InsertFirstPageHeaderFooter(WordDocument doc, IWSection section)
        {
            // Add a new paragraph for header to the document.
            IWParagraph headerPar = new WParagraph(doc);

            // Add a new table to the header.
            IWTable table = section.HeadersFooters.FirstPageHeader.AddTable();

            RowFormat format = new RowFormat();

            // Setting cleared table border style.
            format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Cleared;

            // Inserting table with a row and two columns.
            table.ResetCells(1, 2, format, 265);

            // Inserting logo image to the table first cell.
            headerPar = table[0, 0].AddParagraph() as WParagraph;
            string     basePath    = _hostingEnvironment.WebRootPath;
            FileStream imageStream = new FileStream(basePath + @"/images/DocIO/Northwind_logo.png", FileMode.Open, FileAccess.Read);

            headerPar.AppendPicture(imageStream);
            //Set Image size
            (headerPar.Items[0] as WPicture).Width  = 232.5f;
            (headerPar.Items[0] as WPicture).Height = 54.75f;
            // Inserting text to the table second cell.
            headerPar = table[0, 1].AddParagraph() as WParagraph;
            IWTextRange txt = headerPar.AppendText("Company Headquarters,\n2501 Aerial Center Parkway,\nSuite 110, Morrisville, NC 27560,\nTEL 1-888-936-8638.");

            txt.CharacterFormat.FontSize                  = 12;
            txt.CharacterFormat.CharacterSpacing          = 1.7f;
            headerPar.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
            // Add a new paragraph to the header with address text.
            headerPar = new WParagraph(doc);
            headerPar.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            txt = headerPar.AppendText("\nFirst Page Header");
            txt.CharacterFormat.CharacterSpacing = 1.7f;
            section.HeadersFooters.FirstPageHeader.Paragraphs.Add(headerPar);

            // Add a footer paragraph text to the document.
            WParagraph footerPar = new WParagraph(doc);

            footerPar.ParagraphFormat.Tabs.AddTab(523f, TabJustification.Right, TabLeader.NoLeader);
            // Add text.
            footerPar.AppendText("Copyright Northwind Inc. 2001 - 2017");
            // Add page and Number of pages field to the document.
            footerPar.AppendText("\tFirst Page ");
            footerPar.AppendField("Page", FieldType.FieldPage);
            section.HeadersFooters.FirstPageFooter.Paragraphs.Add(footerPar);
            #region Page Number Settings
            section.PageSetup.RestartPageNumbering = true;
            section.PageSetup.PageStartingNumber   = 1;
            section.PageSetup.PageNumberStyle      = PageNumberStyle.Arabic;
            #endregion Page Number Settings
        }
Beispiel #13
0
        /// <summary>
        /// Inserts Header and Footer to first page.
        /// </summary>
        private void InsertFirstPageHeaderFooter(WordDocument doc, IWSection section)
        {
            //Adds a new table to the header.
            IWTable table = section.HeadersFooters.FirstPageHeader.AddTable();

            RowFormat format = new();

            //Sets cleared table border style.
            format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Cleared;

            //Inserts table with a row and two columns.
            table.ResetCells(1, 2, format, 265);

            //Inserts logo image to the table first cell.
            IWParagraph headerPara  = table[0, 0].AddParagraph() as WParagraph;
            Stream      imageStream = assembly.GetManifestResourceStream("syncfusion.dociodemos.winui.Assets.DocIO.Northwindlogo.png");

            headerPara.AppendPicture(imageStream);
            //Sets Image size
            (headerPara.Items[0] as WPicture).Width  = 232.5f;
            (headerPara.Items[0] as WPicture).Height = 54.75f;

            //Inserts text to the table second cell.
            headerPara = table[0, 1].AddParagraph() as WParagraph;
            IWTextRange txt = headerPara.AppendText("Company Headquarters,\n2501 Aerial Center Parkway,\nSuite 110, Morrisville, NC 27560,\nTEL 1-888-936-8638.");

            txt.CharacterFormat.FontSize                   = 12;
            txt.CharacterFormat.CharacterSpacing           = 1.7f;
            headerPara.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
            //Adds a new paragraph to the header with address text.
            headerPara = new WParagraph(doc);
            headerPara.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            txt = headerPara.AppendText("\nFirst Page Header");
            txt.CharacterFormat.CharacterSpacing = 1.7f;
            section.HeadersFooters.FirstPageHeader.Paragraphs.Add(headerPara);

            //Adds a footer paragraph text to the document.
            WParagraph footerPara = new(doc);

            footerPara.ParagraphFormat.Tabs.AddTab(523f, TabJustification.Right, TabLeader.NoLeader);
            //Adds text.
            footerPara.AppendText("Copyright Northwind Inc. 2001 - 2021");
            //Adds page and Number of pages field to the document.
            footerPara.AppendText("\tPage ");
            footerPara.AppendField("Page", FieldType.FieldPage);
            footerPara.AppendText(" of ");
            footerPara.AppendField("NumPages", FieldType.FieldNumPages);
            section.HeadersFooters.FirstPageFooter.Paragraphs.Add(footerPara);
            #region Page Number Settings
            section.PageSetup.RestartPageNumbering = true;
            section.PageSetup.PageStartingNumber   = 1;
            section.PageSetup.PageNumberStyle      = PageNumberStyle.Arabic;
            #endregion Page Number Settings
        }
Beispiel #14
0
        private void InsertPageHeaderFooter(WordDocument doc, IWSection section1)
        {
             // Add a new paragraph for header to the document.
            IWParagraph headerPar = new WParagraph(doc);

            // Add a new table to the header
            IWTable table = section1.HeadersFooters.Header.AddTable();

            RowFormat format = new RowFormat();

            // Setting Single table border style.
            format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;

            // Inserting table with a row and two columns.
            table.ResetCells(1, 2, format, 265);

            // Inserting logo image to the table first cell.
            headerPar = table[0, 0].AddParagraph() as WParagraph;
#if NETCORE
            headerPar.AppendPicture(Image.FromFile(@"..\..\..\..\..\..\..\..\Common\images\DocIO\Northwind_logo.png"));
#else                       
            headerPar.AppendPicture(Image.FromFile(@"..\..\..\..\..\..\..\Common\images\DocIO\Northwind_logo.png"));
#endif				
            //Set Image size.
            (headerPar.Items[0] as WPicture).Width = 232.5f;
            (headerPar.Items[0] as WPicture).Height = 54.75f;
            // Inserting text to the table second cell.
            headerPar = table[0, 1].AddParagraph() as WParagraph;
            IWTextRange txt = headerPar.AppendText("Company Headquarters,\n2501 Aerial Center Parkway,\nSuite 110, Morrisville, NC 27560,\nTEL 1-888-936-8638.");
            txt.CharacterFormat.FontSize = 12;
            txt.CharacterFormat.CharacterSpacing = 1.7f;
            headerPar.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;

            // Add a footer paragraph text to the document.
            WParagraph footerPar = new WParagraph(doc);
            footerPar.ParagraphFormat.Tabs.AddTab(523f, TabJustification.Right, TabLeader.NoLeader);
            // Add text.
            footerPar.AppendText("Copyright Northwind Inc. 2001 - 2017");
            // Add page and Number of pages field to the document.
            footerPar.AppendText("\tPage ");
            IWField ff = footerPar.AppendField("Page", Syncfusion.DocIO.FieldType.FieldPage);

            section1.HeadersFooters.Footer.Paragraphs.Add(footerPar);

            #region Page Number Settings
            section1.PageSetup.RestartPageNumbering = true;
            section1.PageSetup.PageStartingNumber = Convert.ToInt32(this.numericUpDown1.Value);
            section1.PageSetup.PageNumberStyle = (PageNumberStyle)Enum.Parse(typeof(PageNumberStyle), this.comboBox1.SelectedItem.ToString(), true);
            #endregion

        }
Beispiel #15
0
 static void Main(string[] args)
 {
     using (WordDocument document = new WordDocument())
     {
         document.EnsureMinimal();
         document.LastSection.PageSetup.Margins.All = 72;
         WParagraph para = document.LastParagraph;
         para.AppendText("Essential DocIO - Table of Contents");
         para.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;
         para.ApplyStyle(BuiltinStyle.Heading4);
         para = document.LastSection.AddParagraph() as WParagraph;
         //Creates the new custom styles.
         WParagraphStyle pStyle1 = (WParagraphStyle)document.AddParagraphStyle("MyStyle1");
         pStyle1.CharacterFormat.FontSize = 18f;
         WParagraphStyle pStyle2 = (WParagraphStyle)document.AddParagraphStyle("MyStyle2");
         pStyle2.CharacterFormat.FontSize = 16f;
         WParagraphStyle pStyle3 = (WParagraphStyle)document.AddParagraphStyle("MyStyle3");
         pStyle3.CharacterFormat.FontSize = 14f;
         para = document.LastSection.AddParagraph() as WParagraph;
         //Insert TOC field in the Word document.
         TableOfContent toc = para.AppendTOC(1, 3);
         //Sets the Heading Styles to false, to define custom levels for TOC.
         toc.UseHeadingStyles = false;
         //Sets the TOC level style which determines; based on which the TOC should be created.
         toc.SetTOCLevelStyle(1, "MyStyle1");
         toc.SetTOCLevelStyle(2, "MyStyle2");
         toc.SetTOCLevelStyle(3, "MyStyle3");
         //Adds content to the Word document with custom styles.
         WSection   section = document.LastSection;
         WParagraph newPara = section.AddParagraph() as WParagraph;
         newPara.AppendBreak(BreakType.PageBreak);
         AddHeading(section, "MyStyle1", "Document with custom styles", "This is the 1st custom style. This sample demonstrates the TOC insertion in a word document. Note that DocIO can insert TOC field in a word document. It can refresh or update TOC field by using UpdateTableOfContents method. MS Word refreshes the TOC field after insertion. Please update the field or press F9 key to refresh the TOC.");
         AddHeading(section, "MyStyle2", "Section 1", "This is the 2nd custom style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");
         AddHeading(section, "MyStyle3", "Paragraph 1", "This is the 3rd custom style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text.");
         AddHeading(section, "MyStyle3", "Paragraph 2", "This is the 3rd custom style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph.");
         AddHeading(section, "Normal", "Paragraph with normal", "This is the paragraph with normal style. This demonstrates the paragraph with outline level 4 and normal style. This can be attained by formatting outline level of the paragraph.");
         //Adds a new section to the Word document.
         section = document.AddSection() as WSection;
         section.PageSetup.Margins.All = 72;
         section.BreakCode             = SectionBreakCode.NewPage;
         AddHeading(section, "MyStyle2", "Section 2", "This is the 2nd custom style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");
         AddHeading(section, "MyStyle3", "Paragraph 1", "This is the 3rd custom style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text.");
         AddHeading(section, "MyStyle3", "Paragraph 2", "This is the 3rd custom style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph.");
         //Updates the table of contents.
         document.UpdateTableOfContents();
         //Saves the file in the given path
         Stream docStream = File.Create(Path.GetFullPath(@"../../../TOC-custom-style.docx"));
         document.Save(docStream, FormatType.Docx);
         docStream.Dispose();
     }
 }
Beispiel #16
0
        private void InsertPageHeaderFooter(WordDocument doc, IWSection section1)
        {
            // Add a new paragraph for header to the document.
            IWParagraph headerPar = new WParagraph(doc);

            // Add a new table to the header
            IWTable table = section1.HeadersFooters.Header.AddTable();

            RowFormat format = new RowFormat();

            // Setting Single table border style.
            format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;

            // Inserting table with a row and two columns.
            table.ResetCells(1, 2, format, 265);

            // Inserting logo image to the table first cell.
            headerPar = table[0, 0].AddParagraph() as WParagraph;
            string s = ResolveApplicationDataPath("Northwind_logo.png", "Content\\DocIO");

            headerPar.AppendPicture(System.Drawing.Image.FromFile(s));
            //Set Image size.
            (headerPar.Items[0] as WPicture).Width  = 232.5f;
            (headerPar.Items[0] as WPicture).Height = 54.75f;
            // Inserting text to the table second cell.
            headerPar = table[0, 1].AddParagraph() as WParagraph;
            IWTextRange txt = headerPar.AppendText("Company Headquarters,\n2501 Aerial Center Parkway,\nSuite 110, Morrisville, NC 27560,\nTEL 1-888-936-8638.");

            txt.CharacterFormat.FontSize                  = 12;
            txt.CharacterFormat.CharacterSpacing          = 1.7f;
            headerPar.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;

            // Add a footer paragraph text to the document.
            WParagraph footerPar = new WParagraph(doc);

            footerPar.ParagraphFormat.Tabs.AddTab(523f, TabJustification.Right, TabLeader.NoLeader);
            // Add text.
            footerPar.AppendText("Copyright Northwind Inc. 2001 - 2017");
            // Add page and Number of pages field to the document.
            footerPar.AppendText("\tPage ");
            IWField ff = footerPar.AppendField("Page", FieldType.FieldPage);

            section1.HeadersFooters.Footer.Paragraphs.Add(footerPar);

            #region Page Number Settings
            section1.PageSetup.RestartPageNumbering = true;
            section1.PageSetup.PageStartingNumber   = 1;
            section1.PageSetup.PageNumberStyle      = PageNumberStyle.Arabic;
            #endregion Page Number Settings
        }
Beispiel #17
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            WordDocument document = new WordDocument();

            WSection section = document.AddSection() as WSection;

            //Set Margin of the section
            section.PageSetup.Margins.All = 72;
            WParagraph para = section.AddParagraph() as WParagraph;

            section.AddColumn(100, 100);
            section.AddColumn(100, 100);
            section.MakeColumnsEqual();

            #region Built-in styles
            # region List Style
Beispiel #18
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            // Creating a new document.
            WordDocument document = new WordDocument();

            WSection section = document.AddSection() as WSection;

            //Set Margin of the section
            section.PageSetup.Margins.All = 72;
            WParagraph para = section.AddParagraph() as WParagraph;

            section.AddColumn(100, 100);
            section.AddColumn(100, 100);
            section.MakeColumnsEqual();

            #region Built-in styles
            # region List Style
 /// <summary>
 /// Replaces merge field with HTML string by using MergeFieldEventHandler.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 public static void MergeFieldEvent(object sender, MergeFieldEventArgs args)
 {
     if (args.TableName.Equals("HTML"))
     {
         if (args.FieldName.Equals("ProductList"))
         {
             string     text       = args.FieldValue as string;
             WParagraph paragraph  = args.CurrentMergeField.OwnerParagraph;
             int        paraIndex  = paragraph.OwnerTextBody.ChildEntities.IndexOf(paragraph);
             int        fieldIndex = paragraph.ChildEntities.IndexOf(args.CurrentMergeField);
             //Appends HTML string at the specified position of the document body contents
             paragraph.OwnerTextBody.InsertXHTML(args.FieldValue.ToString(), paraIndex, fieldIndex);
             //Resets the field value
             args.Text = string.Empty;
         }
     }
 }
 /// <summary>
 /// Append HTML to paragraph.
 /// </summary>
 private static void InsertHtml()
 {
     //Iterates through each item in the dictionary.
     foreach (KeyValuePair <WParagraph, Dictionary <int, string> > dictionaryItems in paraToInsertHTML)
     {
         WParagraph paragraph            = dictionaryItems.Key as WParagraph;
         Dictionary <int, string> values = dictionaryItems.Value as Dictionary <int, string>;
         //Iterates through each value in the dictionary.
         foreach (KeyValuePair <int, string> valuePair in values)
         {
             int    index      = valuePair.Key;
             string fieldValue = valuePair.Value;
             //Inserts HTML string at the same position of mergefield in Word document.
             paragraph.OwnerTextBody.InsertXHTML(fieldValue, paragraph.OwnerTextBody.ChildEntities.IndexOf(paragraph), index);
         }
     }
     paraToInsertHTML.Clear();
 }
Beispiel #21
0
        private static void IterateTextBody(WTextBody textBody)
        {
            for (int i = 0; i < textBody.ChildEntities.Count; i++)
            {
                IEntity bodyItemEntity = textBody.ChildEntities[i];
                switch (bodyItemEntity.EntityType)
                {
                case EntityType.Paragraph:
                    WParagraph paragraph = bodyItemEntity as WParagraph;
                    break;

                case EntityType.Table:
                    WTable table = bodyItemEntity as WTable;
                    IterateTable(table);
                    break;
                }
            }
        }
 /// <summary>
 /// Replaces merge field with HTML string by using MergeFieldEventHandler.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 public static void MergeFieldEvent(object sender, MergeFieldEventArgs args)
 {
     if (args.TableName.Equals("HTML"))
     {
         if (args.FieldName.Equals("ProductList"))
         {
             //Gets the current merge field owner paragraph.
             WParagraph paragraph = args.CurrentMergeField.OwnerParagraph;
             //Gets the current merge field index in the current paragraph.
             int mergeFieldIndex = paragraph.ChildEntities.IndexOf(args.CurrentMergeField);
             //Maintain HTML in collection.
             Dictionary <int, string> fieldValues = new Dictionary <int, string>();
             fieldValues.Add(mergeFieldIndex, args.FieldValue.ToString());
             //Maintain paragraph in collection.
             paraToInsertHTML.Add(paragraph, fieldValues);
             //Set field value as empty.
             args.Text = string.Empty;
         }
     }
 }
        /// <summary>
        /// Removes empty paragraphs from the end of Word document.
        /// </summary>
        /// <param name="document">The Word document</param>
        private static void RemoveEmptyPage(WordDocument document)
        {
            WTextBody textBody = document.LastSection.Body;

            //A flag to determine any renderable item found in the Word document.
            bool IsRenderableItem = false;

            //Iterates text body items.
            for (int itemIndex = textBody.ChildEntities.Count - 1; itemIndex >= 0 && !IsRenderableItem; itemIndex--)
            {
                //Check item is empty paragraph and removes it.
                if (textBody.ChildEntities[itemIndex] is WParagraph)
                {
                    WParagraph paragraph = textBody.ChildEntities[itemIndex] as WParagraph;
                    //Iterates into paragraph
                    for (int pIndex = paragraph.Items.Count - 1; pIndex >= 0; pIndex--)
                    {
                        ParagraphItem paragraphItem = paragraph.Items[pIndex];

                        //If page break found in end of document, then remove it to preserve contents in same page
                        if ((paragraphItem is Break && (paragraphItem as Break).BreakType == BreakType.PageBreak))
                        {
                            paragraph.Items.RemoveAt(pIndex);
                        }

                        //Check paragraph contains any renderable items.
                        else if (!(paragraphItem is BookmarkStart || paragraphItem is BookmarkEnd))
                        {
                            IsRenderableItem = true;
                            //Found renderable item and break the iteration.
                            break;
                        }
                    }
                    //Remove empty paragraph and the paragraph with bookmarks only
                    if (paragraph.Items.Count == 0 || !IsRenderableItem)
                    {
                        textBody.ChildEntities.RemoveAt(itemIndex);
                    }
                }
            }
        }
Beispiel #24
0
 static void Main(string[] args)
 {
     using (WordDocument document = new WordDocument())
     {
         document.EnsureMinimal();
         document.LastSection.PageSetup.Margins.All = 72;
         WParagraph para = document.LastParagraph;
         para.AppendText("Essential DocIO - Table of Contents");
         para.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;
         para.ApplyStyle(BuiltinStyle.Heading4);
         para = document.LastSection.AddParagraph() as WParagraph;
         para = document.LastSection.AddParagraph() as WParagraph;
         //Insert TOC field in the Word document.
         TableOfContent toc = para.AppendTOC(1, 3);
         //Sets the heading levels 1 to 3, to include in TOC.
         toc.LowerHeadingLevel = 1;
         toc.UpperHeadingLevel = 3;
         //Adds content to the Word document with built-in heading styles.
         WSection   section = document.LastSection;
         WParagraph newPara = section.AddParagraph() as WParagraph;
         newPara.AppendBreak(BreakType.PageBreak);
         AddHeading(section, BuiltinStyle.Heading1, "Document with built-in heading styles", "This is the built-in heading 1 style. This sample demonstrates the TOC insertion in a word document. Note that DocIO can insert TOC field in a word document. It can refresh or update TOC field by using UpdateTableOfContents method. MS Word refreshes the TOC field after insertion. Please update the field or press F9 key to refresh the TOC.");
         AddHeading(section, BuiltinStyle.Heading2, "Section 1", "This is the built-in heading 2 style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");
         AddHeading(section, BuiltinStyle.Heading3, "Paragraph 1", "This is the built-in heading 3 style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text.");
         AddHeading(section, BuiltinStyle.Heading3, "Paragraph 2", "This is the built-in heading 3 style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph.");
         //Adds a new section to the Word document.
         section = document.AddSection() as WSection;
         section.PageSetup.Margins.All = 72;
         section.BreakCode             = SectionBreakCode.NewPage;
         AddHeading(section, BuiltinStyle.Heading2, "Section 2", "This is the built-in heading 2 style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");
         AddHeading(section, BuiltinStyle.Heading3, "Paragraph 1", "This is the built-in heading 3 style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text.");
         AddHeading(section, BuiltinStyle.Heading3, "Paragraph 2", "This is the built-in heading 3 style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph.");
         //Updates the table of contents.
         document.UpdateTableOfContents();
         //Saves the file in the given path
         Stream docStream = File.Create(Path.GetFullPath(@"../../../TOC-creation.docx"));
         document.Save(docStream, FormatType.Docx);
         docStream.Dispose();
     }
 }
        public ActionResult Styles(string Group1, string Group2)
        {
            if (Group1 == null)
            {
                return(View());
            }
            WordDocument document = null;

            #region Built-in Style
            if (Group1 == "Built-in")
            {
                document = new WordDocument();
                WSection   section = document.AddSection() as WSection;
                WParagraph para    = section.AddParagraph() as WParagraph;

                section.AddColumn(100, 100);
                section.AddColumn(100, 100);
                section.MakeColumnsEqual();

                # region List Style
                //List
                //para = section.AddParagraph() as WParagraph;
                para.AppendText("This para is written with style List").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
                para = section.AddParagraph() as WParagraph;
                para.ApplyStyle(BuiltinStyle.List);
                para.AppendText("Google Chrome\n");
                para.AppendText("Mozilla Firefox\n");
                para.AppendText("Internet Explorer");

                //List5 style
                para = section.AddParagraph() as WParagraph;
                para.AppendText("\nThis para is written with style List5").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
                para = section.AddParagraph() as WParagraph;
                para.ApplyStyle(BuiltinStyle.List5);
                para.AppendText("Google Chrome\n");
                para.AppendText("Mozilla Firefox\n");
                para.AppendText("Internet Explorer");
                # endregion

                # region ListNumber Style
Beispiel #26
0
        /// <summary>
        /// Change tab leader for table of contents in the Word document.
        /// </summary>
        /// <param name="toc"></param>
        private static void ChangeTabLeaderForTableOfContents(TableOfContent toc, TabLeader tabLeader)
        {
            //Inserts the bookmark start before the TOC instance.
            BookmarkStart bkmkStart = new BookmarkStart(toc.Document, "tableOfContent");

            toc.OwnerParagraph.Items.Insert(toc.OwnerParagraph.Items.IndexOf(toc), bkmkStart);

            Entity lastItem = FindLastTOCItem(toc);

            //Insert the bookmark end to next of TOC last item.
            BookmarkEnd bkmkEnd   = new BookmarkEnd(toc.Document, "tableOfContent");
            WParagraph  paragraph = lastItem.Owner as WParagraph;

            paragraph.Items.Insert(paragraph.Items.IndexOf(lastItem) + 1, bkmkEnd);

            //Creates the bookmark navigator instance to access the bookmark
            BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(toc.Document);

            //Moves the virtual cursor to the location before the end of the bookmark "tableOfContent"
            bookmarkNavigator.MoveToBookmark("tableOfContent");
            //Gets the bookmark content
            TextBodyPart part = bookmarkNavigator.GetBookmarkContent();

            //Iterates the items from the bookmark to change the spacing in the table of content
            for (int i = 0; i < part.BodyItems.Count; i++)
            {
                paragraph = part.BodyItems[i] as WParagraph;
                //Sets the tab leader
                if (paragraph.ParagraphFormat.Tabs.Count != 0)
                {
                    paragraph.ParagraphFormat.Tabs[0].TabLeader = tabLeader;
                }
            }

            //Remove the bookmark which we add to get the paragraphs in the table of contents
            Bookmark bookmark = toc.Document.Bookmarks.FindByName("tableOfContent");

            toc.Document.Bookmarks.Remove(bookmark);
        }
        public IActionResult EditEquation(string Button, string Group1)
        {
            if (Button == null)
            {
                return(View());
            }
            string basePath    = _hostingEnvironment.WebRootPath;
            string dataPath    = basePath + @"/DocIO/Mathematical Equation.docx";
            string contenttype = "application/vnd.ms-word.document.12";
            // Load Template document stream.
            FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            if (Button == "View Template")
            {
                return(File(fileStream, contenttype, "Mathematical Equation.docx"));
            }

            // Creates an empty Word document instance.
            WordDocument document = new WordDocument();

            // Opens template document.
            document.Open(fileStream, FormatType.Docx);
            fileStream.Dispose();
            fileStream = null;
            //Gets the last section in the document
            WSection section = document.LastSection;
            //Gets paragraph from Word document
            WParagraph paragraph = document.LastSection.Body.ChildEntities[3] as WParagraph;

            //Gets MathML from the paragraph
            WMath math = paragraph.ChildEntities[0] as WMath;
            //Gets the radical equation
            IOfficeMathRadical mathRadical = math.MathParagraph.Maths[0].Functions[1] as IOfficeMathRadical;
            //Gets the fraction equation in radical
            IOfficeMathFraction mathFraction = mathRadical.Equation.Functions[0] as IOfficeMathFraction;
            //Gets the n-array in fraction
            IOfficeMathNArray mathNAry = mathFraction.Numerator.Functions[0] as IOfficeMathNArray;
            //Gets the math script in n-array
            IOfficeMathScript mathScript = mathNAry.Equation.Functions[0] as IOfficeMathScript;
            //Gets the delimiter in math script
            IOfficeMathDelimiter mathDelimiter = mathScript.Equation.Functions[0] as IOfficeMathDelimiter;

            //Gets the math script in delimiter
            mathScript = mathDelimiter.Equation[0].Functions[0] as IOfficeMathScript;
            //Gets the math run element in math script
            IOfficeMathRunElement mathParaItem = mathScript.Equation.Functions[0] as IOfficeMathRunElement;

            //Modifies the math text value
            (mathParaItem.Item as WTextRange).Text = "x";

            //Gets the math bar in delimiter
            IOfficeMathBar mathBar = mathDelimiter.Equation[0].Functions[2] as IOfficeMathBar;

            //Gets the math run element in bar
            mathParaItem = mathBar.Equation.Functions[0] as IOfficeMathRunElement;
            //Modifies the math text value
            (mathParaItem.Item as WTextRange).Text = "x";

            //Gets the paragraph from Word document
            paragraph = document.LastSection.Body.ChildEntities[6] as WParagraph;
            //Gets MathML from the paragraph
            math = paragraph.ChildEntities[0] as WMath;
            //Gets the math script equation
            mathScript = math.MathParagraph.Maths[0].Functions[0] as IOfficeMathScript;
            //Gets the math run element in math script
            mathParaItem = mathScript.Equation.Functions[0] as IOfficeMathRunElement;
            //Modifies the math text value
            (mathParaItem.Item as WTextRange).Text = "x";

            //Gets the paragraph from Word document
            paragraph = document.LastSection.Body.ChildEntities[7] as WParagraph;
            //Gets MathML from the paragraph
            WMath math2 = paragraph.ChildEntities[0] as WMath;

            //Gets bar equation
            mathBar = math2.MathParagraph.Maths[0].Functions[0] as IOfficeMathBar;
            //Gets the math run element in bar
            mathParaItem = mathBar.Equation.Functions[0] as IOfficeMathRunElement;
            //Gets the math text
            (mathParaItem.Item as WTextRange).Text = "x";

            string       filename = "";
            MemoryStream ms       = new MemoryStream();

            #region Document SaveOption
            if (Group1 == "WordDocx")
            {
                filename    = "EditEquation.docx";
                contenttype = "application/msword";
                document.Save(ms, FormatType.Docx);
            }
            else
            {
                filename    = "EditEquation.pdf";
                contenttype = "application/pdf";
                DocIORenderer renderer = new DocIORenderer();
                renderer.ConvertToPDF(document).Save(ms);
            }
            #endregion Document SaveOption
            document.Close();
            ms.Position = 0;
            return(File(ms, contenttype, filename));
        }
        public ActionResult FormatTable(string Group1)
        {
            if (Group1 == null)
            {
                return(View());
            }
            // Create a new document.
            WordDocument document = new WordDocument();

            // Adding a new section to the document.
            IWSection section = document.AddSection();

            section.PageSetup.DifferentFirstPage = true;
            IWTextRange textRange;
            IWParagraph paragraph = section.AddParagraph();

            // --------------------------------------------
            // Table in page header
            // --------------------------------------------


            IWParagraph hParagraph = new WParagraph(document);

            hParagraph.AppendText("Header text\r\n").CharacterFormat.FontSize = 14;

            section.HeadersFooters.FirstPageHeader.Paragraphs.Add(hParagraph);


            IWTable hTable = document.LastSection.HeadersFooters.FirstPageHeader.AddTable();

            hTable.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
            hTable.TableFormat.Paddings.All       = 5.4f;
            hTable.ResetCells(2, 2);

            hTable[0, 0].AddParagraph().AppendText("1");
            hTable[0, 1].AddParagraph().AppendText("2");
            hTable[1, 0].AddParagraph().AppendText("3");
            hTable[1, 1].AddParagraph().AppendText("4");


            // --------------------------------------------
            // Tiny table
            // --------------------------------------------

            paragraph = section.AddParagraph();

            paragraph.AppendText("Tiny table\r\n").CharacterFormat.FontSize = 14;
            paragraph = section.AddParagraph();
            WTextBody textBody = section.Body;
            IWTable   table    = textBody.AddTable();

            table.ResetCells(2, 2);
            table.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
            table.TableFormat.Paddings.All       = 5.4f;
            WTableRow row_0 = table.Rows[0];

            row_0.Cells[0].AddParagraph().AppendText("A");
            row_0.Cells[0].AddParagraph().AppendText("AA");
            row_0.Cells[0].AddParagraph().AppendText("AAA");

            WTableRow row_1 = table.Rows[1];

            row_1.Cells[1].AddParagraph().AppendText("B");
            row_1.Cells[1].AddParagraph().AppendText("BB\r\nBBB");
            row_1.Cells[1].AddParagraph().AppendText("BBB");

            textBody.AddParagraph().AppendText("Text after table...").CharacterFormat.FontSize = 14;

            // --------------------------------------------
            // Table with different formatting
            // --------------------------------------------

            section.AddParagraph();
            paragraph = section.AddParagraph();
            paragraph.AppendText("Table with different formatting\r\n").CharacterFormat.FontSize = 14;
            paragraph = section.AddParagraph();
            textBody  = section.Body;
            table     = textBody.AddTable();
            table.ResetCells(3, 3);

            /* ------- First Row -------- */

            WTableRow row0 = table.Rows[0];

            paragraph = (IWParagraph)row0.Cells[0].AddParagraph();
            textRange = paragraph.AppendText("1");
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left;
            textRange.CharacterFormat.FontName            = "Arial";
            textRange.CharacterFormat.Bold             = true;
            textRange.CharacterFormat.FontSize         = 14f;
            row0.Cells[0].CellFormat.Borders.LineWidth = 2f;
            row0.Cells[0].CellFormat.Borders.Color     = Color.Magenta;

            paragraph = (IWParagraph)row0.Cells[1].AddParagraph();
            textRange = paragraph.AppendText("2");
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
            textRange.CharacterFormat.Emboss            = true;
            textRange.CharacterFormat.FontSize          = 15f;
            row0.Cells[1].CellFormat.Borders.LineWidth  = 1.3f;
            row0.Cells[1].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DoubleWave;

            paragraph = (IWParagraph)row0.Cells[2].AddParagraph();
            textRange = paragraph.AppendText("3");
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left;
            textRange.CharacterFormat.Engrave             = true;
            textRange.CharacterFormat.FontSize            = 15f;
            row0.Cells[2].CellFormat.Borders.BorderType   = Syncfusion.DocIO.DLS.BorderStyle.Emboss3D;

            /* ------- Second Row -------- */

            WTableRow row1 = table.Rows[1];

            paragraph = (IWParagraph)row1.Cells[0].AddParagraph();
            textRange = paragraph.AppendText("4");
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            textRange.CharacterFormat.SmallCaps           = true;
            textRange.CharacterFormat.FontName            = "Comic Sans MS";
            textRange.CharacterFormat.FontSize            = 16;
            row1.Cells[0].CellFormat.Borders.LineWidth    = 2f;
            row1.Cells[0].CellFormat.Borders.BorderType   = Syncfusion.DocIO.DLS.BorderStyle.DashDotStroker;

            paragraph = (IWParagraph)row1.Cells[1].AddParagraph();
            textRange = paragraph.AppendText("5");
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            textRange.CharacterFormat.FontName            = "Times New Roman";
            textRange.CharacterFormat.Shadow = true;
            textRange.CharacterFormat.TextBackgroundColor = Color.Orange;
            textRange.CharacterFormat.FontSize            = 15f;
            row1.Cells[1].CellFormat.Borders.LineWidth    = 2f;
            row1.Cells[1].CellFormat.Borders.Color        = Color.Brown;

            paragraph = (IWParagraph)row1.Cells[2].AddParagraph();
            textRange = paragraph.AppendText("6");
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            textRange.CharacterFormat.Bold             = true;
            textRange.CharacterFormat.FontSize         = 14f;
            row1.Cells[2].CellFormat.BackColor         = Color.FromArgb(51, 51, 101);
            row1.Cells[2].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

            /* ------- Third Row -------- */

            WTableRow row2 = table.Rows[2];

            paragraph = (IWParagraph)row2.Cells[0].AddParagraph();
            textRange = paragraph.AppendText("7");
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
            textRange.CharacterFormat.FontSize            = 13f;
            row2.Cells[0].CellFormat.Borders.LineWidth    = 1.5f;
            row2.Cells[0].CellFormat.Borders.BorderType   = Syncfusion.DocIO.DLS.BorderStyle.DashLargeGap;

            paragraph = (IWParagraph)row2.Cells[1].AddParagraph();
            textRange = paragraph.AppendText("8");
            textRange.CharacterFormat.TextColor         = Color.Blue;
            textRange.CharacterFormat.FontSize          = 16f;
            row2.Cells[1].CellFormat.Borders.LineWidth  = 3f;
            row2.Cells[1].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Wave;

            paragraph = (IWParagraph)row2.Cells[2].AddParagraph();
            textRange = paragraph.AppendText("9");
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
            row2.Cells[2].CellFormat.Borders.LineWidth    = 2f;
            row2.Cells[2].CellFormat.Borders.Color        = Color.Cyan;
            row2.Cells[2].CellFormat.Borders.Shadow       = true;
            row2.Cells[2].CellFormat.Borders.Space        = 20;

            // --------------------------------------------
            // Table Cell Merging.
            // --------------------------------------------

            section.AddParagraph();
            paragraph = section.AddParagraph();
            paragraph.AppendText("Table Cell Merging...").CharacterFormat.FontSize = 14;
            section.AddParagraph();
            paragraph = section.AddParagraph();
            textBody  = section.Body;

            // Adding a new Table to the textbody.
            table = textBody.AddTable();

            RowFormat format = new RowFormat();

            format.Paddings.All       = 5;
            format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Dot;
            format.Borders.LineWidth  = 2;

            // Inserting rows to the table.
            table.ResetCells(6, 6, format, 80);

            // Table formatting with cell merging.
            table.Rows[0].Cells[0].CellFormat.HorizontalMerge   = CellMerge.Start;
            table.Rows[0].Cells[1].CellFormat.HorizontalMerge   = CellMerge.Continue;
            table.Rows[0].Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
            table.Rows[0].Cells[0].CellFormat.BackColor         = Color.FromArgb(218, 230, 246);
            IWParagraph par = table.Rows[0].Cells[0].AddParagraph();

            par.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            par.AppendText("Horizontal Merge").CharacterFormat.Bold = true;


            table.Rows[2].Cells[3].CellFormat.VerticalMerge = CellMerge.Start;
            table.Rows[3].Cells[3].CellFormat.VerticalMerge = CellMerge.Continue;

            table.Rows[2].Cells[3].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
            par = table.Rows[2].Cells[3].AddParagraph();
            table.Rows[2].Cells[3].CellFormat.BackColor           = Color.FromArgb(252, 172, 85);
            par.ParagraphFormat.HorizontalAlignment               = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            par.AppendText("Vertical Merge").CharacterFormat.Bold = true;

            #region Table Cell Spacing.
            // --------------------------------------------
            // Table Cell Spacing.
            // --------------------------------------------

            section.AddParagraph();
            paragraph = section.AddParagraph();
            paragraph.AppendText("Table Cell spacing...").CharacterFormat.FontSize = 14;

            section.AddParagraph();
            paragraph = section.AddParagraph();
            textBody  = section.Body;

            // Adding a new Table to the textbody.
            table = textBody.AddTable();
            table.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
            table.TableFormat.Paddings.All       = 5.4f;
            format = new RowFormat();

            format.Paddings.All       = 5;
            format.CellSpacing        = 2;
            format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DotDash;
            format.IsBreakAcrossPages = true;
            table.ResetCells(25, 5, format, 90);
            IWTextRange text;
            table.Rows[0].IsHeader = true;

            for (int i = 0; i < table.Rows[0].Cells.Count; i++)
            {
                paragraph = table[0, i].AddParagraph() as WParagraph;
                paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
                text = paragraph.AppendText(string.Format("Header {0}", i + 1));
                text.CharacterFormat.Font        = new Font("Bitstream Vera Serif", 10);
                text.CharacterFormat.Bold        = true;
                text.CharacterFormat.TextColor   = Color.FromArgb(0, 21, 84);
                table[0, i].CellFormat.BackColor = Color.FromArgb(203, 211, 226);
            }

            for (int i = 1; i < table.Rows.Count; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    paragraph = table[i, j].AddParagraph() as WParagraph;
                    paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;

                    text = paragraph.AppendText(string.Format("Cell {0} , {1}", i, j + 1));
                    text.CharacterFormat.TextColor = Color.FromArgb(242, 151, 50);
                    text.CharacterFormat.Bold      = true;
                    if (i % 2 != 1)
                    {
                        table[i, j].CellFormat.BackColor = Color.FromArgb(231, 235, 245);
                    }
                    else
                    {
                        table[i, j].CellFormat.BackColor = Color.FromArgb(246, 249, 255);
                    }
                }
            }
            #endregion Table Cell Spacing.

            #region Nested Table
            // --------------------------------------------
            // Nested Table.
            // --------------------------------------------

            section.AddParagraph();
            paragraph = section.AddParagraph();
            paragraph.ParagraphFormat.PageBreakBefore = true;
            paragraph.AppendText("Nested Table...").CharacterFormat.FontSize = 14;

            section.AddParagraph();
            paragraph = section.AddParagraph();
            textBody  = section.Body;

            // Adding a new Table to the textbody.
            table = textBody.AddTable();

            format = new RowFormat();
            format.Paddings.All       = 5;
            format.CellSpacing        = 2.5f;
            format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DotDash;
            table.ResetCells(5, 3, format, 100);

            for (int i = 0; i < table.Rows[0].Cells.Count; i++)
            {
                paragraph = table[0, i].AddParagraph() as WParagraph;
                paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
                text = paragraph.AppendText(string.Format("Header {0}", i + 1));
                text.CharacterFormat.Font        = new Font("Bitstream Vera Serif", 10);
                text.CharacterFormat.Bold        = true;
                text.CharacterFormat.TextColor   = Color.FromArgb(0, 21, 84);
                table[0, i].CellFormat.BackColor = Color.FromArgb(242, 151, 50);
            }
            table[0, 2].Width = 200;
            for (int i = 1; i < table.Rows.Count; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    paragraph = table[i, j].AddParagraph() as WParagraph;
                    paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;

                    if ((i == 2) && (j == 2))
                    {
                        text = paragraph.AppendText("Nested Table");
                    }

                    else
                    {
                        text = paragraph.AppendText(string.Format("Cell {0} , {1}", i, j + 1));
                    }

                    if ((j == 2))
                    {
                        table[i, j].Width = 200;
                    }

                    text.CharacterFormat.TextColor = Color.FromArgb(242, 151, 50);
                    text.CharacterFormat.Bold      = true;
                }
            }

            // Adding a nested Table.
            IWTable nestTable = table[2, 2].AddTable();

            format = new RowFormat();

            format.Borders.BorderType  = Syncfusion.DocIO.DLS.BorderStyle.DotDash;
            format.HorizontalAlignment = RowAlignment.Center;
            nestTable.ResetCells(3, 3, format, 45);

            for (int i = 0; i < nestTable.Rows.Count; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    paragraph = nestTable[i, j].AddParagraph() as WParagraph;
                    paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;

                    nestTable[i, j].CellFormat.BackColor = Color.FromArgb(231, 235, 245);
                    text = paragraph.AppendText(string.Format("Cell {0} , {1}", i, j + 1));
                    text.CharacterFormat.TextColor = Color.Black;
                    text.CharacterFormat.Bold      = true;
                }
            }
            #endregion Nested Table
            #region Table with Images
            string dataPath = ResolveApplicationDataPath("", "Content\\DocIO");

            //Add a new section to the document.
            section = document.AddSection();
            //Add paragraph to the section.
            paragraph = section.AddParagraph();
            //Writing text.
            textRange = paragraph.AppendText("Table with Images");
            textRange.CharacterFormat.FontSize  = 13f;
            textRange.CharacterFormat.TextColor = Color.DarkBlue;
            textRange.CharacterFormat.Bold      = true;

            //Add paragraph to the section.
            section.AddParagraph();
            paragraph = section.AddParagraph();

            text = null;

            //Adding a new Table to the paragraph.
            table = section.Body.AddTable();
            table.ResetCells(1, 3);

            //Adding rows to the table.
            WTableRow row = table.Rows[0];
            //Set heading row height
            row.Height = 25f;
            //set heading values to the Table.
            for (int i = 0; i < 3; i++)
            {
                //Add paragraph for writing Text to the cells.
                paragraph = (IWParagraph)row.Cells[i].AddParagraph();
                //Set Horizontal Alignment as Center.
                paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
                //Writing Row Heading
                switch (i)
                {
                case 0: text           = paragraph.AppendText("SNO");
                    row.Cells[i].Width = 50f; break;

                case 1: text = paragraph.AppendText("Drinks"); break;

                case 2: text = paragraph.AppendText("Showcase Image"); row.Cells[i].Width = 200f; break;
                }
                //Set row Heading formatting
                text.CharacterFormat.Bold      = true;
                text.CharacterFormat.FontName  = "Cambria";
                text.CharacterFormat.FontSize  = 11f;
                text.CharacterFormat.TextColor = Color.White;

                //Set row cells formatting
                row.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                row.Cells[i].CellFormat.BackColor         = Color.FromArgb(157, 161, 190);

                row.Cells[i].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
            }

            int sno = 1;
            //Writing Sno, Product name and Product Images to the Table.

            row1 = table.AddRow(false);

            //Writing SNO to the table with formatting text.
            paragraph = (IWParagraph)row1.Cells[0].AddParagraph();
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            text = paragraph.AppendText(sno.ToString());
            text.CharacterFormat.Bold     = true;
            text.CharacterFormat.FontSize = 10f;
            row1.Cells[0].CellFormat.VerticalAlignment  = VerticalAlignment.Middle;
            row1.Cells[0].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
            row1.Cells[0].CellFormat.BackColor          = Color.FromArgb(217, 223, 239);
            //Writing Product Name to the table with Formatting.
            paragraph = (IWParagraph)row1.Cells[1].AddParagraph();
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            text = paragraph.AppendText("Apple Juice");
            text.CharacterFormat.Bold                   = true;
            text.CharacterFormat.FontSize               = 10f;
            text.CharacterFormat.TextColor              = Color.FromArgb(50, 65, 124);
            row1.Cells[1].CellFormat.VerticalAlignment  = VerticalAlignment.Middle;
            row1.Cells[1].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
            row1.Cells[1].CellFormat.BackColor          = Color.FromArgb(217, 223, 239);

            //Writing Product Images to the Table.
            paragraph = (IWParagraph)row1.Cells[2].AddParagraph();
            paragraph.AppendPicture(Image.FromFile(dataPath + "Apple Juice.png"));
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            row1.Cells[2].CellFormat.VerticalAlignment    = VerticalAlignment.Middle;
            row1.Cells[2].CellFormat.Borders.BorderType   = Syncfusion.DocIO.DLS.BorderStyle.Single;
            row1.Cells[2].CellFormat.BackColor            = Color.FromArgb(217, 223, 239);
            sno++;
            row1 = table.AddRow(false);

            //Writing SNO to the table with formatting text.
            paragraph = (IWParagraph)row1.Cells[0].AddParagraph();
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            text = paragraph.AppendText(sno.ToString());
            text.CharacterFormat.Bold     = true;
            text.CharacterFormat.FontSize = 10f;
            row1.Cells[0].CellFormat.VerticalAlignment  = VerticalAlignment.Middle;
            row1.Cells[0].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
            row1.Cells[0].CellFormat.BackColor          = Color.FromArgb(217, 223, 239);
            //Writing Product Name to the table with Formatting.
            paragraph = (IWParagraph)row1.Cells[1].AddParagraph();
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            text = paragraph.AppendText("Grape Juice");
            text.CharacterFormat.Bold                   = true;
            text.CharacterFormat.FontSize               = 10f;
            text.CharacterFormat.TextColor              = Color.FromArgb(50, 65, 124);
            row1.Cells[1].CellFormat.VerticalAlignment  = VerticalAlignment.Middle;
            row1.Cells[1].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
            row1.Cells[1].CellFormat.BackColor          = Color.FromArgb(217, 223, 239);

            //Writing Product Images to the Table.
            paragraph = (IWParagraph)row1.Cells[2].AddParagraph();
            paragraph.AppendPicture(Image.FromFile(dataPath + "Grape Juice.png"));
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            row1.Cells[2].CellFormat.VerticalAlignment    = VerticalAlignment.Middle;
            row1.Cells[2].CellFormat.Borders.BorderType   = Syncfusion.DocIO.DLS.BorderStyle.Single;
            row1.Cells[2].CellFormat.BackColor            = Color.FromArgb(217, 223, 239);
            sno++;
            row1 = table.AddRow(false);

            //Writing SNO to the table with formatting text.
            paragraph = (IWParagraph)row1.Cells[0].AddParagraph();
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            text = paragraph.AppendText(sno.ToString());
            text.CharacterFormat.Bold     = true;
            text.CharacterFormat.FontSize = 10f;
            row1.Cells[0].CellFormat.VerticalAlignment  = VerticalAlignment.Middle;
            row1.Cells[0].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
            row1.Cells[0].CellFormat.BackColor          = Color.FromArgb(217, 223, 239);
            //Writing Product Name to the table with Formatting.
            paragraph = (IWParagraph)row1.Cells[1].AddParagraph();
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            text = paragraph.AppendText("Hot Soup");
            text.CharacterFormat.Bold                   = true;
            text.CharacterFormat.FontSize               = 10f;
            text.CharacterFormat.TextColor              = Color.FromArgb(50, 65, 124);
            row1.Cells[1].CellFormat.VerticalAlignment  = VerticalAlignment.Middle;
            row1.Cells[1].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
            row1.Cells[1].CellFormat.BackColor          = Color.FromArgb(217, 223, 239);

            //Writing Product Images to the Table.
            paragraph = (IWParagraph)row1.Cells[2].AddParagraph();
            paragraph.AppendPicture(Image.FromFile(dataPath + "Hot Soup.png"));
            paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            row1.Cells[2].CellFormat.VerticalAlignment    = VerticalAlignment.Middle;
            row1.Cells[2].CellFormat.Borders.BorderType   = Syncfusion.DocIO.DLS.BorderStyle.Single;
            row1.Cells[2].CellFormat.BackColor            = Color.FromArgb(217, 223, 239);
            sno++;
            #endregion Table with Images

            //Save as .doc format
            if (Group1 == "WordDoc")
            {
                return(document.ExportAsActionResult("Sample.doc", FormatType.Doc, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
            }
            //Save as .docx format
            else if (Group1 == "WordDocx")
            {
                return(document.ExportAsActionResult("Sample.docx", FormatType.Docx, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
            }
            // Save as WordML(.xml) format
            else if (Group1 == "WordML")
            {
                return(document.ExportAsActionResult("Sample.xml", FormatType.WordML, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment));
            }
            //Save as .pdf format
            else if (Group1 == "Pdf")
            {
                DocToPDFConverter converter = new DocToPDFConverter();
                PdfDocument       pdfDoc    = converter.ConvertToPDF(document);

                return(pdfDoc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
            return(View());
        }
Beispiel #29
0
        public ActionResult PieChart(string Group1)
        {
            if (Group1 == null)
            {
                return(View());
            }
            string basePath = _hostingEnvironment.WebRootPath;
            string datapath = basePath + @"/DocIO/PieChart.docx";
            //A new document is created.
            FileStream   fileStream = new FileStream(datapath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            WordDocument document   = new WordDocument(fileStream, FormatType.Docx);
            //Create MailMergeDataTable
            MailMergeDataTable mailMergeDataTable = GetMailMergeDataTableProductDetails();

            //Merge the product table in the Word document
            document.MailMerge.ExecuteGroup(mailMergeDataTable);
            //Find the Placeholder of Pie chart to insert
            TextSelection selection = document.Find("<Pie Chart>", false, false);
            WParagraph    paragraph = selection.GetAsOneRange().OwnerParagraph;

            paragraph.ChildEntities.Clear();
            //Create and Append chart to the paragraph
            WChart pieChart = paragraph.AppendChart(446, 270);

            //Set chart data
            pieChart.ChartType  = OfficeChartType.Pie;
            pieChart.ChartTitle = "Best Selling Products";
            pieChart.ChartTitleArea.FontName = "Calibri (Body)";
            pieChart.ChartTitleArea.Size     = 14;
            GetChartData(pieChart, 0);
            //Create a new chart series with the name “Sales”
            IOfficeChartSerie pieSeries = pieChart.Series.Add("Sales");

            pieSeries.Values = pieChart.ChartData[2, 2, 11, 2];
            //Setting data label
            pieSeries.DataPoints.DefaultDataPoint.DataLabels.IsPercentage = true;
            pieSeries.DataPoints.DefaultDataPoint.DataLabels.Position     = OfficeDataLabelPosition.Outside;
            //Setting background color
            pieChart.ChartArea.Fill.ForeColor           = Syncfusion.Drawing.Color.FromArgb(242, 242, 242);
            pieChart.PlotArea.Fill.ForeColor            = Syncfusion.Drawing.Color.FromArgb(242, 242, 242);
            pieChart.ChartArea.Border.LinePattern       = OfficeChartLinePattern.None;
            pieChart.PrimaryCategoryAxis.CategoryLabels = pieChart.ChartData[2, 1, 11, 1];

            string       filename    = "";
            string       contenttype = "";
            MemoryStream ms          = new MemoryStream();

            #region Document SaveOption
            if (Group1 == "WordDocx")
            {
                filename    = "Sample.docx";
                contenttype = "application/msword";
                document.Save(ms, FormatType.Docx);
            }
            else if (Group1 == "WordML")
            {
                filename    = "Sample.xml";
                contenttype = "application/msword";
                document.Save(ms, FormatType.WordML);
            }
            else
            {
                filename    = "Sample.pdf";
                contenttype = "application/pdf";
                DocIORenderer renderer = new DocIORenderer();
                renderer.ConvertToPDF(document).Save(ms);
            }
            #endregion Document SaveOption
            document.Close();
            ms.Position = 0;
            return(File(ms, contenttype, filename));
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            WordDocument doc = new WordDocument();

            doc.EnsureMinimal();

            WParagraph para = doc.LastParagraph;

            para.AppendText("Essential DocIO - Table of Contents");
            para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            para.ApplyStyle(BuiltinStyle.Heading4);

            para = doc.LastSection.AddParagraph() as WParagraph;
            para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
            para.ApplyStyle(BuiltinStyle.Heading4);

            if (!this.CheckBox7.Checked)
            {
                para.AppendText("Select TOC and press F9 to update the Table of Contents").CharacterFormat.HighlightColor = Color.Yellow;
            }

            para = doc.LastSection.AddParagraph() as WParagraph;
            string title = this.TextBox1.Text + "\n";

            para.AppendText(title);
            para.ApplyStyle(BuiltinStyle.Heading4);

            //Insert TOC
            TableOfContent toc = para.AppendTOC(1, 3);

            para.ApplyStyle(BuiltinStyle.Heading4);
            //Apply built-in paragraph formatting
            WSection section = doc.LastSection;

            if (this.RadioButton1.Checked)
            {
                #region Default Styles
                WParagraph newPara = section.AddParagraph() as WParagraph;
                newPara = section.AddParagraph() as WParagraph;
                newPara.AppendBreak(BreakType.PageBreak);
                WTextRange text = newPara.AppendText("Document with Default styles") as WTextRange;
                newPara.ApplyStyle(BuiltinStyle.Heading1);
                newPara = section.AddParagraph() as WParagraph;
                newPara.AppendText("This is the heading1 of built in style. This sample demonstrates the TOC insertion in a word document. Note that DocIO can only insert TOC field in a word document. It can not refresh or create TOC field. MS Word refreshes the TOC field after insertion. Please update the field or press F9 key to refresh the TOC.");

                section.AddParagraph();
                newPara = section.AddParagraph() as WParagraph;
                text    = newPara.AppendText("Section1") as WTextRange;
                newPara.ApplyStyle(BuiltinStyle.Heading2);
                newPara = section.AddParagraph() as WParagraph;
                newPara.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");

                section.AddParagraph();
                newPara = section.AddParagraph() as WParagraph;
                text    = newPara.AppendText("Paragraph1") as WTextRange;
                newPara.ApplyStyle(BuiltinStyle.Heading3);
                newPara = section.AddParagraph() as WParagraph;
                newPara.AppendText("This is the heading3 of built in style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text.");

                section.AddParagraph();
                newPara = section.AddParagraph() as WParagraph;
                text    = newPara.AppendText("Paragraph2") as WTextRange;
                newPara.ApplyStyle(BuiltinStyle.Heading3);
                newPara = section.AddParagraph() as WParagraph;
                newPara.AppendText("This is the heading3 of built in style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph.");

                section.AddParagraph();
                section           = doc.AddSection() as WSection;
                section.BreakCode = SectionBreakCode.NewPage;
                newPara           = section.AddParagraph() as WParagraph;
                text = newPara.AppendText("Section2") as WTextRange;
                newPara.ApplyStyle(BuiltinStyle.Heading2);
                newPara = section.AddParagraph() as WParagraph;
                newPara.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");

                section.AddParagraph();
                newPara = section.AddParagraph() as WParagraph;
                text    = newPara.AppendText("Paragraph1") as WTextRange;
                newPara.ApplyStyle(BuiltinStyle.Heading3);
                newPara = section.AddParagraph() as WParagraph;
                newPara.AppendText("This is the heading3 of built in style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text.");

                section.AddParagraph();
                newPara = section.AddParagraph() as WParagraph;
                text    = newPara.AppendText("Paragraph2") as WTextRange;
                newPara.ApplyStyle(BuiltinStyle.Heading3);
                newPara = section.AddParagraph() as WParagraph;
                newPara.AppendText("This is the heading3 of built in style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph.");
                #endregion
            }
            else
            {
                #region Custom styles
                //Custom styles.
                WParagraphStyle pStyle1 = (WParagraphStyle)doc.AddParagraphStyle("MyStyle1");
                WParagraphStyle pStyle2 = (WParagraphStyle)doc.AddParagraphStyle("MyStyle2");
                WParagraphStyle pStyle3 = (WParagraphStyle)doc.AddParagraphStyle("MyStyle3");

                //Set the Heading Styles to false in order to define custom levels to TOC.
                toc.UseHeadingStyles = false;

                //Set the TOC level style which determines; based on which the TOC should be created.
                toc.SetTOCLevelStyle(1, "MyStyle1");
                toc.SetTOCLevelStyle(2, "MyStyle2");
                toc.SetTOCLevelStyle(3, "MyStyle3");
                section = doc.AddSection() as WSection;

                pStyle1.CharacterFormat.FontName = "Cambria";
                pStyle1.CharacterFormat.FontSize = 30f;

                para = section.AddParagraph() as WParagraph;

                WTextRange text = para.AppendText("Document with Custom Styles") as WTextRange;
                para.ApplyStyle("MyStyle1");
                para = doc.LastSection.AddParagraph() as WParagraph;
                para.AppendText("This is the heading1 of built in style. This sample demonstrates the TOC insertion in a word document. Note that DocIO can only insert TOC field in a word document. It can not refresh or create TOC field. MS Word refreshes the TOC field after insertion. Please update the field or press F9 key to refresh the TOC.");

                pStyle2.CharacterFormat.FontName = "Cambria";
                pStyle2.CharacterFormat.FontSize = 20f;

                doc.LastSection.AddParagraph();

                para = doc.LastSection.AddParagraph() as WParagraph;
                text = para.AppendText("Section1") as WTextRange;
                para.ApplyStyle("MyStyle2");
                para = doc.LastSection.AddParagraph() as WParagraph;
                para.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");

                pStyle3.CharacterFormat.FontName = "Cambria";
                pStyle3.CharacterFormat.FontSize = 14f;

                doc.LastSection.AddParagraph();

                para = doc.LastSection.AddParagraph() as WParagraph;
                text = para.AppendText("Section2") as WTextRange;
                para.ApplyStyle("MyStyle3");
                para = doc.LastSection.AddParagraph() as WParagraph;
                para.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");
                #endregion
            }
            if (Convert.ToInt32(this.DropDownList2.Text) < Convert.ToInt32(this.DropDownList1.Text))
            {
                Response.Write("Not a valid heading level range. UpperHeadingLevel must be greater than LowerHeadingLevel");
            }
            else
            {
                toc.IncludePageNumbers    = this.CheckBox2.Checked;
                toc.RightAlignPageNumbers = this.CheckBox3.Checked;
                toc.UseHyperlinks         = this.CheckBox4.Checked;
                toc.LowerHeadingLevel     = Convert.ToInt32(this.DropDownList1.Text);
                toc.UpperHeadingLevel     = Convert.ToInt32(this.DropDownList2.Text);

                //Used to set levels for a word or paragraph through OutLine Levels
                //Right click text. Select Paragraph option. Set OutlineLevel. Update TOC toc see the text added in TOC.
                toc.UseOutlineLevels = this.CheckBox5.Checked;

                //Used to set levels for a word or paragraph through Table Entry Fields
                //Select the text that should be marked as Table of contents.
                //Press ALT+SHIFT+O. A dialog box will appear with options to enter the text, select the table identifier and level.
                //Choose the table identifier and level for the test and click �Mark�. Update TOC toc see the text added in TOC.
                //Sets the Table Identifier if necessary.
                //toc.TableID = "B";
                toc.UseTableEntryFields = this.CheckBox6.Checked;
                //Updates the table of contents.
                if (this.CheckBox7.Checked)
                {
                    doc.UpdateTableOfContents();
                }

                if (rdButtonDoc.Checked)
                {
                    //Save as .doc format
                    doc.Save("Sample.doc", FormatType.Doc, Response, HttpContentDisposition.Attachment);
                }
                //Save as .docx format
                else if (rdButtonDocx.Checked)
                {
                    try
                    {
                        doc.Save("Sample.docx", FormatType.Docx, Response, HttpContentDisposition.Attachment);
                    }
                    catch (Win32Exception ex)
                    {
                        Response.Write("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                        Console.WriteLine(ex.ToString());
                    }
                }
                //Save as WordML(.xml) format
                if (rdButtonWordML.Checked)
                {
                    try
                    {
                        doc.Save("Sample.xml", FormatType.WordML, Response, HttpContentDisposition.Attachment);
                    }
                    catch (Win32Exception ex)
                    {
                        Response.Write("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                        Console.WriteLine(ex.ToString());
                    }
                }
                //Save as .pdf format
                else if (rdButtonPdf.Checked)
                {
                    try
                    {
                        DocToPDFConverter converter = new DocToPDFConverter();
                        PdfDocument       pdfDoc    = converter.ConvertToPDF(doc);

                        pdfDoc.Save("Sample.pdf", Response, HttpReadType.Save);
                    }
                    catch (Win32Exception ex)
                    {
                        Response.Write("PDF Viewer is not installed in this system");
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }