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();
     }
 }
Пример #2
0
 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();
         docStream = File.OpenRead(Path.GetFullPath(@"../../../Source.docx"));
         WordDocument subDocument = new WordDocument(docStream, FormatType.Docx);
         docStream.Dispose();
         //Gets the content from another Word document to replace
         TextBodyPart replacePart = new TextBodyPart(subDocument);
         foreach (TextBodyItem bodyItem in subDocument.LastSection.Body.ChildEntities)
         {
             replacePart.BodyItems.Add(bodyItem.Clone());
         }
         string placeholderText = "Suppliers/Vendors of Northwind" + "Customers of Northwind"
                                  + "Employee details of Northwind traders" + "The product information"
                                  + "The inventory details" + "The shippers" + "Purchase Order transactions"
                                  + "Sales Order transaction" + "Inventory transactions" + "Invoices" + "[end replace]";
         //Finds the text that extends to several paragraphs and replaces it with desired content.
         document.ReplaceSingleLine(placeholderText, replacePart, false, false);
         subDocument.Dispose();
         //Saves the resultant file in the given path
         docStream = File.Create(Path.GetFullPath(@"Result.docx"));
         document.Save(docStream, FormatType.Docx);
         docStream.Dispose();
     }
 }
Пример #3
0
 public void Replace(TextBodyPart textBodyPart)
 {
     this.Clear();
     this.bool_7         = true;
     this.textBodyPart_0 = textBodyPart;
     this.method_39();
 }
Пример #4
0
        internal int method_26(Regex A_0, TextBodyPart A_1, bool A_2)
        {
            int num = 12;

            if (Class191.smethod_0(A_0))
            {
                throw new ArgumentException(BookmarkStart.b("愱儳圵䨷夹吻ḽ㌿㙁㙃⽅♇ⵉ汋ⵍㅏ㱑㩓㥕ⱗ穙㹛㭝䁟ݡॣᙥᱧ፩", num));
            }
            Class185 class2 = this.method_23(A_0);

            if (class2 == null)
            {
                return(0);
            }
            foreach (TextSelection selection in class2)
            {
                CharacterFormat characterFormat = null;
                if (A_2)
                {
                    characterFormat = selection.StartTextRange.CharacterFormat;
                }
                int       num2           = selection.method_0();
                Paragraph ownerParagraph = selection.OwnerParagraph;
                A_1.method_1(ownerParagraph.OwnerTextBody, ownerParagraph.method_5(), num2, characterFormat, A_2);
                if (base.Document.ReplaceFirst)
                {
                    break;
                }
            }
            return(class2.Count);
        }
 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();
     }
 }
Пример #6
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Load the document from disk.
            Document doc = new Document();

            doc.LoadFromFile(@"..\..\..\..\..\..\Data\Bookmark.docx");

            //Get the bookmark by name.
            Bookmark       bookmark = doc.Bookmarks["Test"];
            DocumentObject docObj   = null;

            //Judge if the paragraph includes the bookmark exists in the table, if it exists in cell,
            //Then need to find its outermost parent object(Table),
            //and get the start/end index of current object on body.
            if ((bookmark.BookmarkStart.Owner as Paragraph).IsInCell)
            {
                docObj = bookmark.BookmarkStart.Owner.Owner.Owner.Owner;
            }
            else
            {
                docObj = bookmark.BookmarkStart.Owner;
            }
            int startIndex = doc.Sections[0].Body.ChildObjects.IndexOf(docObj);

            if ((bookmark.BookmarkEnd.Owner as Paragraph).IsInCell)
            {
                docObj = bookmark.BookmarkEnd.Owner.Owner.Owner.Owner;
            }
            else
            {
                docObj = bookmark.BookmarkEnd.Owner;
            }
            int endIndex = doc.Sections[0].Body.ChildObjects.IndexOf(docObj);

            //Get the start/end index of the bookmark object on the paragraph.
            Paragraph para        = bookmark.BookmarkStart.Owner as Paragraph;
            int       pStartIndex = para.ChildObjects.IndexOf(bookmark.BookmarkStart);

            para = bookmark.BookmarkEnd.Owner as Paragraph;
            int pEndIndex = para.ChildObjects.IndexOf(bookmark.BookmarkEnd);

            //Get the content of current bookmark and copy.
            TextBodySelection select = new TextBodySelection(doc.Sections[0].Body, startIndex, endIndex, pStartIndex, pEndIndex);
            TextBodyPart      body   = new TextBodyPart(select);

            for (int i = 0; i < body.BodyItems.Count; i++)
            {
                doc.Sections[0].Body.ChildObjects.Add(body.BodyItems[i].Clone());
            }

            //Save the document.
            doc.SaveToFile("CopyBookmarkContent.docx", FileFormat.Docx);

            //Launch the Word file.
            FileViewer("CopyBookmarkContent.docx");
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Load the document
            string   input = @"..\..\..\..\..\..\Data\Bookmark.docx";
            Document doc   = new Document();

            doc.LoadFromFile(input);

            //Create a table
            Table table = new Table(doc, true);

            //Create datatable
            DataTable dt = new DataTable();

            dt.Columns.Add("id", typeof(string));
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("job", typeof(string));
            dt.Columns.Add("email", typeof(string));
            dt.Columns.Add("salary", typeof(string));
            dt.Rows.Add(new string[] { "Name", "Capital", "Continent", "Area", "Population" });
            dt.Rows.Add(new string[] { "Argentina", "Buenos Aires", "South America", "2777815", "32300003" });
            dt.Rows.Add(new string[] { "Bolivia", "La Paz", "South America", "1098575", "7300000" });
            dt.Rows.Add(new string[] { "Brazil", "Brasilia", "South America", "8511196", "150400000" });
            table.ResetCells(dt.Rows.Count, dt.Columns.Count);

            //Fill the table with the data of datatable
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    table.Rows[i].Cells[j].AddParagraph().AppendText(dt.Rows[i][j].ToString());
                }
            }

            //Get the specific bookmark by its name
            BookmarksNavigator navigator = new BookmarksNavigator(doc);

            navigator.MoveToBookmark("Test");

            //Create a TextBodyPart instance and add the table to it
            TextBodyPart part = new TextBodyPart(doc);

            part.BodyItems.Add(table);

            //Replace the current bookmark content with the TextBodyPart object
            navigator.ReplaceBookmarkContent(part);

            //Save and launch document
            string output = "ReplaceWithTable.docx";

            doc.SaveToFile(output, FileFormat.Docx);
            Viewer(output);
        }
Пример #8
0
 internal override void Close()
 {
     base.Close();
     if (this.m_textBody != null)
     {
         this.m_textBody.method_28();
         this.m_textBody = null;
     }
     this.m_format                  = null;
     this.textBodyPart_0            = null;
     this.paragraphItemCollection_1 = null;
     this.commentsCollection_0      = null;
 }
        private void CreateBookmarkForTable(Document doc, Section section)
        {
            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();

            //Append text for added paragraph
            TextRange txtRange = paragraph.AppendText("The following example demonstrates how to create bookmark for a table in a Word document.");

            //Set the font in italic
            txtRange.CharacterFormat.Italic = true;

            //Append bookmark start
            paragraph.AppendBookmarkStart("CreateBookmark");

            //Append bookmark end
            paragraph.AppendBookmarkEnd("CreateBookmark");

            //Add table
            Table table = section.AddTable(true);

            //Set the number of rows and columns
            table.ResetCells(2, 2);

            //Append text for table cells
            TextRange range = table[0, 0].AddParagraph().AppendText("sampleA");

            range = table[0, 1].AddParagraph().AppendText("sampleB");
            range = table[1, 0].AddParagraph().AppendText("120");
            range = table[1, 1].AddParagraph().AppendText("260");

            //Get the bookmark by index.
            Bookmark bookmark = doc.Bookmarks[0];

            //Get the name of bookmark.
            String bookmarkName = bookmark.Name;

            //Locate the bookmark by name.
            BookmarksNavigator navigator = new BookmarksNavigator(doc);

            navigator.MoveToBookmark(bookmarkName);

            //Add table to TextBodyPart
            TextBodyPart part = navigator.GetBookmarkContent();

            part.BodyItems.Add(table);

            //Replace bookmark cotent with table
            navigator.ReplaceBookmarkContent(part);
        }
Пример #10
0
        protected override object CloneImpl()
        {
            Comment comment = (Comment)base.CloneImpl();

            comment.m_format   = this.Format.Clone(comment.Document);
            comment.m_textBody = (Spire.Doc.Body) this.Body.Clone();
            comment.m_textBody.method_0(comment);
            foreach (BodyRegion region in comment.Body.ChildObjects)
            {
                region.method_0(comment.m_textBody);
            }
            this.paragraphItemCollection_1 = null;
            this.textBodyPart_0            = null;
            return(comment);
        }
