Example #1
0
        static string ReplaceBookMarks <T>(string path, string contentPath, T model)
        {
            try
            {
                var doc = new Document(path);
                var bks = doc.Bookmarks;
                BookmarksNavigator nav = new BookmarksNavigator(doc);
                var      props         = typeof(T).GetProperties().Where(x => x.CustomAttributes.Count() != 0).ToList();
                Bookmark bk            = null;
                //遍历属性
                foreach (var prop in props)
                {
                    var propAttr = prop.GetCustomAttribute(typeof(BkNameAttribute), false);
                    if (propAttr == null)
                    {
                        continue;
                    }
                    var propAttrVal = (propAttr as BkNameAttribute).DisplayName;

                    if (propAttrVal.Contains("_"))//带选型的标签
                    {
                        var propVal = prop.GetValue(model);
                        bk = bks.FindByName(propAttrVal + propVal);
                        if (bk == null)
                        {
                            continue;
                        }
                        nav.MoveToBookmark(propAttrVal + propVal);
                        nav.ReplaceBookmarkContent("", true);
                        continue;
                    }
                    bk = bks.FindByName(propAttrVal);
                    if (bk == null)
                    {
                        continue;
                    }
                    nav.MoveToBookmark(bk.Name);
                    var value = prop.GetValue(model);
                    if (string.IsNullOrEmpty(value.ToString()))
                    {
                        continue;
                    }
                    nav.ReplaceBookmarkContent(value.ToString(), true);
                }

                doc.SaveToFile("doc.docx", FileFormat.Docx);
                doc.Clone().Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return("ok");
        }
        /// <summary>
        /// Replaces the contents of an existing <paramref name="bookmark"/> with <paramref name="text"/>
        /// </summary>
        /// <param name="bookmark"></param>
        /// <param name="text"></param>
        public BookmarkHelper ReplaceBookmarkWithText(string bookmark, string text)
        {
            // Moves the virtual cursor to the location before the end of the bookmark "Northwind"
            _bookmarkNavigator.MoveToBookmark(bookmark);


            // Replaces the contents of an existing bookmark with simple text
            _bookmarkNavigator.ReplaceBookmarkContent(text, true);

            // Returns this for Fluent API simulation
            return(this);
        }
Example #3
0
        static string ReplaceBookMarks <T>(string path, T model)
        {
            var doc = new Document(path);
            var bks = doc.Bookmarks;
            BookmarksNavigator nav = new BookmarksNavigator(doc);
            var props = typeof(T).GetProperties();

            for (int k = 0; k < bks.Count; k++)
            {
                var i = bks[k];

                nav.MoveToBookmark(i.Name);
                object value = string.Empty;

                var prop = props.FirstOrDefault(_ =>
                                                ((BkNameAttribute)_.GetCustomAttribute(typeof(BkNameAttribute), false)).DisplayName.Equals(i.Name));
                value = prop?.GetValue(model);
                if (value != null)
                {
                    nav.ReplaceBookmarkContent(value.ToString(), true);
                }
            }

            doc.SaveToFile("doc.docx", FileFormat.Docx);
            return("ok");
        }
        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);
        }
        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);
        }
        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);
        }
Example #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            Document doc = new Document();

            doc.LoadFromFile(@"..\..\..\..\..\..\..\Data\Bookmark.docx");
            //Locate the bookmark
            BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);

            bookmarkNavigator.MoveToBookmark("Test");
            //Replace the context with new.
            bookmarkNavigator.ReplaceBookmarkContent("This is replaced content.", false);

            //Save to disk.
            doc.SaveToFile("ReplaceBookMarkContent.docx", FileFormat.Docx);
            FileViewer("ReplaceBookMarkContent.docx");
        }
