private void button1_Click(object sender, EventArgs e) { //Load the document from disk. Document doc = new Document(); doc.LoadFromFile(@"..\..\..\..\..\..\Data\Bookmark.docx"); //Get the bookmark by name. Bookmark bookmark = doc.Bookmarks["Test"]; DocumentObject docObj = null; //Judge if the paragraph includes the bookmark exists in the table, if it exists in cell, //Then need to find its outermost parent object(Table), //and get the start/end index of current object on body. if ((bookmark.BookmarkStart.Owner as Paragraph).IsInCell) { docObj = bookmark.BookmarkStart.Owner.Owner.Owner.Owner; } else { docObj = bookmark.BookmarkStart.Owner; } int startIndex = doc.Sections[0].Body.ChildObjects.IndexOf(docObj); if ((bookmark.BookmarkEnd.Owner as Paragraph).IsInCell) { docObj = bookmark.BookmarkEnd.Owner.Owner.Owner.Owner; } else { docObj = bookmark.BookmarkEnd.Owner; } int endIndex = doc.Sections[0].Body.ChildObjects.IndexOf(docObj); //Get the start/end index of the bookmark object on the paragraph. Paragraph para = bookmark.BookmarkStart.Owner as Paragraph; int pStartIndex = para.ChildObjects.IndexOf(bookmark.BookmarkStart); para = bookmark.BookmarkEnd.Owner as Paragraph; int pEndIndex = para.ChildObjects.IndexOf(bookmark.BookmarkEnd); //Get the content of current bookmark and copy. TextBodySelection select = new TextBodySelection(doc.Sections[0].Body, startIndex, endIndex, pStartIndex, pEndIndex); TextBodyPart body = new TextBodyPart(select); for (int i = 0; i < body.BodyItems.Count; i++) { doc.Sections[0].Body.ChildObjects.Add(body.BodyItems[i].Clone()); } //Save the document. doc.SaveToFile("CopyBookmarkContent.docx", FileFormat.Docx); //Launch the Word file. FileViewer("CopyBookmarkContent.docx"); }
private void button1_Click(object sender, System.EventArgs e) { try { if (radioButton1.Checked) { // Get Template files path. string dataPath = Application.StartupPath + @"..\..\..\..\..\..\..\common\Data\DocIO\"; // Creating new documents. WordDocument docSource1 = new WordDocument(); WordDocument docSource2 = new WordDocument(); WordDocument docMaster = new WordDocument(); // Load Templates. docSource1.Open(Path.Combine(dataPath, "TemplateSource1.doc"), FormatType.Doc); docSource2.Open(Path.Combine(dataPath, "TemplateSource2.doc"), FormatType.Doc); docMaster.Open(Path.Combine(dataPath, "TemplateMaster.doc"), FormatType.Doc); // Search for a string and store in TextSelection //The TextSelection copies a text segment with formatting. TextSelection selection1 = docSource1.Find("PlaceHolder text is replaced with this formatted animated text", false, false); // Search for a string and store in TextSelection TextSelection selection2 = docSource2.Find(new Regex("This is the second Sentence")); // Replacing the placeholder inside Master Template with matches found while //search the two template documents. docMaster.Replace(new Regex("PlaceHolder1"), selection1); docMaster.Replace(new Regex("PlaceHolder2"), selection2); //Save as doc format if (wordDocRadioBtn.Checked) { //Saving the document to disk. docMaster.Save("Sample.doc"); //Message box confirmation to view the created document. if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer] #if NETCORE System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.doc") { UseShellExecute = true }; process.Start(); #else System.Diagnostics.Process.Start("Sample.doc"); #endif //Exit this.Close(); } } //Save as docx format else if (wordDocxRadioBtn.Checked) { //Saving the document as .docx docMaster.Save("Sample.docx", FormatType.Docx); //Message box confirmation to view the created document. if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { try { //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer] #if NETCORE System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.docx") { UseShellExecute = true }; process.Start(); #else System.Diagnostics.Process.Start("Sample.docx"); #endif //Exit this.Close(); } catch (Win32Exception ex) { MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system"); Console.WriteLine(ex.ToString()); } } } //Save as pdf format else if (pdfRadioBtn.Checked) { DocToPDFConverter converter = new DocToPDFConverter(); //Convert word document into PDF document PdfDocument pdfDoc = converter.ConvertToPDF(docMaster); //Save the pdf file pdfDoc.Save("Sample.pdf"); //Message box confirmation to view the created document. if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { try { #if NETCORE System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.pdf") { UseShellExecute = true }; process.Start(); #else System.Diagnostics.Process.Start("Sample.pdf"); #endif //Exit this.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } else { // Exit this.Close(); } } else { //Load template document #if NETCORE WordDocument doc = new WordDocument(@"..\..\..\..\..\..\..\common\Data\DocIO\original.doc"); #else WordDocument doc = new WordDocument(@"..\..\..\..\..\..\common\Data\DocIO\original.doc"); #endif //Load the document to be replaced #if NETCORE WordDocument replaceDoc = new WordDocument(@"..\..\..\..\..\..\..\common\Data\DocIO\Replace.doc"); #else WordDocument replaceDoc = new WordDocument(@"..\..\..\..\..\..\common\Data\DocIO\Replace.doc"); #endif //Set Margin of the section doc.LastSection.PageSetup.Margins.All = 72; //Select a table and add it to TextBodyPart TextBodyPart replacePart = new TextBodyPart(replaceDoc); replacePart.BodyItems.Add(replaceDoc.Sections[0].Body.Tables[0] as WTable); //Replace Text with table doc.Replace("INSERT TABLE", replacePart, true, true); //Select text and image replacePart = new TextBodyPart(replaceDoc); TextBodySelection textSel = new TextBodySelection(replaceDoc.LastSection.Body, 0, replaceDoc.LastSection.Paragraphs.Count, 0, 1); replacePart.Copy(textSel); //Replace Text with image and text. doc.Replace("INSERT PARAGRAPH ITEMS", replacePart, false, true); //Save as doc format if (wordDocRadioBtn.Checked) { //Saving the document to disk. doc.Save("Sample.doc"); //Message box confirmation to view the created document. if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer] #if NETCORE System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.doc") { UseShellExecute = true }; process.Start(); #else System.Diagnostics.Process.Start("Sample.doc"); #endif //Exit this.Close(); } } //Save as docx format else if (wordDocxRadioBtn.Checked) { //Saving the document as .docx doc.Save("Sample.docx", FormatType.Docx); //Message box confirmation to view the created document. if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { try { //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer] #if NETCORE System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.docx") { UseShellExecute = true }; process.Start(); #else System.Diagnostics.Process.Start("Sample.docx"); #endif //Exit this.Close(); } catch (Win32Exception ex) { MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system"); Console.WriteLine(ex.ToString()); } } } //Save as pdf format else if (pdfRadioBtn.Checked) { DocToPDFConverter converter = new DocToPDFConverter(); //Convert word document into PDF document PdfDocument pdfDoc = converter.ConvertToPDF(doc); //Save the pdf file pdfDoc.Save("Sample.pdf"); //Message box confirmation to view the created document. if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { try { //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer] #if NETCORE System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.pdf") { UseShellExecute = true }; process.Start(); #else System.Diagnostics.Process.Start("Sample.pdf"); #endif //Exit this.Close(); } catch (Exception ex) { MessageBoxAdv.Show("PDF Viewer is not installed in this system"); Console.WriteLine(ex.ToString()); } } } else { // Exit this.Close(); } } } catch (Exception Ex) { MessageBox.Show(Ex.Message); } }
/// <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); } }