Пример #11
0
        internal int method_27(Regex A_0, IDocument A_1, bool A_2)
        {
            int num = 7;

            if (Class191.smethod_0(A_0))
            {
                throw new ArgumentException(BookmarkStart.b("縬䨮倰䄲嘴弶ᤸ䠺䤼䴾⡀ⵂ≄杆⩈⩊⍌ⅎ㹐❒畔㕖㱘筚㡜㉞ᅠᝢᱤ", num));
            }
            CharacterFormat characterFormat = null;
            Class185        class2          = this.method_23(A_0);

            if (class2 == null)
            {
                return(0);
            }
            foreach (TextSelection selection in class2)
            {
                if (A_2)
                {
                    characterFormat = selection.StartTextRange.CharacterFormat;
                }
                int       num3           = selection.method_0();
                Paragraph ownerParagraph = selection.OwnerParagraph;
                for (int i = A_1.Sections.Count - 1; i >= 0; i--)
                {
                    ISection section = A_1.Sections[i];
                    if (!A_2)
                    {
                        base.Document.CurClonedSection = section as Section;
                    }
                    TextBodyPart part = new TextBodyPart(base.Document);
                    part.method_0(section.Body, false);
                    part.method_1(ownerParagraph.OwnerTextBody, ownerParagraph.method_5(), num3, characterFormat, A_2);
                }
                if (base.Document.ReplaceFirst)
                {
                    break;
                }
            }
            return(class2.Count);
        }
Пример #12
0
 public void Clear()
 {
     if ((this.paragraphItemCollection_1 != null) && (this.paragraphItemCollection_1.Count != 0))
     {
         if (this.bool_7)
         {
             this.paragraphItemCollection_1.Clear();
             this.textBodyPart_0 = null;
         }
         else
         {
             ParagraphBase firstItem = this.paragraphItemCollection_1.FirstItem as ParagraphBase;
             ParagraphBase lastItem  = this.paragraphItemCollection_1.LastItem as ParagraphBase;
             this.method_31(firstItem, lastItem);
             this.Format.BookmarkStartOffset = 0;
             this.Format.BookmarkEndOffset   = 1;
             this.paragraphItemCollection_1.Clear();
             this.bool_7 = false;
         }
     }
 }
Пример #13
0
 internal void method_3(TextSelection[] A_0, TextBodyPart A_1)
 {
     if ((A_0 != null) && (A_0.Length != 0))
     {
         TextSelection selection = null;
         int           num3      = A_0.Length - 1;
         for (int i = num3; i >= 0; i--)
         {
             selection = A_0[i];
             int pItemIndex = selection.method_0();
             if (i == 0)
             {
                 Paragraph ownerParagraph = selection.OwnerParagraph;
                 A_1.PasteAt(ownerParagraph.OwnerTextBody, ownerParagraph.method_5(), pItemIndex);
             }
             else
             {
                 this.method_4(selection);
             }
         }
     }
 }
Пример #14
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);
        }
 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();
         //Creates a new table
         WTable table = new WTable(document);
         table.ResetCells(1, 6);
         table[0, 0].Width = 52f;
         table[0, 0].AddParagraph().AppendText("Supplier ID");
         table[0, 1].Width = 128f;
         table[0, 1].AddParagraph().AppendText("Company Name");
         table[0, 2].Width = 70f;
         table[0, 2].AddParagraph().AppendText("Contact Name");
         table[0, 3].Width = 92f;
         table[0, 3].AddParagraph().AppendText("Address");
         table[0, 4].Width = 66.5f;
         table[0, 4].AddParagraph().AppendText("City");
         table[0, 5].Width = 56f;
         table[0, 5].AddParagraph().AppendText("Country");
         //Imports data to the table
         ImportDataToTable(table);
         //Applies the built-in table style (Medium Shading 1 Accent 1) to the table
         table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent1);
         //Replaces the table placeholder text with a new table
         TextBodyPart bodyPart = new TextBodyPart(document);
         bodyPart.BodyItems.Add(table);
         document.Replace("[Suppliers table]", 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();
     }
 }
Пример #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Load Document
            string   input = @"..\..\..\..\..\..\Data\BookmarkTemplate.docx";
            Document doc   = new Document();

            doc.LoadFromFile(input);

            //Creates a BookmarkNavigator instance to access the bookmark
            BookmarksNavigator navigator = new BookmarksNavigator(doc);

            //Locate a specific bookmark by bookmark name
            navigator.MoveToBookmark("Content");
            TextBodyPart textBodyPart = navigator.GetBookmarkContent();

            //Iterate through the items in the bookmark content to get the text
            string text = null;

            foreach (var item in textBodyPart.BodyItems)
            {
                if (item is Paragraph)
                {
                    foreach (var childObject in (item as Paragraph).ChildObjects)
                    {
                        if (childObject is TextRange)
                        {
                            text += (childObject as TextRange).Text;
                        }
                    }
                }
            }

            //Save to TXT File and launch it
            string output = "ExtractBookmarkText.txt";

            File.WriteAllText(output, text);
            Viewer(output);
        }
Пример #17
0
        private void SetTagValue()
        {
            if (lstTag.Count > 0)
            {
                foreach (ITagWord iTag in lstTag)
                {
                    string tagName = Contains.START_TAG + iTag.TagName + Contains.END_TAG;
                    switch (iTag.TagType)
                    {
                    case TagWordType.Text:
                        Document.Replace(tagName, iTag.Data.ToString(), false, false);
                        break;

                    case TagWordType.Image:
                        Image       img       = ConvertStrBase64ToImage(iTag.Data.ToString());
                        IWParagraph paragraph = Section.AddParagraph();
                        IWPicture   picture   = paragraph.AppendPicture(img);
                        if (iTag.TagStyle != "")
                        {
                            string[] lstStyle = iTag.TagStyle.Split(';');
                            for (int i = 0, n = lstStyle.Length; i < n; i++)
                            {
                                SetStyle(picture, lstStyle[i]);
                            }
                        }
                        paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
                        TextBodyPart textBodyPart = new TextBodyPart(Document);
                        textBodyPart.BodyItems.Add(paragraph);
                        Document.Replace(tagName, textBodyPart, false, false);
                        break;

                    default:
                        break;
                    }
                }
            }
        }