Example #8
0
        static string ReplaceBookMarks <T>(string path, string contentPath, T model, Action <string, string, BookmarksNavigator> AddContecnt)
        {
            try
            {
                var doc = new Document(path);
                var bks = doc.Bookmarks;
                BookmarksNavigator nav = new BookmarksNavigator(doc);
                var props = typeof(T).GetProperties();

                for (int k = 0; k < bks.Count; k++)
                {
                    var i = bks[k];

                    nav.MoveToBookmark(i.Name);
                    if (i.Name.Equals("Content"))
                    {
                        AddContecnt?.Invoke(contentPath, i.Name, nav);
                        continue;
                    }

                    object value = string.Empty;

                    var prop = props.FirstOrDefault(_ =>
                                                    ((BkNameAttribute)_.GetCustomAttribute(typeof(BkNameAttribute), false)).DisplayName.Equals(i.Name));
                    value = prop?.GetValue(model);
                    if (value != null)
                    {
                        nav.ReplaceBookmarkContent(value.ToString(), true);
                    }
                }
                doc.SaveToFile("doc.docx", FileFormat.Docx);
                doc.Clone().Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return("ok");
        }
        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);
        }
Example #10
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());
        }
        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);
        }
        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
        }
Example #13
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));
        }
        void OnButtonClicked(object sender, EventArgs e)
        {
            Assembly assembly = typeof(App).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 = 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.


            #region Saving Document
            MemoryStream stream = new MemoryStream();
            document.Save(stream, FormatType.Word2013);
            document.Close();
            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
        }
Example #16
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
            }
        }
Example #17
0
        private void GenerateButton_Click(object sender, RoutedEventArgs e)
        {
            string currentDir = Environment.CurrentDirectory;

            Document doc = new Document(currentDir + "\\template.docx", FileFormat.Docx);

            BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);

            bookmarkNavigator.MoveToBookmark("Name");
            bookmarkNavigator.ReplaceBookmarkContent(CVName.Text, true);

            bookmarkNavigator.MoveToBookmark("Position");
            bookmarkNavigator.ReplaceBookmarkContent(CVPositionResult.Text, true);

            bookmarkNavigator.MoveToBookmark("Summary");
            bookmarkNavigator.ReplaceBookmarkContent(CVSummaryResult.Text, true);

            bookmarkNavigator.MoveToBookmark("Languages");
            bookmarkNavigator.ReplaceBookmarkContent(CVLangualeResult.Text, true);

            bookmarkNavigator.MoveToBookmark("Databases");
            bookmarkNavigator.ReplaceBookmarkContent(CVDatabasesResult.Text, true);

            bookmarkNavigator.MoveToBookmark("Technologies");
            bookmarkNavigator.ReplaceBookmarkContent(CVTechnologyResult.Text, true);

            bookmarkNavigator.MoveToBookmark("Tools");
            bookmarkNavigator.ReplaceBookmarkContent(CVToolsResult.Text, true);

            bookmarkNavigator.MoveToBookmark("Langs");
            bookmarkNavigator.ReplaceBookmarkContent(CVNonPrLangualeResult.Text, true);

            string Experience = "";

            foreach (ListBoxItem c in CVExperienceResult.Items)
            {
                Experience += c.Content + "\n";
            }

            bookmarkNavigator.MoveToBookmark("Projects");
            bookmarkNavigator.ReplaceBookmarkContent(Experience, true);

            string Education = "";

            foreach (ListBoxItem c in CVEducationResult.Items)
            {
                Education += c.Content + "\n";
            }

            bookmarkNavigator.MoveToBookmark("Education");
            bookmarkNavigator.ReplaceBookmarkContent(Education, true);

            bookmarkNavigator.MoveToBookmark("Image");

            Paragraph p = new Paragraph(doc);

            if (image != null)
            {
                DocPicture Pic = p.AppendPicture(imageBtm.StreamSource);

                bookmarkNavigator.ReplaceBookmarkContent("", true);
                bookmarkNavigator.InsertParagraph(p);

                Pic.Width  = 150;
                Pic.Height = 150;
            }

            doc.SaveToFile(currentDir + "\\" + CVName.Text + ".docx", FileFormat.Docx);
        }
