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"); }
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"); }
public static bool ExportWordByTemplete <T>(T model, string templeteFilePath, string targetFilePath) { try { Document doc = new Document(); doc.LoadFromFile(templeteFilePath); BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc); var bookmarks = doc.Bookmarks; while (bookmarks.Count > 0) { var bookmark = bookmarks[0]; bookmarkNavigator.MoveToBookmark(bookmark.Name, true, true); //移动到书签并清空书签原有内容 var paras = bookmark.Name.Split('_'); if (paras.Length < 3) { doc.Bookmarks.Remove(bookmark); continue; } var type = paras[0].ToLower(); var name = paras[1].ToLower(); var num = paras[2].ToLower(); switch (type) { case "table": var dataTable = GetModelValue(name, model); bookmarkNavigator.InsertTable(GetTable(doc, (DataTable)dataTable)); break; default: var text = GetModelValue(name, model); if (text != null) { bookmarkNavigator.InsertText(text.ToString()); } break; } doc.Bookmarks.Remove(bookmark); } doc.Properties.FormFieldShading = false; doc.SaveToFile(targetFilePath, FileFormat.Doc); doc.Close(); return(true); } catch (Exception ex) { string msg = ex.Message; return(false); } }
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); }
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 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); }
/// <summary> /// Delete the bookmark items. /// </summary> /// <param name="bkmkName"></param> /// <param name="document"></param> private static void DeleteBookmarkContents(string bkmkName, WordDocument document) { //Creates the bookmark navigator instance to access the bookmark BookmarksNavigator navigator = new BookmarksNavigator(document); //Moves the virtual cursor to the location before the end of the bookmark "tableOfContent". navigator.MoveToBookmark(bkmkName); //Deletes the bookmark content. navigator.DeleteBookmarkContent(false); //Gets the bookmark instance by using FindByName method of BookmarkCollection with bookmark name. Bookmark bookmark = document.Bookmarks.FindByName(bkmkName); //Removes the bookmark named "tableOfContent" from Word document. document.Bookmarks.Remove(bookmark); }
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"); }
private void button1_Click(object sender, EventArgs e) { //Create the first document Document document1 = new Document(); //Load the first document from disk. document1.LoadFromFile(@"..\..\..\..\..\..\Data\Bookmark.docx"); //Create the second document Document document2 = new Document(); //Load the second document from disk. document2.LoadFromFile(@"..\..\..\..\..\..\Data\Insert.docx"); //Get the first section of the first document Section section1 = document1.Sections[0]; //Locate the bookmark BookmarksNavigator bn = new BookmarksNavigator(document1); //Find bookmark by name bn.MoveToBookmark("Test", true, true); //Get bookmarkStart BookmarkStart start = bn.CurrentBookmark.BookmarkStart; //Get the owner paragraph Paragraph para = start.OwnerParagraph; //Get the para index int index = section1.Body.ChildObjects.IndexOf(para); //Insert the paragraphs of document2 foreach (Section section2 in document2.Sections) { foreach (Paragraph paragraph in section2.Paragraphs) { section1.Body.ChildObjects.Insert(index + 1, paragraph.Clone() as Paragraph); } } //Save the document. document1.SaveToFile("Output.docx", FileFormat.Docx); //Launch the Word file. WordDocViewer("Output.docx"); }
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"); }
/// <summary> /// Change tab leader for table of contents in the Word document. /// </summary> /// <param name="toc"></param> private static void ChangeTabLeaderForTableOfContents(TableOfContent toc, TabLeader tabLeader) { //Inserts the bookmark start before the TOC instance. BookmarkStart bkmkStart = new BookmarkStart(toc.Document, "tableOfContent"); toc.OwnerParagraph.Items.Insert(toc.OwnerParagraph.Items.IndexOf(toc), bkmkStart); Entity lastItem = FindLastTOCItem(toc); //Insert the bookmark end to next of TOC last item. BookmarkEnd bkmkEnd = new BookmarkEnd(toc.Document, "tableOfContent"); WParagraph paragraph = lastItem.Owner as WParagraph; paragraph.Items.Insert(paragraph.Items.IndexOf(lastItem) + 1, bkmkEnd); //Creates the bookmark navigator instance to access the bookmark BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(toc.Document); //Moves the virtual cursor to the location before the end of the bookmark "tableOfContent" bookmarkNavigator.MoveToBookmark("tableOfContent"); //Gets the bookmark content TextBodyPart part = bookmarkNavigator.GetBookmarkContent(); //Iterates the items from the bookmark to change the spacing in the table of content for (int i = 0; i < part.BodyItems.Count; i++) { paragraph = part.BodyItems[i] as WParagraph; //Sets the tab leader if (paragraph.ParagraphFormat.Tabs.Count != 0) { paragraph.ParagraphFormat.Tabs[0].TabLeader = tabLeader; } } //Remove the bookmark which we add to get the paragraphs in the table of contents Bookmark bookmark = toc.Document.Bookmarks.FindByName("tableOfContent"); toc.Document.Bookmarks.Remove(bookmark); }
private void button1_Click(object sender, EventArgs e) { //Load Document string input = @"..\..\..\..\..\..\Data\BookmarkTemplate.docx"; Document doc = new Document(); doc.LoadFromFile(input); //Creates a BookmarkNavigator instance to access the bookmark BookmarksNavigator navigator = new BookmarksNavigator(doc); //Locate a specific bookmark by bookmark name navigator.MoveToBookmark("Content"); TextBodyPart textBodyPart = navigator.GetBookmarkContent(); //Iterate through the items in the bookmark content to get the text string text = null; foreach (var item in textBodyPart.BodyItems) { if (item is Paragraph) { foreach (var childObject in (item as Paragraph).ChildObjects) { if (childObject is TextRange) { text += (childObject as TextRange).Text; } } } } //Save to TXT File and launch it string output = "ExtractBookmarkText.txt"; File.WriteAllText(output, text); Viewer(output); }
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); }
private static void AddContent(string originFilePath, string markName, BookmarksNavigator nav) { if (string.IsNullOrEmpty(originFilePath)) { return; } var doc = new Document(); doc.LoadFromFileInReadMode(originFilePath, FileFormat.Auto); foreach (Section sec in doc.Sections) { var parahs = sec.Paragraphs; if (parahs == null || parahs.Count == 0) { continue; } var section = sec.Clone(); section.HeadersFooters.LinkToPrevious = true; nav.Document.Sections.Add(section); } }
private void button1_Click(object sender, EventArgs e) { //Load the document string input = @"..\..\..\..\..\..\Data\Bookmark.docx"; Document doc = new Document(); doc.LoadFromFile(input); //Create an instance of BookmarksNavigator BookmarksNavigator bn = new BookmarksNavigator(doc); //Find a bookmark named Test bn.MoveToBookmark("Test", true, true); //Add a section Section section0 = doc.AddSection(); //Add a paragraph for the section Paragraph paragraph = section0.AddParagraph(); Image image = Image.FromFile(@"..\..\..\..\..\..\Data\Word.png"); //Add a picture into the paragraph DocPicture picture = paragraph.AppendPicture(image); //Add the paragraph at the position of bookmark bn.InsertParagraph(paragraph); //Remove the section0 doc.Sections.Remove(section0); //Save and launch document string output = "InsertImageAtBookmark.docx"; doc.SaveToFile(output, FileFormat.Docx); Viewer(output); }
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)); }
public IActionResult yjExportInfo(AddressRequestPayload payload) { var response = ResponseModelFactory.CreateInstance; string sWebRootFolder = _hostingEnvironment.WebRootPath + "\\UploadFiles\\ImportUserInfoWord\\"; var timeInfo = DateTime.Now.ToString("yyyyMMddHHmmss"); var wordName = timeInfo + "address.docx"; string wordUrl = sWebRootFolder + wordName; MemoryStream ms = new MemoryStream(); XWPFDocument m_Docx = new XWPFDocument(); m_Docx.Write(ms); ms.Flush(); SaveToFile(ms, wordUrl); List <string> list = new List <string>(); using (_dbContext) { Document document111 = new Document(); document111.LoadFromFile(wordUrl); Section section = document111.Sections[0]; section.Paragraphs[0].AppendBookmarkStart("picture"); section.Paragraphs[0].AppendBookmarkEnd("picture"); var user = AuthContextService.CurrentUser; string s1 = payload.Kw2; string[] s2 = s1.Split(" "); StringBuilder where = new StringBuilder(); StringBuilder sql = new StringBuilder("SELECT * FROM HomeAddress HA "); for (int i = 0; i < s2.Length; i++) { if (s2.Length > 0 && i == 0) { where.Append("WHERE "); } where.Append("HA.Address LIKE '%" + s2[i] + "%' "); if (i >= 0 && i < s2.Length - 1) { where.Append(" AND "); } } sql.Append(where); //var query = _dbContext.HomeAdd.FromSql(sql.ToString()); var query = _dbContext.HomeAddress.FromSqlRaw(sql.ToString()); if (!string.IsNullOrEmpty(payload.Kw)) { query = query.Where(x => x.Address.ToString().Contains(payload.Kw)); } if (!string.IsNullOrEmpty(payload.Kw1)) { query = query.Where(x => x.Address.ToString().Contains(payload.Kw1)); } var entities = query.ToList(); //var entities = _dbContext.HomeAddress.Where(x => ids.IndexOf(x.HomeAddressUuid.ToString()) >= 0).ToList(); for (int i = 0; i < entities.Count(); i++) { var pata = _hostingEnvironment.WebRootPath + EWM.GetEWM2("h_" + entities[i].HomeAddressUuid.ToString(), _hostingEnvironment, entities[i].Address); //实例化BookmarksNavigator类,指定需要添加图片的书签“” BookmarksNavigator bn = new BookmarksNavigator(document111); bn.MoveToBookmark("picture", true, true); //添加段落,加载图片并插入到段落 Section section0 = document111.AddSection(); Spire.Doc.Documents.Paragraph paragraph = section0.AddParagraph(); Image image = Image.FromFile(pata); DocPicture picture = document111.Sections[0].Paragraphs[0].AppendPicture(image); picture.Width = 160; picture.Height = 180; //picture.HorizontalPosition = 100.0f; //picture.VerticalPosition = 50.0f; bn.InsertParagraph(paragraph); document111.Sections.Remove(section0); //string output = sWebRootFolder + "test.docx"; document111.SaveToFile(wordUrl, FileFormat.Docx); //Arraypata = pata.; //list.Add(pata); } list.Add(wordUrl); //关闭进程 document111.Dispose(); var time = DateTime.Now.ToString("yyyyMMddHHmmssfff"); var check = ZIP.CompressMulti(list, _hostingEnvironment.WebRootPath + "\\UploadFiles\\EWM\\" + time, false); if (check) { response.SetSuccess("导出成功"); response.SetData("\\UploadFiles\\EWM\\" + time + ".zip"); } else { response.SetFailed("导出失败"); } } return(Ok(response)); }
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 } }
/// <summary> /// Default constructor /// </summary> /// <param name="wordDocument">Word document to access bookmark</param> public BookmarkHelper(IWordDocument wordDocument) { _bookmarkNavigator = new BookmarksNavigator(wordDocument); }
public IActionResult Batchs(string command, string ids) { var response = ResponseModelFactory.CreateInstance; string sWebRootFolder = _hostingEnvironment.WebRootPath + "\\UploadFiles\\ImportUserInfoWord\\"; var timeInfo = DateTime.Now.ToString("yyyyMMddHHmmss"); var wordName = timeInfo + "address.docx"; string wordUrl = sWebRootFolder + wordName; MemoryStream ms = new MemoryStream(); XWPFDocument m_Docx = new XWPFDocument(); m_Docx.Write(ms); ms.Flush(); SaveToFile(ms, wordUrl); List <string> list = new List <string>(); using (_dbContext) { //document111.LoadFromFile(sWebRootFolder + "test.docx"); Document document111 = new Document(); document111.LoadFromFile(wordUrl); Section section = document111.Sections[0]; document111.Watermark = null; section.Paragraphs[0].AppendBookmarkStart("picture"); section.Paragraphs[0].AppendBookmarkEnd("picture"); var parameters = ids.Split(",").Select((id, index) => new SqlParameter(string.Format("@p{0}", index), id)).ToList(); var parameterNames = string.Join(", ", parameters.Select(p => p.ParameterName)); var entities = _dbContext.GrabageRoom.Where(x => ids.IndexOf(x.GarbageRoomUuid.ToString()) >= 0).ToList(); for (int i = 0; i < entities.Count; i++) { var pata = _hostingEnvironment.WebRootPath + EWM.GetEWM2("d_" + entities[i].GarbageRoomUuid.ToString(), _hostingEnvironment, entities[i].Ljname); //实例化BookmarksNavigator类,指定需要添加图片的书签“” BookmarksNavigator bn = new BookmarksNavigator(document111); bn.MoveToBookmark("picture", true, true); //添加段落,加载图片并插入到段落 Section section0 = document111.AddSection(); Spire.Doc.Documents.Paragraph paragraph = section0.AddParagraph(); Image image = Image.FromFile(pata); //DocPicture picture = paragraph.AppendPicture(image); DocPicture picture = document111.Sections[0].Paragraphs[0].AppendPicture(image); picture.Width = 160; picture.Height = 180; //picture.HorizontalPosition = 100.0f; //picture.VerticalPosition = 100.0f; bn.InsertParagraph(paragraph); document111.Sections.Remove(section0); //string output = sWebRootFolder + "test.docx"; document111.SaveToFile(wordUrl, FileFormat.Docx); } list.Add(wordUrl); //关闭进程 document111.Dispose(); var time = DateTime.Now.ToString("yyyyMMddHHmmssfff"); var check = ZIP.CompressMulti(list, _hostingEnvironment.WebRootPath + "\\UploadFiles\\EWM\\" + time, false); if (check) { response.SetSuccess("导出成功"); response.SetData("\\UploadFiles\\EWM\\" + time + ".zip"); } else { response.SetFailed("导出失败"); } return(Ok(response)); } }
private void button1_Click(object sender, EventArgs e) { //Create the source document Document sourcedocument = new Document(); //Load the source document from disk. sourcedocument.LoadFromFile(@"..\..\..\..\..\..\Data\Bookmark.docx"); //Create a destination document Document destinationDoc = new Document(); //Add a section for destination document Section section = destinationDoc.AddSection(); //Add a paragraph for destination document Paragraph paragraph = section.AddParagraph(); //Locate the bookmark in source document BookmarksNavigator navigator = new BookmarksNavigator(sourcedocument); //Find bookmark by name navigator.MoveToBookmark("Test", true, true); //get text body part TextBodyPart textBodyPart = navigator.GetBookmarkContent(); //Create a TextRange type list List <TextRange> list = new List <TextRange>(); //Traverse the items of text body foreach (var item in textBodyPart.BodyItems) { //if it is paragraph if (item is Paragraph) { //Traverse the ChildObjects of the paragraph foreach (var childObject in (item as Paragraph).ChildObjects) { //if it is TextRange if (childObject is TextRange) { //Add it into list TextRange range = childObject as TextRange; list.Add(range); } } } } //Add the extract content to destinationDoc document for (int m = 0; m < list.Count; m++) { paragraph.Items.Add(list[m].Clone()); } //Save the document. destinationDoc.SaveToFile("Output.docx", FileFormat.Docx); //Launch the Word file. WordDocViewer("Output.docx"); }
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()); }
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); }
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); } }
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 }
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 }
/// <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); } }
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); }
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()); }
public static void Create() { try { //Laad de template in Document testdoc = new Document(); testdoc.LoadFromFile(AppDomain.CurrentDomain.BaseDirectory + "\\Template.docx"); //Maak table Section section = testdoc.Sections[0]; Table table = section.Tables[0] as Table; //Table table = new Table(testdoc); table.ApplyStyle(DefaultTableStyle.MediumShading1Accent1); BookmarksNavigator navigator = new BookmarksNavigator(testdoc); TextBodyPart part = new TextBodyPart(testdoc); /*Aantal studenten /module/sesmter */ //Deze tabel klopt //Aantal studenten / module /semster1 AddTableInBookmark("select Module, count(Geslacht) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where MONTH([Module begindatum]) < 7 group by module ,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE())-5) order by YEAR([Module begindatum]), semester", table, navigator, "TotaalAantalStudentenSem1", part); //Aantal studenten / module / semester2 AddTableInBookmark("select Module, count(Geslacht) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where MONTH([Module begindatum]) > 7 group by module , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE())-5) order by YEAR([Module begindatum]), semester", table, navigator, "TotaalAantalStudentenSem2", part); /*Geslaagde mensen / module per semester */ //tabellen kloppen //Semester 1 AddTableInBookmark("select Module, COUNT([Module attest]) as value , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where[Module attest] = 'Geslaagd' and MONTH([Module begindatum]) < 7 group by module , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) order by YEAR([Module begindatum]), semester", table, navigator, "MensenGeslaagdSem1", part); //Geslaagde mensen / module per semester //semester 2 AddTableInBookmark("select Module, COUNT([Module attest]) as value , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where[Module attest] = 'Geslaagd' and MONTH([Module begindatum]) > 7 group by module , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) order by YEAR([Module begindatum]), semester", table, navigator, "MensenGeslaagdSem2", part); //Aantal afgestudeerden /semester //semester 1 AddTableInBookmarkWithoutGroups("select COUNT(Stamnummer) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Module = 'Module Toegepaste verpleegkunde (40 weken)' and[Module attest] = 'Geslaagd' and MONTH([Module begindatum]) < 7 group by CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum])", table, navigator, "AantalAfgestudeerdeStudentenSem1", part); //semester 2 AddTableInBookmarkWithoutGroups("select COUNT(Stamnummer) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Module = 'Module Toegepaste verpleegkunde (40 weken)' and[Module attest] = 'Geslaagd' and MONTH([Module begindatum]) > 7 group by CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum])", table, navigator, "AantalAfgestudeerdeStudentenSem2", part); //RedenStoppen //Klopt //semester 1 AddTableInBookmark("select[Reden stoppen] ,count([Reden stoppen]) as value,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester , YEAR([Module begindatum]) as jaar from tblStudentGegevens where [Reden stoppen] != '' and MONTH([Module begindatum]) < 7 group by [Reden stoppen],CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) order by YEAR([Module begindatum]) ASC, semester ASC ", table, navigator, "RedenStoppenSem1", part); //semester 2 AddTableInBookmark("select[Reden stoppen] ,count([Reden stoppen]) as value,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester , YEAR([Module begindatum]) as jaar from tblStudentGegevens where [Reden stoppen] != '' and MONTH([Module begindatum]) > 7 group by [Reden stoppen],CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) order by YEAR([Module begindatum]) ASC, semester ASC ", table, navigator, "RedenStoppenSem2", part); //school leren kennen //Klopt //semester 1 AddTableInBookmark("select coalesce(nullif([School leren kennen],''), 'onbekend') as [school leren kennen], count([School leren kennen]) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Module = 'Module Initiatie verpleegkunde (20 weken)' and MONTH([Module begindatum]) < 7 group by [School leren kennen], CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) order by YEAR([Module begindatum]) ASC, semester ASC", table, navigator, "SchoolLerenKennenSem1", part); //semester 2 AddTableInBookmark("select coalesce(nullif([School leren kennen],''), 'onbekend') as [school leren kennen], count([School leren kennen]) as value, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Module = 'Module Initiatie verpleegkunde (20 weken)' and MONTH([Module begindatum]) > 7 group by [School leren kennen], CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) order by YEAR([Module begindatum]) ASC, semester ASC", table, navigator, "SchoolLerenKennenSem2", part); ////Aantal modules dat hernomen worden per module per semester* ////semester 1 //// AddTableInBookmark("select Module, count(Module) as value ,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where [Verleende studiebewijzen 1ste zit] = '' and[Reden stoppen] = '' and[Klas vorig schooljaar] = '' and MONTH([Module begindatum]) < 7 group by Module, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) order by YEAR([Module begindatum]) ASC, semester ASC", table, navigator, "ModuleHernemenSem1", part); ////semester 2 //if (ConnectDatabase.ExecuteQuery("create or alter view StudentenMetEenVorigeKlas as select Module as module,[Module attest] as moduleAttest, REPLACE([Klas vorig schooljaar], ' ', '') as VorigeKlas ,Klas as Klas,[Module begindatum] as begindatum from tblStudentGegevens where[Klas vorig schooljaar] != ''")) //{ // if (ConnectDatabase.ExecuteQuery()) // AddTableInBookmark("select Module, count(Module) as value ,CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where [Verleende studiebewijzen 1ste zit] = '' and[Reden stoppen] = '' and[Klas vorig schooljaar] = '' and MONTH([Module begindatum]) > 7 group by Module, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) order by YEAR([Module begindatum]) ASC, semester ASC", table, navigator, "ModuleHernemenSem2", part); //} /******************/ //Gemiddelde duur aantal semesters van de opleiding / student PER MOdule per afstudeerjaar (andere functie nodig) if (ConnectDatabase.ExecuteQuery("create or alter view GeslaagdeStudenten as select Stamnummer, Module from tblStudentGegevens where Module = 'Module Toegepaste verpleegkunde (40 weken)' and[Module attest] = 'Geslaagd'")) { if (ConnectDatabase.ExecuteQuery("create or alter view AantalModulesPerAfgestudeerdeStudent as select count(tblStudentGegevens.Module) as aantalModules, GeslaagdeStudenten.Stamnummer from tblStudentGegevens INNER JOIN GeslaagdeStudenten ON tblStudentGegevens.Stamnummer = GeslaagdeStudenten.Stamnummer group by GeslaagdeStudenten.Stamnummer")) { AddTableInBookmarkWithoutGroups("select ROUND(AVG(CAST(AantalModulesPerAfgestudeerdeStudent.aantalModules as float)),2) as value, YEAR([Module begindatum]) as jaar from tblStudentGegevens INNER JOIN AantalModulesPerAfgestudeerdeStudent ON tblStudentGegevens.Stamnummer = AantalModulesPerAfgestudeerdeStudent.Stamnummer Group by YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5)", table, navigator, "GemiddeldeDuur", part); } } //Percentage meisjes jongens if (ConnectDatabase.ExecuteQuery("create or alter view TotaalAantalStudentenPerSemester as select Count(Stamnummer) as 'value' , CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens group by CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) ")) { if (ConnectDatabase.ExecuteQuery("create or alter view TotaalAantalVrouwenPerSemester as select Count(Stamnummer) as 'value', CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Geslacht = 'V' group by CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5) ")) { if (ConnectDatabase.ExecuteQuery("create or alter view TotaalAantalMannenPerSemester as select Count(Stamnummer) as 'value' , Geslacht, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END AS semester, YEAR([Module begindatum]) as jaar from tblStudentGegevens where Geslacht = 'M' group by Geslacht, CASE WHEN MONTH([Module begindatum]) < 7 THEN 1 ELSE 2 END , YEAR([Module begindatum]) HAVING YEAR([Module begindatum]) >= (Year(GETDATE()) - 5)")) { //Mannen AddTableInBookmarkWithoutGroups("select CAST(ROUND(CAST(TotaalAantalMannenPerSemester.value as float) / CAST(TotaalAantalStudentenPerSemester.value as float) * 100,2) AS nvarchar(50)) +'%' as value , TotaalAantalStudentenPerSemester.semester, TotaalAantalStudentenPerSemester.jaar from TotaalAantalStudentenPerSemester join TotaalAantalMannenPerSemester on(TotaalAantalMannenPerSemester.jaar = TotaalAantalStudentenPerSemester.jaar and TotaalAantalMannenPerSemester.semester = TotaalAantalStudentenPerSemester.semester) where TotaalAantalStudentenPerSemester.jaar >= (Year(GETDATE()) - 5) and TotaalAantalMannenPerSemester.semester = 1 ", table, navigator, "VerhoudingManSem1", part); AddTableInBookmarkWithoutGroups("select CAST(ROUND(CAST(TotaalAantalMannenPerSemester.value as float) / CAST(TotaalAantalStudentenPerSemester.value as float) * 100,2) AS nvarchar(50)) +'%' as value , TotaalAantalStudentenPerSemester.semester, TotaalAantalStudentenPerSemester.jaar from TotaalAantalStudentenPerSemester join TotaalAantalMannenPerSemester on(TotaalAantalMannenPerSemester.jaar = TotaalAantalStudentenPerSemester.jaar and TotaalAantalMannenPerSemester.semester = TotaalAantalStudentenPerSemester.semester) where TotaalAantalStudentenPerSemester.jaar >= (Year(GETDATE()) - 5) and TotaalAantalMannenPerSemester.semester = 2 ", table, navigator, "VerhoudingManSem2", part); //Vrouwen AddTableInBookmarkWithoutGroups(" select CAST(ROUND(CAST(TotaalAantalVrouwenPerSemester.value as float) / CAST(TotaalAantalStudentenPerSemester.value as float) * 100,2) AS nvarchar(50)) +'%' as value , TotaalAantalStudentenPerSemester.semester, TotaalAantalStudentenPerSemester.jaar from TotaalAantalStudentenPerSemester join TotaalAantalVrouwenPerSemester on(TotaalAantalVrouwenPerSemester.jaar = TotaalAantalStudentenPerSemester.jaar and TotaalAantalVrouwenPerSemester.semester = TotaalAantalStudentenPerSemester.semester) where TotaalAantalStudentenPerSemester.jaar >= (Year(GETDATE()) - 5) and TotaalAantalVrouwenPerSemester.semester = 1", table, navigator, "VerhoudingVrouwSem1", part); AddTableInBookmarkWithoutGroups(" select CAST(ROUND(CAST(TotaalAantalVrouwenPerSemester.value as float) / CAST(TotaalAantalStudentenPerSemester.value as float) * 100,2) AS nvarchar(50)) +'%' as value , TotaalAantalStudentenPerSemester.semester, TotaalAantalStudentenPerSemester.jaar from TotaalAantalStudentenPerSemester join TotaalAantalVrouwenPerSemester on(TotaalAantalVrouwenPerSemester.jaar = TotaalAantalStudentenPerSemester.jaar and TotaalAantalVrouwenPerSemester.semester = TotaalAantalStudentenPerSemester.semester) where TotaalAantalStudentenPerSemester.jaar >= (Year(GETDATE()) - 5) and TotaalAantalVrouwenPerSemester.semester = 2", table, navigator, "VerhoudingVrouwSem2", part); } } } testdoc.SaveToFile(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\output.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\output.docx"); } catch (Exception ex) { MessageBox.Show("Er is een onverwachte fout opgetreden bij het exporten van de data: " + ex, "Fout", MessageBoxButton.OK, MessageBoxImage.Error); } }