Пример #18
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                string dataPath = @"..\..\..\..\..\..\..\Common\Data\DocIO\";
                // Creating a new document.
                WordDocument document = new WordDocument();
                //Adds section with one empty paragraph to the Word document
                document.EnsureMinimal();
                //sets the page margins
                document.LastSection.PageSetup.Margins.All = 72f;
                //Appends bookmark to the paragraph
                document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
                document.LastParagraph.AppendText("Northwind database with normalization concept");
                document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
                // Open an existing template document with single section to get Northwind.information
                WordDocument nwdInformation = new WordDocument(dataPath + "Bookmark_Template.doc");
                // Open an existing template document with multiple section to get Northwind data.
                WordDocument templateDocument = new WordDocument(dataPath + "BkmkDocumentPart_Template.doc");
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the template document.
                BookmarksNavigator bk = new BookmarksNavigator(templateDocument);
                // Move to the NorthWind bookmark in template document
                bk.MoveToBookmark("NorthWind");
                //Gets the bookmark content as WordDocumentPart
                WordDocumentPart documentPart = bk.GetContent();
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the Northwind information document.
                bk = new BookmarksNavigator(nwdInformation);
                // Move to the information bookmark
                bk.MoveToBookmark("Information");
                // Get the content of information bookmark.
                TextBodyPart bodyPart = bk.GetBookmarkContent();
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the destination document.
                bk = new BookmarksNavigator(document);
                // Move to the NorthWind database in the destination document
                bk.MoveToBookmark("NorthwindDatabase");
                //Replace the bookmark content using word document parts
                bk.ReplaceContent(documentPart);
                // Move to the Northwind_Information in the destination document
                bk.MoveToBookmark("Northwind_Information");
                // Replacing content of Northwind_Information bookmark.
                bk.ReplaceBookmarkContent(bodyPart);
                // Move to the text bookmark
                bk.MoveToBookmark("Text");
                //Deletes the bookmark content
                bk.DeleteBookmarkContent(true);
                // Inserting text inside the bookmark. This will preserve the source formatting
                bk.InsertText("Northwind Database contains the following table:");
                #region tableinsertion
                WTable tbl = new WTable(document);
                tbl.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.None;
                tbl.TableFormat.IsAutoResized      = true;
                tbl.ResetCells(8, 2);
                IWParagraph paragraph;
                tbl.Rows[0].IsHeader = true;
                paragraph            = tbl[0, 0].AddParagraph();
                paragraph.AppendText("Suppliers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[0, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[1, 0].AddParagraph();
                paragraph.AppendText("Customers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[1, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[2, 0].AddParagraph();
                paragraph.AppendText("Employees");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[2, 1].AddParagraph();
                paragraph.AppendText("3");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[3, 0].AddParagraph();
                paragraph.AppendText("Products");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[3, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[4, 0].AddParagraph();
                paragraph.AppendText("Inventory");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[4, 1].AddParagraph();
                paragraph.AppendText("2");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[5, 0].AddParagraph();
                paragraph.AppendText("Shippers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[5, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[6, 0].AddParagraph();
                paragraph.AppendText("PO Transactions");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[6, 1].AddParagraph();
                paragraph.AppendText("3");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[7, 0].AddParagraph();
                paragraph.AppendText("Sales Transactions");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[7, 1].AddParagraph();
                paragraph.AppendText("7");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;


                bk.InsertTable(tbl);
                #endregion
                //Move to image bookmark
                bk.MoveToBookmark("Image");
                //Deletes the bookmark content
                bk.DeleteBookmarkContent(true);
                // Inserting image to the bookmark.
                IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
                pic.LoadImage(System.Drawing.Image.FromFile(@"..\..\..\..\..\..\..\Common\images\DocIO\Northwind.png"));
                pic.WidthScale  = 50f; // It reduces the image size because it doesnot fit
                pic.HeightScale = 75f; // in document page.
                bodyPart.Close();
                documentPart.Close();
                #region save document
                //Save as doc format
                if (wordDocRadioBtn.Checked)
                {
                    //Saving the document to disk.
                    document.Save("Sample.doc");

                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                        System.Diagnostics.Process.Start("Sample.doc");
                        //Exit
                        this.Close();
                    }
                }
                //Save as docx format
                else if (wordDocxRadioBtn.Checked)
                {
                    //Saving the document as .docx
                    document.Save("Sample.docx", FormatType.Docx);
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                            System.Diagnostics.Process.Start("Sample.docx");
                            //Exit
                            this.Close();
                        }
                        catch (Win32Exception ex)
                        {
                            MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                //Save as pdf format
                else if (pdfRadioBtn.Checked)
                {
                    DocToPDFConverter converter = new DocToPDFConverter();
                    //Convert word document into PDF document
                    PdfDocument pdfDoc = converter.ConvertToPDF(document);
                    //Save the pdf file
                    pdfDoc.Save("Sample.pdf");
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            System.Diagnostics.Process.Start("Sample.pdf");
                            //Exit
                            this.Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBoxAdv.Show("PDF Viewer is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                #endregion
                else
                {
                    // Exit
                    this.Close();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
        public ActionResult BookmarkNavigation(string Group1)
        {
            if (Group1 == null)
            {
                return(View());
            }
            #region BookmarkNavigation
            // Creating a new document.
            WordDocument document = new WordDocument();
            //Adds section with one empty paragraph to the Word document
            document.EnsureMinimal();
            //sets the page margins
            document.LastSection.PageSetup.Margins.All = 72f;
            //Appends bookmark to the paragraph
            document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
            document.LastParagraph.AppendText("Northwind database with normalization concept");
            document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
            string basePath     = _hostingEnvironment.WebRootPath;
            string dataPath     = basePath + @"/DocIO/Bookmark_Template.doc";
            string dataPathTemp = basePath + @"/DocIO/BkmkDocumentPart_Template.doc";
            // Open an existing template document with single section to get Northwind.information
            WordDocument nwdInformation = new WordDocument();
            FileStream   fileStream     = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            nwdInformation.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;
            // Open an existing template document with multiple section to get Northwind data.
            WordDocument templateDocument = new WordDocument();
            fileStream = new FileStream(dataPathTemp, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            templateDocument.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the template document.
            BookmarksNavigator bk = new BookmarksNavigator(templateDocument);
            // Move to the NorthWind bookmark in template document
            bk.MoveToBookmark("NorthWind");
            //Gets the bookmark content as WordDocumentPart
            WordDocumentPart documentPart = bk.GetContent();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the Northwind information document.
            bk = new BookmarksNavigator(nwdInformation);
            // Move to the information bookmark
            bk.MoveToBookmark("Information");
            // Get the content of information bookmark.
            TextBodyPart bodyPart = bk.GetBookmarkContent();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the destination document.
            bk = new BookmarksNavigator(document);
            // Move to the NorthWind database in the destination document
            bk.MoveToBookmark("NorthwindDatabase");
            //Replace the bookmark content using word document parts
            bk.ReplaceContent(documentPart);
            // Move to the Northwind_Information in the destination document
            bk.MoveToBookmark("Northwind_Information");
            // Replacing content of Northwind_Information bookmark.
            bk.ReplaceBookmarkContent(bodyPart);
            // Move to the text bookmark
            bk.MoveToBookmark("Text");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting text inside the bookmark. This will preserve the source formatting
            bk.InsertText("Northwind Database contains the following table:");
            #region tableinsertion
            WTable tbl = new WTable(document);
            tbl.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.None;
            tbl.TableFormat.IsAutoResized      = true;
            tbl.ResetCells(8, 2);
            IWParagraph paragraph;
            tbl.Rows[0].IsHeader = true;
            paragraph            = tbl[0, 0].AddParagraph();
            paragraph.AppendText("Suppliers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[0, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 0].AddParagraph();
            paragraph.AppendText("Customers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 0].AddParagraph();
            paragraph.AppendText("Employees");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 0].AddParagraph();
            paragraph.AppendText("Products");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 0].AddParagraph();
            paragraph.AppendText("Inventory");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 1].AddParagraph();
            paragraph.AppendText("2");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 0].AddParagraph();
            paragraph.AppendText("Shippers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 0].AddParagraph();
            paragraph.AppendText("PO Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 0].AddParagraph();
            paragraph.AppendText("Sales Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 1].AddParagraph();
            paragraph.AppendText("7");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            bk.InsertTable(tbl);
            #endregion tableinsertion
            //Move to image bookmark
            bk.MoveToBookmark("Image");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting image to the bookmark.
            IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;

            FileStream imageStream = new FileStream(basePath + @"/images/DocIO/Northwind.png", FileMode.Open, FileAccess.Read);
            pic.LoadImage(imageStream);
            pic.WidthScale  = 50f; // It reduce the image size because it don't fit
            pic.HeightScale = 75f; // in document page.
            #endregion BookmarkNavigation

            FormatType type        = FormatType.Docx;
            string     filename    = "Sample.docx";
            string     contenttype = "application/vnd.ms-word.document.12";
            #region Document SaveOption
            //Save as .doc format
            if (Group1 == "WordDoc")
            {
                type        = FormatType.Doc;
                filename    = "Sample.doc";
                contenttype = "application/msword";
            }
            //Save as .xml format
            else if (Group1 == "WordML")
            {
                type        = FormatType.WordML;
                filename    = "Sample.xml";
                contenttype = "application/msword";
            }
            #endregion Document SaveOption
            MemoryStream ms = new MemoryStream();
            document.Save(ms, type);
            document.Close();
            ms.Position = 0;
            return(File(ms, contenttype, filename));
        }
Пример #20
0
        private void ManipulateBookmarkContents()
        {
            // Creating a new document.
            using (WordDocument document = new WordDocument())
            {
                #region Document Manipulations
                Assembly assembly = typeof(App).GetTypeInfo().Assembly;
                //Adds section with one empty paragraph to the Word document
                document.EnsureMinimal();
                //sets the page margins
                document.LastSection.PageSetup.Margins.All = 72f;
                //Appends bookmark to the paragraph
                document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
                document.LastParagraph.AppendText("Northwind database with relational data");
                document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
                // Open an existing template document with single section.
                WordDocument nwdInformation = new WordDocument();
                Stream       inputStream    = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Bookmark_Template.doc");
                // Open an existing template document.
                nwdInformation.Open(inputStream, FormatType.Doc);
                inputStream.Dispose();
                // Open an existing template document with multiple section.
                WordDocument templateDocument = new WordDocument();
                inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.BkmkDocumentPart_Template.doc");
                // Open an existing template document.
                templateDocument.Open(inputStream, FormatType.Doc);
                inputStream.Dispose();
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the template document.
                BookmarksNavigator bk = new BookmarksNavigator(templateDocument);
                // Move to the NorthWind bookmark in template document
                bk.MoveToBookmark("NorthWind");
                //Gets the bookmark content as WordDocumentPart
                WordDocumentPart documentPart = bk.GetContent();
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the Northwind information document.
                bk = new BookmarksNavigator(nwdInformation);
                // Move to the information bookmark
                bk.MoveToBookmark("Information");
                // Get the content of information bookmark.
                TextBodyPart bodyPart = bk.GetBookmarkContent();
                // Creating a bookmark navigator. Which help us to navigate through the
                // bookmarks in the destination document.
                bk = new BookmarksNavigator(document);
                // Move to the NorthWind database in the destination document
                bk.MoveToBookmark("NorthwindDatabase");
                //Replace the bookmark content using word document parts
                bk.ReplaceContent(documentPart);
                // Move to the Northwind_Information in the destination document
                bk.MoveToBookmark("Northwind_Information");
                // Replacing content of Northwind_Information bookmark.
                bk.ReplaceBookmarkContent(bodyPart);
                // Move to the text bookmark
                bk.MoveToBookmark("Text");
                //Deletes the bookmark content
                bk.DeleteBookmarkContent(true);
                // Inserting text inside the bookmark. This will preserve the source formatting
                bk.InsertText("Northwind Database contains the following table:");
                #region tableinsertion
                WTable tbl = new WTable(document);
                tbl.TableFormat.Borders.BorderType = BorderStyle.None;
                tbl.TableFormat.IsAutoResized      = true;
                tbl.ResetCells(8, 2);
                IWParagraph paragraph;
                tbl.Rows[0].IsHeader = true;
                paragraph            = tbl[0, 0].AddParagraph();
                paragraph.AppendText("Suppliers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[0, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[1, 0].AddParagraph();
                paragraph.AppendText("Customers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[1, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[2, 0].AddParagraph();
                paragraph.AppendText("Employees");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[2, 1].AddParagraph();
                paragraph.AppendText("3");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[3, 0].AddParagraph();
                paragraph.AppendText("Products");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[3, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[4, 0].AddParagraph();
                paragraph.AppendText("Inventory");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[4, 1].AddParagraph();
                paragraph.AppendText("2");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[5, 0].AddParagraph();
                paragraph.AppendText("Shippers");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[5, 1].AddParagraph();
                paragraph.AppendText("1");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[6, 0].AddParagraph();
                paragraph.AppendText("PO Transactions");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[6, 1].AddParagraph();
                paragraph.AppendText("3");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[7, 0].AddParagraph();
                paragraph.AppendText("Sales Transactions");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;

                paragraph = tbl[7, 1].AddParagraph();
                paragraph.AppendText("7");
                paragraph.BreakCharacterFormat.FontName = "Calibri";
                paragraph.BreakCharacterFormat.FontSize = 10;


                bk.InsertTable(tbl);
                #endregion
                bk.MoveToBookmark("Image");
                bk.DeleteBookmarkContent(true);
                // Inserting image to the bookmark.
                IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
                inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Northwind.png");
                pic.LoadImage(inputStream);
                inputStream.Dispose();
                pic.WidthScale  = 50f; // It reduce the image size because it don't fit
                pic.HeightScale = 75f; // in document page.
                #endregion
                #region Saving Document
                //Save the word document to stream.
                MemoryStream stream = new MemoryStream();
                document.Save(stream, FormatType.Docx);
                //Save file in the disk based on specfic OS
                if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
                {
                    Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("BookMarkNavigation.docx", "application/msword", stream);
                }
                else
                {
                    Xamarin.Forms.DependencyService.Get <ISave>().Save("BookMarkNavigation.docx", "application/msword", stream);
                }
                #endregion
            }
        }
Пример #21
0
        public ActionResult AdvancedReplace(string Group1, string Button)
        {
            if (Group1 == null)
            {
                return(View());
            }
            try
            {
                string basePath         = _hostingEnvironment.WebRootPath;
                string dataPathTemp     = basePath + @"/DocIO/SourceTemplate1.doc";
                string dataPathTemplate = basePath + @"/DocIO/SourceTemplate2.doc";
                string dataPathMaster   = basePath + @"/DocIO/MasterTemplate.doc";
                string contenttype1     = "application/msword";
                //Load Template document stream.
                FileStream fileStream = new FileStream(dataPathMaster, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                if (Button == "View Template")
                {
                    return(File(fileStream, contenttype1, "MasterTemplate.doc"));
                }
                fileStream.Dispose();
                fileStream = null;

                //Creating new documents.
                WordDocument docSource1 = new WordDocument();
                WordDocument docSource2 = new WordDocument();
                WordDocument docMaster  = new WordDocument();
                //Load Templates.
                fileStream = new FileStream(dataPathTemp, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                docSource1.Open(fileStream, FormatType.Doc);
                fileStream.Dispose();
                fileStream = null;
                fileStream = new FileStream(dataPathTemplate, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                docSource2.Open(fileStream, FormatType.Doc);
                fileStream.Dispose();
                fileStream = null;
                fileStream = new FileStream(dataPathMaster, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                docMaster.Open(fileStream, FormatType.Doc);
                fileStream.Dispose();
                fileStream = null;
                //Search for a string and store in TextSelection
                //The TextSelection copies a text segment with formatting.
                TextSelection selection1 = docSource1.Find("PlaceHolder text is replaced with this formatted animated text", false, false);
                //Get the text segment to replace the tex across multiple paragraphs
                TextBodyPart replacePart = new TextBodyPart(docSource2);
                foreach (TextBodyItem bodyItem in docSource2.LastSection.Body.ChildEntities)
                {
                    replacePart.BodyItems.Add(bodyItem.Clone());
                }
                //Replacing the placeholder inside Master Template with matches found while
                //search the two template documents.
                docMaster.Replace("PlaceHolder1", selection1, true, true, true);
                docMaster.ReplaceSingleLine((new System.Text.RegularExpressions.Regex("PlaceHolder2Start:Suppliers/Vendors of Northwind." +
                                                                                      "Customers of Northwind.Employee details of Northwind traders.The product information.The inventory details.The shippers." +
                                                                                      "PO transactions i.e Purchase Order transactions.Sales Order transaction.Inventory transactions.Invoices.PlaceHolder2End")), replacePart);

                FormatType type        = FormatType.Docx;
                string     filename    = "Sample.docx";
                string     contenttype = "application/vnd.ms-word.document.12";
                #region Document SaveOption
                //Save as .doc format
                if (Group1 == "WordDoc")
                {
                    type        = FormatType.Doc;
                    filename    = "Sample.doc";
                    contenttype = "application/msword";
                }
                //Save as .xml format
                else if (Group1 == "WordML")
                {
                    type        = FormatType.WordML;
                    filename    = "Sample.xml";
                    contenttype = "application/msword";
                }
                #endregion Document SaveOption
                MemoryStream ms = new MemoryStream();
                docMaster.Save(ms, type);
                docMaster.Close();
                ms.Position = 0;
                return(File(ms, contenttype, filename));
            }
            catch (Exception)
            {
            }
            return(View());
        }
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Assembly execAssem = typeof(BookmarkNavigationDemo).GetTypeInfo().Assembly;
            // Creating a new document.
            WordDocument document = new WordDocument();

            //Adds section with one empty paragraph to the Word document
            document.EnsureMinimal();
            //sets the page margins
            document.LastSection.PageSetup.Margins.All = 72f;
            //Appends bookmark to the paragraph
            document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
            document.LastParagraph.AppendText("Northwind database with relational data");
            document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
            // Open an existing template document with single section.
            WordDocument nwdInformation = new WordDocument();
            Stream       inputStream    = execAssem.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Assets.Bookmark_Template.doc");
            // Open an existing template document.
            await nwdInformation.OpenAsync(inputStream, FormatType.Doc);

            inputStream.Dispose();
            // Open an existing template document with multiple section.
            WordDocument templateDocument = new WordDocument();

            inputStream = execAssem.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Assets.BkmkDocumentPart_Template.doc");
            // Open an existing template document.
            await templateDocument.OpenAsync(inputStream, FormatType.Doc);

            inputStream.Dispose();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the template document.
            BookmarksNavigator bk = new BookmarksNavigator(templateDocument);

            // Move to the NorthWind bookmark in template document
            bk.MoveToBookmark("NorthWind");
            //Gets the bookmark content as WordDocumentPart
            WordDocumentPart documentPart = bk.GetContent();

            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the Northwind information document.
            bk = new BookmarksNavigator(nwdInformation);
            // Move to the information bookmark
            bk.MoveToBookmark("Information");
            // Get the content of information bookmark.
            TextBodyPart bodyPart = bk.GetBookmarkContent();

            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the destination document.
            bk = new BookmarksNavigator(document);
            // Move to the NorthWind database in the destination document
            bk.MoveToBookmark("NorthwindDatabase");
            //Replace the bookmark content using word document parts
            bk.ReplaceContent(documentPart);
            // Move to the Northwind_Information in the destination document
            bk.MoveToBookmark("Northwind_Information");
            // Replacing content of Northwind_Information bookmark.
            bk.ReplaceBookmarkContent(bodyPart);
            // Move to the text bookmark
            bk.MoveToBookmark("Text");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting text inside the bookmark. This will preserve the source formatting
            bk.InsertText("Northwind Database contains the following table:");
            #region tableinsertion
            WTable tbl = new WTable(document);
            tbl.TableFormat.Borders.BorderType = BorderStyle.None;
            tbl.TableFormat.IsAutoResized      = true;
            tbl.ResetCells(8, 2);
            IWParagraph paragraph;
            tbl.Rows[0].IsHeader = true;
            paragraph            = tbl[0, 0].AddParagraph();
            paragraph.AppendText("Suppliers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[0, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 0].AddParagraph();
            paragraph.AppendText("Customers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 0].AddParagraph();
            paragraph.AppendText("Employees");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 0].AddParagraph();
            paragraph.AppendText("Products");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 0].AddParagraph();
            paragraph.AppendText("Inventory");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 1].AddParagraph();
            paragraph.AppendText("2");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 0].AddParagraph();
            paragraph.AppendText("Shippers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 0].AddParagraph();
            paragraph.AppendText("PO Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 0].AddParagraph();
            paragraph.AppendText("Sales Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 1].AddParagraph();
            paragraph.AppendText("7");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;


            bk.InsertTable(tbl);
            #endregion
            //Move to image bookmark
            bk.MoveToBookmark("Image");
            //Deletes the bookmark
            bk.DeleteBookmarkContent(true);
            // Inserting image to the bookmark.
            IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
            inputStream = execAssem.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Assets.Northwind.png");
            pic.LoadImage(inputStream);
            inputStream.Dispose();
            pic.WidthScale  = 50f; // It reduce the image size because it don't fit
            pic.HeightScale = 75f; // in document page.
            Save(rdDoc.IsChecked == true, document);
        }
        public static void AddTableInBookmark(string sql, Table table, BookmarksNavigator navigator, string bookmark, TextBodyPart txtbodyPart)
        {
            //Voer sql query uit en steek deze in datatable
            DataTable result = ConnectDatabase.getTable(sql);

            //Vul de table met data van de datatable
            List <string> years = new List <string>();

            for (int i = 0; i < result.Rows.Count; i++)
            {
                if (!years.Contains(result.Rows[i]["jaar"].ToString()))
                {
                    years.Add(result.Rows[i]["jaar"].ToString());
                }
            }
            years.Sort();

            List <string> groups = new List <string>();

            for (int i = 0; i < result.Rows.Count; i++)
            {
                if (!groups.Contains(result.Rows[i][0].ToString()))
                {
                    groups.Add(result.Rows[i][0].ToString());
                }
            }
            //groups.Sort(); sorteer modules
            table.ResetCells(groups.Count + 1, years.Count + 1);
            table.Rows[0].Cells[0].AddParagraph().AppendText(bookmark);
            for (int i = 0; i < years.Count; i++)
            {
                table.Rows[0].Cells[i + 1].AddParagraph().AppendText(years[i]);
            }
            for (int i = 1; i <= groups.Count; i++)
            {
                table.Rows[i].Cells[0].AddParagraph().AppendText(groups[i - 1]);
            }

            for (int i = 1; i <= groups.Count; i++)
            {
                List <TableInput> tableInputByGroup = GetTableInputsByGroup(result, groups[i - 1], years);
                for (int j = 1; j <= tableInputByGroup.Count; j++)
                {
                    table.Rows[i].Cells[j].AddParagraph().AppendText(tableInputByGroup[j - 1].Value.ToString());
                }
            }
            table.AutoFit(AutoFitBehaviorType.AutoFitToContents);

            navigator.MoveToBookmark(bookmark);

            txtbodyPart.BodyItems.Add(table);
            navigator.ReplaceBookmarkContent(txtbodyPart);
        }
        public static void AddTableInBookmarkWithoutGroups(string sql, Table table, BookmarksNavigator navigator, string bookmark, TextBodyPart txtbodyPart)
        {
            //Voer sql query uit en steek deze in datatable
            DataTable result = ConnectDatabase.getTable(sql);

            //Vul de table met data van de datatable
            List <string> years = new List <string>();

            for (int i = 0; i < result.Rows.Count; i++)
            {
                if (!years.Contains(result.Rows[i]["jaar"].ToString()))
                {
                    years.Add(result.Rows[i]["jaar"].ToString());
                }
            }
            years.Sort();



            table.ResetCells(2, years.Count + 1);
            table.Rows[0].Cells[0].AddParagraph().AppendText(bookmark);
            for (int i = 0; i < years.Count; i++)
            {
                table.Rows[0].Cells[i + 1].AddParagraph().AppendText(years[i]);
            }

            for (int i = 1; i <= years.Count; i++)
            {
                table.Rows[1].Cells[i].AddParagraph().AppendText(result.Rows[i - 1]["value"].ToString());
            }

            table.AutoFit(AutoFitBehaviorType.AutoFitToContents);

            navigator.MoveToBookmark(bookmark);

            txtbodyPart.BodyItems.Add(table);
            navigator.ReplaceBookmarkContent(txtbodyPart);
        }
        void OnButtonClicked(object sender, EventArgs e)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            // Creating a new document.
            WordDocument document = new WordDocument();

            //Adds section with one empty paragraph to the Word document
            document.EnsureMinimal();
            //sets the page margins
            document.LastSection.PageSetup.Margins.All = 72f;
            //Appends bookmark to the paragraph
            document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
            document.LastParagraph.AppendText("Northwind database with relational data");
            document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
            // Open an existing template document with single section.
            WordDocument nwdInformation = new WordDocument();
            Stream       inputStream    = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Bookmark_Template.docx");

            // Open an existing template document.
            nwdInformation.Open(inputStream, FormatType.Doc);
            inputStream.Dispose();
            // Open an existing template document with multiple section.
            WordDocument templateDocument = new WordDocument();

            inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.BkmkDocumentPart_Template.docx");
            // Open an existing template document.
            templateDocument.Open(inputStream, FormatType.Doc);
            inputStream.Dispose();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the template document.
            BookmarksNavigator bk = new BookmarksNavigator(templateDocument);

            // Move to the NorthWind bookmark in template document
            bk.MoveToBookmark("NorthWind");
            //Gets the bookmark content as WordDocumentPart
            WordDocumentPart documentPart = bk.GetContent();

            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the Northwind information document.
            bk = new BookmarksNavigator(nwdInformation);
            // Move to the information bookmark
            bk.MoveToBookmark("Information");
            // Get the content of information bookmark.
            TextBodyPart bodyPart = bk.GetBookmarkContent();

            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the destination document.
            bk = new BookmarksNavigator(document);
            // Move to the NorthWind database in the destination document
            bk.MoveToBookmark("NorthwindDatabase");
            //Replace the bookmark content using word document parts
            bk.ReplaceContent(documentPart);
            // Move to the Northwind_Information in the destination document
            bk.MoveToBookmark("Northwind_Information");
            // Replacing content of Northwind_Information bookmark.
            bk.ReplaceBookmarkContent(bodyPart);
            #region Bookmark selection for table
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the Northwind information document.
            bk = new BookmarksNavigator(nwdInformation);
            bk.MoveToBookmark("SuppliersTable");
            //Sets the column index where the bookmark starts within the table
            bk.CurrentBookmark.FirstColumn = 1;
            //Sets the column index where the bookmark ends within the table
            bk.CurrentBookmark.LastColumn = 5;
            // Get the content of suppliers table bookmark.
            bodyPart = bk.GetBookmarkContent();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the destination document.
            bk = new BookmarksNavigator(document);
            bk.MoveToBookmark("Table");
            bk.ReplaceBookmarkContent(bodyPart);
            #endregion
            // Move to the text bookmark
            bk.MoveToBookmark("Text");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting text inside the bookmark. This will preserve the source formatting
            bk.InsertText("Northwind Database contains the following table:");
            #region tableinsertion
            WTable tbl = new WTable(document);
            tbl.TableFormat.Borders.BorderType = BorderStyle.None;
            tbl.TableFormat.IsAutoResized      = true;
            tbl.ResetCells(8, 2);
            IWParagraph paragraph;
            tbl.Rows[0].IsHeader = true;
            paragraph            = tbl[0, 0].AddParagraph();
            paragraph.AppendText("Suppliers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[0, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 0].AddParagraph();
            paragraph.AppendText("Customers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 0].AddParagraph();
            paragraph.AppendText("Employees");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 0].AddParagraph();
            paragraph.AppendText("Products");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 0].AddParagraph();
            paragraph.AppendText("Inventory");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 1].AddParagraph();
            paragraph.AppendText("2");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 0].AddParagraph();
            paragraph.AppendText("Shippers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 0].AddParagraph();
            paragraph.AppendText("PO Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 0].AddParagraph();
            paragraph.AppendText("Sales Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 1].AddParagraph();
            paragraph.AppendText("7");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;


            bk.InsertTable(tbl);
            #endregion
            bk.MoveToBookmark("Image");
            bk.DeleteBookmarkContent(true);
            // Inserting image to the bookmark.
            IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
            inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Northwind.png");
            pic.LoadImage(inputStream);
            inputStream.Dispose();
            pic.WidthScale  = 50f; // It reduce the image size because it don't fit
            pic.HeightScale = 75f; // in document page.


            #region Saving Document
            MemoryStream stream = new MemoryStream();
            document.Save(stream, FormatType.Word2013);
            document.Close();
            if (stream != null)
            {
                SaveAndroid androidSave = new SaveAndroid();
                androidSave.Save("BookmarkNavigation.docx", "application/msword", stream, m_context);
            }

            #endregion
        }
        public static void Create()
        {
            try
            {
                //Laad de template in
                Document testdoc = new Document();
                testdoc.LoadFromFile(AppDomain.CurrentDomain.BaseDirectory + "\\Template.docx");
                //Maak table
                Section section = testdoc.Sections[0];
                Table   table   = section.Tables[0] as Table;
                //Table table = new Table(testdoc);
                table.ApplyStyle(DefaultTableStyle.MediumShading1Accent1);

                BookmarksNavigator navigator = new BookmarksNavigator(testdoc);

                TextBodyPart part = new TextBodyPart(testdoc);

                /*Aantal studenten /module/sesmter */

                //Deze tabel klopt
                //Aantal studenten / module /semster1
                AddTableInBookmark("select Module, count(Geslacht) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where MONTH([Module begindatum]) < 7  group by module ,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE())-5) order by  YEAR([Module begindatum]), semester", table, navigator, "TotaalAantalStudentenSem1", part);
                //Aantal studenten / module / semester2
                AddTableInBookmark("select Module, count(Geslacht) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where MONTH([Module begindatum]) > 7  group by module , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE())-5) order by  YEAR([Module begindatum]), semester", table, navigator, "TotaalAantalStudentenSem2", part);


                /*Geslaagde mensen / module per semester */
                //tabellen kloppen
                //Semester 1
                AddTableInBookmark("select Module, COUNT([Module attest]) as value , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where[Module attest] = 'Geslaagd' and MONTH([Module begindatum]) < 7 group by module , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) order by  YEAR([Module begindatum]), semester", table, navigator, "MensenGeslaagdSem1", part);

                //Geslaagde mensen / module per semester
                //semester 2
                AddTableInBookmark("select Module, COUNT([Module attest]) as value , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where[Module attest] = 'Geslaagd' and MONTH([Module begindatum]) > 7 group by module , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) order by  YEAR([Module begindatum]), semester", table, navigator, "MensenGeslaagdSem2", part);



                //Aantal afgestudeerden /semester

                //semester 1
                AddTableInBookmarkWithoutGroups("select COUNT(Stamnummer) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Module = 'Module Toegepaste verpleegkunde (40 weken)' and[Module attest] = 'Geslaagd' and MONTH([Module begindatum]) < 7 group by  CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum])", table, navigator, "AantalAfgestudeerdeStudentenSem1", part);

                //semester 2
                AddTableInBookmarkWithoutGroups("select COUNT(Stamnummer) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Module = 'Module Toegepaste verpleegkunde (40 weken)' and[Module attest] = 'Geslaagd' and MONTH([Module begindatum]) > 7 group by  CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum])", table, navigator, "AantalAfgestudeerdeStudentenSem2", part);


                //RedenStoppen
                //Klopt
                //semester 1
                AddTableInBookmark("select[Reden stoppen] ,count([Reden stoppen]) as value,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester , YEAR([Module begindatum]) as jaar from tblStudentGegevens where [Reden stoppen] != '' and MONTH([Module begindatum]) < 7 group by [Reden stoppen],CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) order by  YEAR([Module begindatum]) ASC, semester ASC ", table, navigator, "RedenStoppenSem1", part);

                //semester 2
                AddTableInBookmark("select[Reden stoppen] ,count([Reden stoppen]) as value,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester , YEAR([Module begindatum]) as jaar from tblStudentGegevens where [Reden stoppen] != '' and MONTH([Module begindatum]) > 7 group by [Reden stoppen],CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) order by  YEAR([Module begindatum]) ASC, semester ASC ", table, navigator, "RedenStoppenSem2", part);


                //school leren kennen
                //Klopt
                //semester 1
                AddTableInBookmark("select coalesce(nullif([School leren kennen],''), 'onbekend') as [school leren kennen], count([School leren kennen]) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Module = 'Module Initiatie verpleegkunde (20 weken)' and MONTH([Module begindatum]) < 7 group by [School leren kennen], CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) order by  YEAR([Module begindatum]) ASC, semester ASC", table, navigator, "SchoolLerenKennenSem1", part);

                //semester 2
                AddTableInBookmark("select coalesce(nullif([School leren kennen],''), 'onbekend') as [school leren kennen], count([School leren kennen]) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Module = 'Module Initiatie verpleegkunde (20 weken)' and MONTH([Module begindatum]) > 7 group by [School leren kennen], CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) order by  YEAR([Module begindatum]) ASC, semester ASC", table, navigator, "SchoolLerenKennenSem2", part);


                ////Aantal modules dat hernomen worden per module per semester*
                ////semester 1

                //// AddTableInBookmark("select Module, count(Module) as value ,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where [Verleende studiebewijzen 1ste zit] = '' and[Reden stoppen] = '' and[Klas vorig schooljaar] = '' and MONTH([Module begindatum]) < 7 group by Module,  CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) order by  YEAR([Module begindatum]) ASC, semester ASC", table, navigator, "ModuleHernemenSem1", part);

                ////semester 2
                //if (ConnectDatabase.ExecuteQuery("create or alter view StudentenMetEenVorigeKlas as select Module as module,[Module attest] as moduleAttest, REPLACE([Klas vorig schooljaar], ' ', '') as VorigeKlas  ,Klas as Klas,[Module begindatum] as begindatum from tblStudentGegevens where[Klas vorig schooljaar]  != ''"))
                //{
                //    if (ConnectDatabase.ExecuteQuery())
                //        AddTableInBookmark("select Module, count(Module) as value ,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where [Verleende studiebewijzen 1ste zit] = '' and[Reden stoppen] = '' and[Klas vorig schooljaar] = '' and MONTH([Module begindatum]) > 7 group by Module,  CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) order by  YEAR([Module begindatum]) ASC, semester ASC", table, navigator, "ModuleHernemenSem2", part);
                //}



                /******************/

                //Gemiddelde duur aantal semesters van de opleiding / student PER MOdule per afstudeerjaar (andere functie nodig)
                if (ConnectDatabase.ExecuteQuery("create or alter view GeslaagdeStudenten as select Stamnummer, Module from tblStudentGegevens where Module = 'Module Toegepaste verpleegkunde (40 weken)' and[Module attest] = 'Geslaagd'"))
                {
                    if (ConnectDatabase.ExecuteQuery("create or alter view AantalModulesPerAfgestudeerdeStudent as select count(tblStudentGegevens.Module) as aantalModules, GeslaagdeStudenten.Stamnummer from tblStudentGegevens INNER JOIN GeslaagdeStudenten ON tblStudentGegevens.Stamnummer = GeslaagdeStudenten.Stamnummer group by   GeslaagdeStudenten.Stamnummer"))
                    {
                        AddTableInBookmarkWithoutGroups("select ROUND(AVG(CAST(AantalModulesPerAfgestudeerdeStudent.aantalModules as float)),2)  as value, YEAR([Module begindatum]) as jaar from tblStudentGegevens INNER JOIN AantalModulesPerAfgestudeerdeStudent ON tblStudentGegevens.Stamnummer = AantalModulesPerAfgestudeerdeStudent.Stamnummer Group by YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5)", table, navigator, "GemiddeldeDuur", part);
                    }
                }


                //Percentage meisjes jongens
                if (ConnectDatabase.ExecuteQuery("create or alter view TotaalAantalStudentenPerSemester as select Count(Stamnummer) as 'value' , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens group  by CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) "))
                {
                    if (ConnectDatabase.ExecuteQuery("create or alter view TotaalAantalVrouwenPerSemester as select Count(Stamnummer) as 'value', CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Geslacht = 'V' group  by CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) "))
                    {
                        if (ConnectDatabase.ExecuteQuery("create or alter view TotaalAantalMannenPerSemester as select Count(Stamnummer) as 'value' , Geslacht, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Geslacht = 'M' group  by Geslacht, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5)"))
                        {
                            //Mannen
                            AddTableInBookmarkWithoutGroups("select CAST(ROUND(CAST(TotaalAantalMannenPerSemester.value as float) / CAST(TotaalAantalStudentenPerSemester.value as float) * 100,2) AS nvarchar(50)) +'%' as value , TotaalAantalStudentenPerSemester.semester, TotaalAantalStudentenPerSemester.jaar from TotaalAantalStudentenPerSemester join TotaalAantalMannenPerSemester on(TotaalAantalMannenPerSemester.jaar = TotaalAantalStudentenPerSemester.jaar and TotaalAantalMannenPerSemester.semester = TotaalAantalStudentenPerSemester.semester) where TotaalAantalStudentenPerSemester.jaar >= (Year(GETDATE()) - 5) and TotaalAantalMannenPerSemester.semester = 1 ", table, navigator, "VerhoudingManSem1", part);
                            AddTableInBookmarkWithoutGroups("select CAST(ROUND(CAST(TotaalAantalMannenPerSemester.value as float) / CAST(TotaalAantalStudentenPerSemester.value as float) * 100,2) AS nvarchar(50)) +'%' as value , TotaalAantalStudentenPerSemester.semester, TotaalAantalStudentenPerSemester.jaar from TotaalAantalStudentenPerSemester join TotaalAantalMannenPerSemester on(TotaalAantalMannenPerSemester.jaar = TotaalAantalStudentenPerSemester.jaar and TotaalAantalMannenPerSemester.semester = TotaalAantalStudentenPerSemester.semester) where TotaalAantalStudentenPerSemester.jaar >= (Year(GETDATE()) - 5) and TotaalAantalMannenPerSemester.semester = 2 ", table, navigator, "VerhoudingManSem2", part);

                            //Vrouwen
                            AddTableInBookmarkWithoutGroups(" select CAST(ROUND(CAST(TotaalAantalVrouwenPerSemester.value as float) / CAST(TotaalAantalStudentenPerSemester.value as float) * 100,2) AS nvarchar(50)) +'%' as value , TotaalAantalStudentenPerSemester.semester, TotaalAantalStudentenPerSemester.jaar from TotaalAantalStudentenPerSemester join TotaalAantalVrouwenPerSemester on(TotaalAantalVrouwenPerSemester.jaar = TotaalAantalStudentenPerSemester.jaar and TotaalAantalVrouwenPerSemester.semester = TotaalAantalStudentenPerSemester.semester) where TotaalAantalStudentenPerSemester.jaar >= (Year(GETDATE()) - 5) and TotaalAantalVrouwenPerSemester.semester = 1", table, navigator, "VerhoudingVrouwSem1", part);
                            AddTableInBookmarkWithoutGroups(" select CAST(ROUND(CAST(TotaalAantalVrouwenPerSemester.value as float) / CAST(TotaalAantalStudentenPerSemester.value as float) * 100,2) AS nvarchar(50)) +'%' as value , TotaalAantalStudentenPerSemester.semester, TotaalAantalStudentenPerSemester.jaar from TotaalAantalStudentenPerSemester join TotaalAantalVrouwenPerSemester on(TotaalAantalVrouwenPerSemester.jaar = TotaalAantalStudentenPerSemester.jaar and TotaalAantalVrouwenPerSemester.semester = TotaalAantalStudentenPerSemester.semester) where TotaalAantalStudentenPerSemester.jaar >= (Year(GETDATE()) - 5) and TotaalAantalVrouwenPerSemester.semester = 2", table, navigator, "VerhoudingVrouwSem2", part);
                        }
                    }
                }



                testdoc.SaveToFile(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\output.docx", FileFormat.Docx2013);
                System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\output.docx");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Er is een onverwachte fout opgetreden bij het exporten van de data: " + ex, "Fout", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #27
0
        /// <summary>
        /// Replace a specific content in the Word document with another document
        /// </summary>
        /// <returns>Return the created Word document as stream</returns>
        public MemoryStream AdvancedReplace(string documentType, string button)
        {
            string basePath         = _hostingEnvironment.WebRootPath;
            string dataPathTemp     = basePath + @"/DocIO/SourceTemplate1.doc";
            string dataPathTemplate = basePath + @"/DocIO/SourceTemplate2.doc";
            string dataPathMaster   = basePath + @"/DocIO/MasterTemplate.doc";
            //Load Template document stream.
            FileStream fileStream = new FileStream(dataPathMaster, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            if (button == "View Template")
            {
                MemoryStream ms = new MemoryStream();
                fileStream.Position = 0;
                fileStream.CopyTo(ms);
                fileStream.Dispose();
                return(ms);
            }
            fileStream = null;
            //Creating new documents.
            WordDocument docSource1 = new WordDocument();
            WordDocument docSource2 = new WordDocument();
            WordDocument docMaster  = new WordDocument();

            //Load Templates.
            fileStream = new FileStream(dataPathTemp, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            docSource1.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;
            fileStream = new FileStream(dataPathTemplate, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            docSource2.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;
            fileStream = new FileStream(dataPathMaster, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            docMaster.Open(fileStream, FormatType.Doc);
            fileStream.Dispose();
            fileStream = null;
            //Search for a string and store in TextSelection
            //The TextSelection copies a text segment with formatting.
            TextSelection selection1 = docSource1.Find("PlaceHolder text is replaced with this formatted animated text", false, false);
            //Get the text segment to replace the tex across multiple paragraphs
            TextBodyPart replacePart = new TextBodyPart(docSource2);

            foreach (TextBodyItem bodyItem in docSource2.LastSection.Body.ChildEntities)
            {
                replacePart.BodyItems.Add(bodyItem.Clone());
            }
            //Replacing the placeholder inside Master Template with matches found while
            //search the two template documents.
            docMaster.Replace("PlaceHolder1", selection1, true, true, true);
            docMaster.ReplaceSingleLine((new System.Text.RegularExpressions.Regex("PlaceHolder2Start:Suppliers/Vendors of Northwind." +
                                                                                  "Customers of Northwind.Employee details of Northwind traders.The product information.The inventory details.The shippers." +
                                                                                  "PO transactions i.e Purchase Order transactions.Sales Order transaction.Inventory transactions.Invoices.PlaceHolder2End")), replacePart);

            FormatType formatType = FormatType.Docx;

            //Save as .doc format
            if (documentType == "WordDoc")
            {
                formatType = FormatType.Doc;
            }
            //Save as .xml format
            else if (documentType == "WordML")
            {
                formatType = FormatType.WordML;
            }
            //Save the document as a stream and retrun the stream
            using (MemoryStream stream = new MemoryStream())
            {
                //Save the created Word document to MemoryStream
                docMaster.Save(stream, formatType);
                docMaster.Close();
                stream.Position = 0;
                return(stream);
            }
        }
Пример #28
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                if (radioButton1.Checked)
                {
                    // Get Template files path.
                    string dataPath = Application.StartupPath + @"..\..\..\..\..\..\..\common\Data\DocIO\";

                    // Creating new documents.
                    WordDocument docSource1 = new WordDocument();
                    WordDocument docSource2 = new WordDocument();
                    WordDocument docMaster  = new WordDocument();

                    // Load Templates.
                    docSource1.Open(Path.Combine(dataPath, "TemplateSource1.doc"), FormatType.Doc);
                    docSource2.Open(Path.Combine(dataPath, "TemplateSource2.doc"), FormatType.Doc);
                    docMaster.Open(Path.Combine(dataPath, "TemplateMaster.doc"), FormatType.Doc);

                    // Search for a string and store in TextSelection
                    //The TextSelection copies a text segment with formatting.
                    TextSelection selection1 = docSource1.Find("PlaceHolder text is replaced with this formatted animated text", false, false);

                    // Search for a string and store in TextSelection
                    TextSelection selection2 = docSource2.Find(new Regex("This is the second Sentence"));

                    // Replacing the placeholder inside Master Template with matches found while
                    //search the two template documents.
                    docMaster.Replace(new Regex("PlaceHolder1"), selection1);
                    docMaster.Replace(new Regex("PlaceHolder2"), selection2);

                    //Save as doc format
                    if (wordDocRadioBtn.Checked)
                    {
                        //Saving the document to disk.
                        docMaster.Save("Sample.doc");

                        //Message box confirmation to view the created document.
                        if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
#if NETCORE
                            System.Diagnostics.Process process = new System.Diagnostics.Process();
                            process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.doc")
                            {
                                UseShellExecute = true
                            };
                            process.Start();
#else
                            System.Diagnostics.Process.Start("Sample.doc");
#endif
                            //Exit
                            this.Close();
                        }
                    }
                    //Save as docx format
                    else if (wordDocxRadioBtn.Checked)
                    {
                        //Saving the document as .docx
                        docMaster.Save("Sample.docx", FormatType.Docx);
                        //Message box confirmation to view the created document.
                        if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            try
                            {
                                //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
#if NETCORE
                                System.Diagnostics.Process process = new System.Diagnostics.Process();
                                process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.docx")
                                {
                                    UseShellExecute = true
                                };
                                process.Start();
#else
                                System.Diagnostics.Process.Start("Sample.docx");
#endif
                                //Exit
                                this.Close();
                            }
                            catch (Win32Exception ex)
                            {
                                MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                                Console.WriteLine(ex.ToString());
                            }
                        }
                    }
                    //Save as pdf format
                    else if (pdfRadioBtn.Checked)
                    {
                        DocToPDFConverter converter = new DocToPDFConverter();
                        //Convert word document into PDF document
                        PdfDocument pdfDoc = converter.ConvertToPDF(docMaster);
                        //Save the pdf file
                        pdfDoc.Save("Sample.pdf");
                        //Message box confirmation to view the created document.
                        if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            try
                            {
#if NETCORE
                                System.Diagnostics.Process process = new System.Diagnostics.Process();
                                process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.pdf")
                                {
                                    UseShellExecute = true
                                };
                                process.Start();
#else
                                System.Diagnostics.Process.Start("Sample.pdf");
#endif
                                //Exit
                                this.Close();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.ToString());
                            }
                        }
                    }
                    else
                    {
                        // Exit
                        this.Close();
                    }
                }
                else
                {
                    //Load template document
#if NETCORE
                    WordDocument doc = new WordDocument(@"..\..\..\..\..\..\..\common\Data\DocIO\original.doc");
#else
                    WordDocument doc = new WordDocument(@"..\..\..\..\..\..\common\Data\DocIO\original.doc");
#endif
                    //Load the document to be replaced
#if NETCORE
                    WordDocument replaceDoc = new WordDocument(@"..\..\..\..\..\..\..\common\Data\DocIO\Replace.doc");
#else
                    WordDocument replaceDoc = new WordDocument(@"..\..\..\..\..\..\common\Data\DocIO\Replace.doc");
#endif
                    //Set Margin of the section
                    doc.LastSection.PageSetup.Margins.All = 72;
                    //Select a table and add it to TextBodyPart
                    TextBodyPart replacePart = new TextBodyPart(replaceDoc);
                    replacePart.BodyItems.Add(replaceDoc.Sections[0].Body.Tables[0] as WTable);

                    //Replace Text with table
                    doc.Replace("INSERT TABLE", replacePart, true, true);

                    //Select text and image
                    replacePart = new TextBodyPart(replaceDoc);
                    TextBodySelection textSel = new TextBodySelection(replaceDoc.LastSection.Body, 0, replaceDoc.LastSection.Paragraphs.Count, 0, 1);
                    replacePart.Copy(textSel);

                    //Replace Text with image and text.
                    doc.Replace("INSERT PARAGRAPH ITEMS", replacePart, false, true);

                    //Save as doc format
                    if (wordDocRadioBtn.Checked)
                    {
                        //Saving the document to disk.
                        doc.Save("Sample.doc");

                        //Message box confirmation to view the created document.
                        if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
#if NETCORE
                            System.Diagnostics.Process process = new System.Diagnostics.Process();
                            process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.doc")
                            {
                                UseShellExecute = true
                            };
                            process.Start();
#else
                            System.Diagnostics.Process.Start("Sample.doc");
#endif
                            //Exit
                            this.Close();
                        }
                    }
                    //Save as docx format
                    else if (wordDocxRadioBtn.Checked)
                    {
                        //Saving the document as .docx
                        doc.Save("Sample.docx", FormatType.Docx);
                        //Message box confirmation to view the created document.
                        if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            try
                            {
                                //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
#if NETCORE
                                System.Diagnostics.Process process = new System.Diagnostics.Process();
                                process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.docx")
                                {
                                    UseShellExecute = true
                                };
                                process.Start();
#else
                                System.Diagnostics.Process.Start("Sample.docx");
#endif
                                //Exit
                                this.Close();
                            }
                            catch (Win32Exception ex)
                            {
                                MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                                Console.WriteLine(ex.ToString());
                            }
                        }
                    }
                    //Save as pdf format
                    else if (pdfRadioBtn.Checked)
                    {
                        DocToPDFConverter converter = new DocToPDFConverter();
                        //Convert word document into PDF document
                        PdfDocument pdfDoc = converter.ConvertToPDF(doc);
                        //Save the pdf file
                        pdfDoc.Save("Sample.pdf");
                        //Message box confirmation to view the created document.
                        if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            try
                            {
                                //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
#if NETCORE
                                System.Diagnostics.Process process = new System.Diagnostics.Process();
                                process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.pdf")
                                {
                                    UseShellExecute = true
                                };
                                process.Start();
#else
                                System.Diagnostics.Process.Start("Sample.pdf");
#endif
                                //Exit
                                this.Close();
                            }
                            catch (Exception ex)
                            {
                                MessageBoxAdv.Show("PDF Viewer is not installed in this system");
                                Console.WriteLine(ex.ToString());
                            }
                        }
                    }
                    else
                    {
                        // Exit
                        this.Close();
                    }
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
Пример #29
0
        public ActionResult BookmarkNavigation(string Group1)
        {
            if (Group1 == null)
            {
                return(View());
            }
            #region BookmarkNavigation
            // Creating a new document.
            WordDocument document = new WordDocument();
            //Adds section with one empty paragraph to the Word document
            document.EnsureMinimal();
            //sets the page margins
            document.LastSection.PageSetup.Margins.All = 72f;
            //Appends bookmark to the paragraph
            document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
            document.LastParagraph.AppendText("Northwind database with normalization concept");
            document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
            // Open an existing template document with single section to get Northwind.information
            WordDocument nwdInformation = new WordDocument(ResolveApplicationDataPath("Bookmark_Template.doc", "App_Data\\DocIO"));
            // Open an existing template document with multiple section to get Northwind data.
            WordDocument templateDocument = new WordDocument(ResolveApplicationDataPath("BkmkDocumentPart_Template.doc", "App_Data\\DocIO"));
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the template document.
            BookmarksNavigator bk = new BookmarksNavigator(templateDocument);
            // Move to the NorthWind bookmark in template document
            bk.MoveToBookmark("NorthWind");
            //Gets the bookmark content as WordDocumentPart
            WordDocumentPart documentPart = bk.GetContent();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the Northwind information document.
            bk = new BookmarksNavigator(nwdInformation);
            // Move to the information bookmark
            bk.MoveToBookmark("Information");
            // Get the content of information bookmark.
            TextBodyPart bodyPart = bk.GetBookmarkContent();
            // Creating a bookmark navigator. Which help us to navigate through the
            // bookmarks in the destination document.
            bk = new BookmarksNavigator(document);
            // Move to the NorthWind database in the destination document
            bk.MoveToBookmark("NorthwindDatabase");
            //Replace the bookmark content using word document parts
            bk.ReplaceContent(documentPart);
            // Move to the Northwind_Information in the destination document
            bk.MoveToBookmark("Northwind_Information");
            // Replacing content of Northwind_Information bookmark.
            bk.ReplaceBookmarkContent(bodyPart);
            // Move to the text bookmark
            bk.MoveToBookmark("Text");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting text inside the bookmark. This will preserve the source formatting
            bk.InsertText("Northwind Database contains the following table:");
            #region tableinsertion
            WTable tbl = new WTable(document);
            tbl.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.None;
            tbl.TableFormat.IsAutoResized      = true;
            tbl.ResetCells(8, 2);
            IWParagraph paragraph;
            tbl.Rows[0].IsHeader = true;
            paragraph            = tbl[0, 0].AddParagraph();
            paragraph.AppendText("Suppliers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[0, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 0].AddParagraph();
            paragraph.AppendText("Customers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[1, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 0].AddParagraph();
            paragraph.AppendText("Employees");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[2, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 0].AddParagraph();
            paragraph.AppendText("Products");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[3, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 0].AddParagraph();
            paragraph.AppendText("Inventory");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[4, 1].AddParagraph();
            paragraph.AppendText("2");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 0].AddParagraph();
            paragraph.AppendText("Shippers");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[5, 1].AddParagraph();
            paragraph.AppendText("1");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 0].AddParagraph();
            paragraph.AppendText("PO Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[6, 1].AddParagraph();
            paragraph.AppendText("3");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 0].AddParagraph();
            paragraph.AppendText("Sales Transactions");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            paragraph = tbl[7, 1].AddParagraph();
            paragraph.AppendText("7");
            paragraph.BreakCharacterFormat.FontName = "Calibri";
            paragraph.BreakCharacterFormat.FontSize = 10;

            bk.InsertTable(tbl);
            #endregion tableinsertion
            //Move to image bookmark
            bk.MoveToBookmark("Image");
            //Deletes the bookmark content
            bk.DeleteBookmarkContent(true);
            // Inserting image to the bookmark.
            IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
            pic.LoadImage(System.Drawing.Image.FromFile(ResolveApplicationDataPath("Northwind.png", "Content\\DocIO")));
            pic.WidthScale  = 50f; // It reduce the image size because it don't fit
            pic.HeightScale = 75f; // in document page.
            #endregion BookmarkNavigation

            #region Document SaveOption
            //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));
            }
            #endregion Document SaveOption
            return(View());
        }
Пример #30
0
        private async void btnGuardar_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            try
            {
                if (document != null)
                {
                    document.Close();
                    document = null;
                }
                if (document == null)
                {
                    document  = new WordDocument();
                    docStream = File.OpenRead(Path.GetFullPath(sFilePathWord));
                    await document.OpenAsync(docStream, FormatType.Docx);

                    docStream.Dispose();
                }
                foreach (var x in textBoxes)
                {
                    replace(x.Name, x.Text, sFilePathWord);
                }
                foreach (var z in richEditBoxes)
                {
                    string valor;
                    z.TextDocument.GetText(Windows.UI.Text.TextGetOptions.None, out valor);
                    replace(z.Name, valor, sFilePathWord);
                }
                foreach (var x in comboBoxes)
                {
                    if (x.SelectedItem == null)
                    {
                        replace(x.Name, "", sFilePathWord);
                    }
                    else
                    if (x.Name.ToLower().Contains("nombre_tutor"))
                    {
                        replace("Grupo", (x.SelectedItem as TutoresProfesores).grupo + " de " + (x.SelectedItem as TutoresProfesores).semestre + " semestre", sFilePathWord);
                        replace("Correo", (x.SelectedItem as TutoresProfesores).correo, sFilePathWord);
                        if ((x.SelectedItem as TutoresProfesores).imagen != null)
                        {
                            //TextSelection textSelections = document.Find(new Regex("^<[Imagen]>"));
                            Stream     imageStream = (x.SelectedItem as TutoresProfesores).imagen;
                            WParagraph paragraph   = new WParagraph(document);
                            WPicture   picture     = paragraph.AppendPicture(imageStream) as WPicture;
                            picture.Width  = 60;
                            picture.Height = 60;
                            TextSelection newSelection = new TextSelection(paragraph, 0, 1);
                            TextBodyPart  bodyPart     = new TextBodyPart(document);
                            bodyPart.BodyItems.Add(paragraph);
                            document.Replace("<[Imagen]>", bodyPart, true, true);
                        }
                        replace(x.Name, x.SelectedItem.ToString(), sFilePathWord);
                    }
                    replace(x.Name, x.SelectedItem.ToString(), sFilePathWord);
                }
                foreach (var fecha in datePickers)
                {
                    if (fecha.SelectedDate == null)
                    {
                        fecha.SelectedDate = DateTime.UtcNow;
                    }
                    if (fecha.Name.ToLower().Contains("año"))
                    {
                        replace(fecha.Name, fecha.Date.DateTime.ToString("yyyy"), sFilePathWord);
                    }
                    else
                    {
                        replace(fecha.Name, fecha.Date.DateTime.ToString("MMMM"), sFilePathWord);
                    }
                }
                foreach (var dp in calendarDatePickers)
                {
                    if (dp.Date.Value.DateTime == null)
                    {
                        dp.Date = DateTime.UtcNow;
                    }
                    replace(dp.Name, dp.Date.Value.DateTime.ToString("dd/MMMM/yyyy"), sFilePathWord);
                }
                if (checkBoxes != null)
                {
                    foreach (var cb in checkBoxes)
                    {
                        if (cb.IsChecked == true)
                        {
                            replace(cb.Name, "x", sFilePathWord);
                        }
                        else
                        {
                            replace(cb.Name, "", sFilePathWord);
                        }
                    }
                }
                replace("Jefe_Tutorias", await DBAssets.getStringAsync((App.Current as App).ConnectionString, "SELECT nombre FROM CoordinadoresTutorias;"), sFilePathWord);
                replace("Jefe_Departamento", await DBAssets.getStringAsync((App.Current as App).ConnectionString, "SELECT nombre FROM JefesDepartamentos WHERE id_jefe = 1;"), sFilePathWord);
                replace("Jefe_Tutorias_Institucional", await DBAssets.getStringAsync((App.Current as App).ConnectionString, "SELECT nombre FROM CoordinadoresTutoriasInstitucionales;"), sFilePathWord);
                replace("Jefe_Desarrollo_Académico", await DBAssets.getStringAsync((App.Current as App).ConnectionString, "SELECT nombre FROM JefesDepartamentos WHERE id_jefe = 2;"), sFilePathWord);

                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = "Resultado";
                savePicker.FileTypeChoices.Add("Word Documents", new List <string>()
                {
                    ".docx"
                });
                StorageFile outputStorageFile = await savePicker.PickSaveFileAsync();

                await document.SaveAsync(outputStorageFile, FormatType.Docx);
            }
            catch (Exception ex)
            {
                var err = new MessageDialog("Unable to open File!" + ex.Message);
                await err.ShowAsync();
            }
        }