Example #18
0
        /// <summary>
        /// 透過既有的套印檔匯出 Word 文件 (以「編輯書籤內容」方式套印)
        /// </summary>
        /// <param name="result">回傳: 執行結果</param>
        /// <param name="msg">回傳: 訊息</param>
        /// <returns>串流資訊</returns>
        public byte[] ExportResumeByDocx_Bookmark(out bool result, out string msg)
        {
            result = true;
            msg    = "";
            MemoryStream ms = new MemoryStream();

            try
            {
                Spire.Doc.Document document = new Spire.Doc.Document();

                //載入套印檔
                //注意: 實際運作時,若同一時間有兩位以上使用者同時進行套印,會產生「無法開啟已開啟檔案」的錯誤
                //建議實作時,一個使用者執行匯出動作時先複製一個套印檔,完成套印後再將複製的檔案刪除,即可避開錯誤
                document.LoadFromFile(HttpContext.Current.Server.MapPath("~/App_Data/MyResumeSample_Bookmark.docx"));

                #region 定義樣式

                //定義樣式 BasicStyle: 一般段落文字
                ParagraphStyle style = new ParagraphStyle(document)
                {
                    Name = "Basic"
                };
                //style.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Justify;
                style.CharacterFormat.FontName = "標楷體";
                style.CharacterFormat.FontSize = 12;
                document.Styles.Add(style);

                #endregion

                //取得要套印的內容
                Resume model = new Resume();

                #region 套印內容

                BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);

                Spire.Doc.Bookmark bookmark = document.Bookmarks.FindByName("NAME");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("NAME");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Name) ? "" : model.Name, false);
                }
                bookmark = document.Bookmarks.FindByName("GENDER");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("GENDER");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Gender) ? "" : model.Gender, false);
                }
                bookmark = document.Bookmarks.FindByName("EMAIL");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("EMAIL");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Email) ? "" : model.Email, false);
                }
                bookmark = document.Bookmarks.FindByName("ADDRESS");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("ADDRESS");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Address) ? "" : model.Address, false);
                }
                bookmark = document.Bookmarks.FindByName("PHONE");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("PHONE");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Phone) ? "" : model.Phone, false);
                }
                bookmark = document.Bookmarks.FindByName("MOBILE");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("MOBILE");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Mobile) ? "" : model.Mobile, false);
                }



                Spire.Doc.Section tempSection = document.AddSection();
                string            html;
                ParagraphBase     replacementFirstItem;
                ParagraphBase     replacementLastItem;
                TextBodySelection selection;
                TextBodyPart      part;

                //HTML Contents: Desciprion1
                bookmark = document.Bookmarks.FindByName("DESCRIPTION1");
                if (bookmark != null)
                {
                    html = string.IsNullOrEmpty(model.Description1) ? "" : HttpUtility.HtmlDecode(model.Description1);
                    tempSection.AddParagraph().AppendHTML(html);
                    replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
                    replacementLastItem  = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
                    selection            = new TextBodySelection(replacementFirstItem, replacementLastItem);
                    //將內容各段落套用指定的樣式
                    for (int i = 0; i < tempSection.Paragraphs.Count; i++)
                    {
                        tempSection.Paragraphs[i].ApplyStyle("Basic");
                    }
                    part = new TextBodyPart(selection);

                    // locate the bookmark
                    bookmarkNavigator.MoveToBookmark("DESCRIPTION1");
                    //replace the content of bookmark
                    bookmarkNavigator.ReplaceBookmarkContent(part);
                    //remove temp section
                    document.Sections.Remove(tempSection);
                }

                //HTML Contents: Desciprion2
                bookmark = document.Bookmarks.FindByName("DESCRIPTION2");
                if (bookmark != null)
                {
                    tempSection = document.AddSection();
                    html        = string.IsNullOrEmpty(model.Description2) ? "" : HttpUtility.HtmlDecode(model.Description2);
                    tempSection.AddParagraph().AppendHTML(html);
                    replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
                    replacementLastItem  = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
                    selection            = new TextBodySelection(replacementFirstItem, replacementLastItem);
                    part = new TextBodyPart(selection);

                    bookmarkNavigator.MoveToBookmark("DESCRIPTION2");
                    bookmarkNavigator.ReplaceBookmarkContent(part);
                    document.Sections.Remove(tempSection);
                }

                //圖片
                bookmark = document.Bookmarks.FindByName("IMG");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("IMG");
                    Spire.Doc.Section             section_img   = document.AddSection();
                    Spire.Doc.Documents.Paragraph paragraph_img = section_img.AddParagraph();
                    Image      img     = Image.FromFile(HttpContext.Current.Server.MapPath("~/App_Data/Penguins.jpg"));
                    DocPicture picture = paragraph_img.AppendPicture(img);

                    bookmarkNavigator.InsertParagraph(paragraph_img);
                    document.Sections.Remove(section_img);
                }
                #endregion

                #region 動態新增表格

                if (model.JobHistory.Count > 0)
                {
                    Spire.Doc.Section s      = document.AddSection();
                    Spire.Doc.Table   table  = s.AddTable(true);
                    string[]          Header = { "序號", "任職公司", "職稱", "開始時間", "結束時間" };

                    //Add Cells
                    table.ResetCells(model.JobHistory.Count + 1, Header.Length);

                    //Header Row
                    TableRow FRow = table.Rows[0];
                    FRow.IsHeader = true;
                    for (int i = 0; i < Header.Length; i++)
                    {
                        Spire.Doc.Documents.Paragraph p = FRow.Cells[i].AddParagraph();
                        FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        p.Format.HorizontalAlignment = HorizontalAlignment.Center;

                        TextRange TR = p.AppendText(Header[i]);
                        TR.CharacterFormat.Bold = true;
                    }

                    //Data Row
                    model.JobHistory = model.JobHistory.OrderBy(x => x.StartDT).ToList();
                    for (int r = 0; r < model.JobHistory.Count; r++)
                    {
                        TableRow DataRow = table.Rows[r + 1];
                        string[] data    = new string[] { (r + 1).ToString(), model.JobHistory[r].CompanyName, model.JobHistory[r].JobTitle, (model.JobHistory[r].StartDT.HasValue ? model.JobHistory[r].StartDT.Value.ToShortDateString() : ""), (model.JobHistory[r].EndDT.HasValue ? model.JobHistory[r].EndDT.Value.ToShortDateString() : "") };

                        //Columns.
                        for (int c = 0; c < data.Length; c++)
                        {
                            //Cell Alignment
                            DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

                            //Fill Data in Rows
                            Spire.Doc.Documents.Paragraph p2 = DataRow.Cells[c].AddParagraph();
                            TextRange TR2 = p2.AppendText(data[c]);

                            //Format Cells
                            p2.Format.HorizontalAlignment = HorizontalAlignment.Center;
                        }
                    }

                    bookmarkNavigator.MoveToBookmark("TABLE");
                    bookmarkNavigator.InsertTable(table);
                }

                #endregion

                #region 套用樣式

                //套用文章段落樣式
                for (int s = 0; s < document.Sections.Count; s++)
                {
                    Spire.Doc.Section sections = document.Sections[s];
                    //套用文章段落樣式
                    for (int p = 0; p < sections.Paragraphs.Count; p++)
                    {
                        Spire.Doc.Documents.Paragraph pgh = sections.Paragraphs[p];
                        pgh.ApplyStyle("Basic");
                        pgh.Format.BeforeSpacing = 12;
                    }

                    //套用表格樣式
                    for (int t = 0; t < document.Sections[s].Tables.Count; t++)
                    {
                        Spire.Doc.Table table = (Spire.Doc.Table)document.Sections[s].Tables[t];
                        table.PreferredWidth            = new PreferredWidth(WidthType.Percentage, 100);
                        table.TableFormat.IsAutoResized = true;

                        //set table border
                        //table.TableFormat.Borders.Right.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Left.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Top.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Horizontal.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Vertical.BorderType = Spire.Doc.Documents.BorderStyle.Thick;

                        for (int tr = 0; tr < table.Rows.Count; tr++)
                        {
                            for (int td = 0; td < table.Rows[tr].Cells.Count; td++)
                            {
                                for (int t_ph = 0; t_ph < table.Rows[tr].Cells[td].Paragraphs.Count; t_ph++)
                                {
                                    table.Rows[tr].Cells[td].Paragraphs[t_ph].ApplyStyle("Basic");
                                }
                            }
                        }
                    }
                }

                #endregion

                //匯出
                document.SaveToStream(ms, FileFormat.Docx);
            }
            catch (Exception ex)
            {
                result = false;
                msg    = ex.Message;
            }

            if (result)
            {
                return(ms.ToArray());
            }
            else
            {
                return(null);
            }
        }
Example #19
0
        public ActionResult CreateContract(Guid callID)
        {
            var callData    = db.Calls.ToList();
            var itemsData   = db.Items.ToList();
            var custData    = db.Customers.ToList();
            var repData     = db.Representatives.ToList();
            var callDetails = db.CallDetails.ToList();
            //var progdata = db.Programs.ToList();

            var callData2 = (from c in db.CallDetails
                             join item in itemsData on c.ItemID equals item.ItemID
                             join calcdet in db.CalcDetails.ToList() on item.CalcDetailsID equals calcdet.CalcID
                             where (c.CallID == callID)
                             select new ContractViewModel.Itm {
                itemname = item.ItemName, Qty = c.ItemQty.ToString(), itemsubtype = item.ItemSubtype.ItemSubtype1, additionals = item.Additional, calcDate = calcdet.CalcDate.ToString(), calcNum = calcdet.CalcNum
            }).ToList();


            ContractViewModel contract = new ContractViewModel();

            CultureInfo ci = new CultureInfo("RU-ru");

            contract = (from cd in callData
                        join cust in custData on cd.CustomerID equals cust.CustomerID
                        join rep in repData on cust.RepresentativeID equals rep.RepresentativeID
                        join calldet in callDetails on cd.CallID equals calldet.CallID
                        join item in itemsData on calldet.ItemID equals item.ItemID

                        where (cd.CallID == (Guid)callID)
                        select new ContractViewModel {
                CallID = cd.CallID,
                callDate = cd.CallDate.ToString("dd MMMM yyyy г.", ci),
                sampleActDate = cd.SampleActDate.ToString("dd MMMM yyyy г.", ci),
                callNumber = cd.DocNumber.ToString(),
                expAffNum = cd.AffidavitNum.ToString(),
                expAffDate = cd.AffidavitDate.ToString("dd MMMM yyyy г.", ci),
                contractDate = cd.ContractDate,
                repdoc = rep.RepDoc.ToString(),
                repFName = rep.FirstName.ToString(),
                repMName = rep.MidName.ToString(),
                repFamName = rep.FamilyName.ToString(),
                repPosition = rep.Position.ToString(),
                repPhone = rep.PhoneNumber.ToString(),
                custName = cust.Name.ToString(),
                custAddress = cust.Address.ToString(),
                custTaxID = cust.TaxID.ToString(),
                custBIC = cust.BIC.ToString(),
                custPhoneNumber = cust.PhoneNumber.ToString(),
                custOKPO = cust.OKPO.ToString(),
                custAccount = cust.Account.ToString(),
                custBankBranch = cust.BankBranch.ToString(),
                custBranchAddress = cust.BranchAddress.ToString(),
                custBankCode = cust.BankCode.ToString(),
                custMPhoneNumber = cust.MPhoneNumber.ToString()
            }

                        ).FirstOrDefault();

            contract.itmList = callData2;

            ////////////////////////////////////////////////////////////////////////////////////////////////////////

            //                              ВВОД ДАННЫХ В ШАБЛОН ДОГОВОРА                                        //

            ///////////////////////////////////////////////////////////////////////////////////////////////////////


            List <string> expertData = callexp.Split(' ').Reverse().ToList();

            string expName = expertData[0] + expertData[1] + expertData[2];

            int nameIndex = callexp.IndexOf(expName);

            string expertPosition = callexp.Remove(nameIndex, expName.Length);

            string firstWordInPosition = callexp.Split(' ').First();

            int firstWordIndex = expertPosition.IndexOf(firstWordInPosition);

            string expPositionTail = expertPosition.Remove(firstWordIndex, firstWordInPosition.Length);

            CyrNounCollection      nouns = new CyrNounCollection();
            CyrAdjectiveCollection adj   = new CyrAdjectiveCollection();
            CyrPhrase phrase             = new CyrPhrase(nouns, adj);
            CyrResult expname            = phrase.Decline(expName, GetConditionsEnum.Strict);

            expName = expname.Genitive;

            CyrNoun   strict        = nouns.Get(firstWordInPosition, GetConditionsEnum.Strict);
            CyrResult expPosition   = strict.Decline();
            string    firstWordDecl = expPosition.Genitive;

            expertPosition = string.Concat(firstWordDecl, expPositionTail);

            firstWordInPosition = contract.repPosition.Split(' ').First();

            firstWordIndex = contract.repPosition.IndexOf(firstWordInPosition);

            string repPositionTail = contract.repPosition.Remove(firstWordIndex, firstWordInPosition.Length);

            CyrResult repname = phrase.Decline((contract.repFamName + contract.repFName + contract.repMName), GetConditionsEnum.Strict);
            string    repName = repname.Genitive;

            strict = nouns.Get(firstWordInPosition, GetConditionsEnum.Strict);
            CyrResult repPosition = strict.Decline();

            firstWordDecl = repPosition.Genitive;
            string representativePosition = string.Concat(firstWordDecl, expPositionTail);


            try
            {
                Document document = new Document();
                document.LoadFromFile("~/Content/FileTemplates/ContractTemplateCorporate.docx");
                BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
                bookmarkNavigator.MoveToBookmark("ContractNum");
                bookmarkNavigator.ReplaceBookmarkContent(contract.callNumber, true);

                bookmarkNavigator.MoveToBookmark("ContractDay");
                if (contract.contractDate.HasValue)
                {
                    bookmarkNavigator.ReplaceBookmarkContent((contract.contractDate?.ToString("dd", new CultureInfo("ru-RU"))), true);

                    bookmarkNavigator.MoveToBookmark("ContractMonth");
                    bookmarkNavigator.ReplaceBookmarkContent(contract.contractDate?.ToString(" MMMM ", new CultureInfo("ru-RU")), true);

                    bookmarkNavigator.MoveToBookmark("ContractYear");
                    bookmarkNavigator.ReplaceBookmarkContent(contract.contractDate?.ToString(" yyyy г.", new CultureInfo("ru-RU")), true);
                }

                else
                {
                    bookmarkNavigator.ReplaceBookmarkContent((DateTime.Today.ToString("dd", new CultureInfo("ru-RU"))), true);

                    bookmarkNavigator.MoveToBookmark("ContractMonth");
                    bookmarkNavigator.ReplaceBookmarkContent(DateTime.Today.ToString(" MMMM ", new CultureInfo("ru-RU")), true);

                    bookmarkNavigator.MoveToBookmark("ContractYear");
                    bookmarkNavigator.ReplaceBookmarkContent(DateTime.Today.ToString(" yyyy г.", new CultureInfo("ru-RU")), true);
                }

                bookmarkNavigator.MoveToBookmark("ContractExpertPosition");
                bookmarkNavigator.ReplaceBookmarkContent(expertPosition, true);

                bookmarkNavigator.MoveToBookmark("ContractExpertFullName");
                bookmarkNavigator.ReplaceBookmarkContent(expName, true);

                bookmarkNavigator.MoveToBookmark("AffidavitNum");
                bookmarkNavigator.ReplaceBookmarkContent(contract.expAffNum, true);

                bookmarkNavigator.MoveToBookmark("AffidavitDate");
                bookmarkNavigator.ReplaceBookmarkContent(contract.expAffDate, true);

                bookmarkNavigator.MoveToBookmark("CustomerName");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custName, true);

                bookmarkNavigator.MoveToBookmark("CustomerDoc");
                bookmarkNavigator.ReplaceBookmarkContent(" ", true);

                bookmarkNavigator.MoveToBookmark("RepresentativePosition");
                bookmarkNavigator.ReplaceBookmarkContent(representativePosition, true);

                bookmarkNavigator.MoveToBookmark("RepresentativeName");
                bookmarkNavigator.ReplaceBookmarkContent(repName, true);

                bookmarkNavigator.MoveToBookmark("CustomerCompanyDoc");
                bookmarkNavigator.ReplaceBookmarkContent(contract.repdoc, true);

                foreach (ContractViewModel.Itm i in contract.itmList)
                {
                    CyrResult it_name = phrase.Decline(i.itemsubtype, GetConditionsEnum.Strict);
                    i.itemsubtype = it_name.Genitive;

                    bookmarkNavigator.MoveToBookmark("ItemName");
                    bookmarkNavigator.ReplaceBookmarkContent(i.itemsubtype + i.itemname, true);

                    string progname = (from prog in db.Programs.ToList()
                                       join t in db.ItemTypes.ToList() on prog.ItemTypeID equals t.ItemTypeID
                                       join st in db.ItemSubtypes.ToList() on t.ItemTypeID equals st.ItemTypeID
                                       join item in db.Items.ToList() on st.ItemSubtypeID equals item.ItemSubtypeID
                                       where item.ItemName == i.itemname
                                       select prog.ProgramNameShort).FirstOrDefault();


                    bookmarkNavigator.MoveToBookmark("ProgramShortName");
                    bookmarkNavigator.ReplaceBookmarkContent(progname, true);

                    bookmarkNavigator.MoveToBookmark("ItemsNum");
                    bookmarkNavigator.ReplaceBookmarkContent(i.Qty, true);


                    string [] stringarr       = i.additionals.Split(' ');
                    CyrResult addCyr          = phrase.Decline(stringarr[0], GetConditionsEnum.Strict);
                    string    additionals     = addCyr.Genitive;
                    int       index           = i.additionals.IndexOf(additionals);
                    string    additionalsTail = i.additionals.Remove(index, stringarr[0].Length);

                    bookmarkNavigator.MoveToBookmark("Additionals");
                    bookmarkNavigator.ReplaceBookmarkContent(additionals + additionalsTail, true);

                    bookmarkNavigator.MoveToBookmark("CalculationOrderDate");
                    bookmarkNavigator.ReplaceBookmarkContent(i.calcDate, true);

                    bookmarkNavigator.MoveToBookmark("CalculationOrderNum");
                    bookmarkNavigator.ReplaceBookmarkContent(i.calcNum, true);
                }

                decimal TotalSum = 0;
                var     costs    = from callitem in callDetails
                                   where (callitem.CallID == callID)
                                   select callitem.ItemTestCost;
                TotalSum = costs.Sum(c => Convert.ToDecimal(c));

                bookmarkNavigator.MoveToBookmark("TotalSum");
                bookmarkNavigator.ReplaceBookmarkContent(TotalSum.ToString(), true);

                bookmarkNavigator.MoveToBookmark("TestingDurationCalDays");
                bookmarkNavigator.ReplaceBookmarkContent("30", true);

                bookmarkNavigator.MoveToBookmark("ExpertFIO");
                bookmarkNavigator.ReplaceBookmarkContent(expName, true);

                bookmarkNavigator.MoveToBookmark("RepresentativeFIO");
                bookmarkNavigator.ReplaceBookmarkContent(repName, true);

                bookmarkNavigator.MoveToBookmark("CustomerName2");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custName, true);

                bookmarkNavigator.MoveToBookmark("TaxID");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custTaxID, true);

                bookmarkNavigator.MoveToBookmark("OKPO");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custOKPO, true);

                bookmarkNavigator.MoveToBookmark("CustomerAddress");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custAddress, true);

                bookmarkNavigator.MoveToBookmark("CustomerPhoneNum");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custPhoneNumber, true);

                bookmarkNavigator.MoveToBookmark("CustomerMphoneNum");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custMPhoneNumber, true);

                bookmarkNavigator.MoveToBookmark("BankAccount");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custAccount, true);

                bookmarkNavigator.MoveToBookmark("BankBranch");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custBankBranch, true);

                bookmarkNavigator.MoveToBookmark("BankAddress");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custBranchAddress, true);

                bookmarkNavigator.MoveToBookmark("BankCode");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custBankCode, true);

                bookmarkNavigator.MoveToBookmark("BIC");
                bookmarkNavigator.ReplaceBookmarkContent(contract.custBIC, true);

                //Save doc file.

                if (document != null)
                {
                    string path = Server.MapPath(@"~\Area\Manager\Files\Contracts\");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    document.SaveToFile(path + @"docx\" + contract.CallID.ToString() + ".docx", Spire.Doc.FileFormat.Docx);
                    document.SaveToFile(path + @"pdf\" + contract.CallID.ToString() + ".pdf", Spire.Doc.FileFormat.PDF);
                    ViewBag.pdf = (path + @"pdf\" + contract.CallID.ToString() + ".pdf");
                }
            }

            catch (Exception e)
            {
                return(new HttpNotFoundResult(e.ToString()));
            }



            return(View());
        }