public void AddWeizhu(string filename, string str) { Dictionary <string, object> dic = new Dictionary <string, object> { { "内容", this.Hulue(str.Trim()) } }; var list = _sqlhelper.GetAnySet(Setting._cijuchachongbiao, dic); string text = list[0]["来源"].ToString(); Spire.Doc.Document document = new Spire.Doc.Document(); document.LoadFromFile(filename); TextSelection[] selectionArray = document.FindAllString(str, false, true); if (selectionArray != null) { TextSelection[] selectionArray2 = selectionArray; int index = 0; while (true) { if (index >= selectionArray2.Length) { document.SaveToFile(filename); document.Dispose(); this.ClearShuiyin(filename); break; } TextSelection selection = selectionArray2[index]; Spire.Doc.Fields.Footnote entity = selection.GetAsOneRange().OwnerParagraph.AppendFootnote(Spire.Doc.FootnoteType.Endnote); entity.TextBody.AddParagraph().AppendText(text); Paragraph ownerParagraph = selection.GetAsOneRange().OwnerParagraph; ownerParagraph.ChildObjects.Insert(ownerParagraph.ChildObjects.IndexOf(selection.GetAsOneRange()) + 1, entity); index++; } } }
private void button1_Click(object sender, EventArgs e) { //Open a Word document Document document = new Document(@"..\..\..\..\..\..\Data\SampleB_2.docx"); //Find the text that will be replaced TextSelection ts = document.FindString("Test", true, true); TextRange tr = ts.GetAsOneRange(); //Get the paragraph Paragraph par = tr.OwnerParagraph; //Get the index of the text in the paragraph int index = par.ChildObjects.IndexOf(tr); //Create a new field MergeField field = new MergeField(document); field.FieldName = "MergeField"; //Insert field at specific position par.ChildObjects.Insert(index, field); //Remove the text par.ChildObjects.Remove(tr); //Save to file document.SaveToFile("result.docx", FileFormat.Docx); //Launch result file WordDocViewer("result.docx"); }
public static Boolean ReplaceParagraph(this Document doc, string placeHolder, string newParaContent) { if (doc == null || string.IsNullOrWhiteSpace(placeHolder) || string.IsNullOrWhiteSpace(newParaContent)) { throw new ArgumentNullException($"some parameter is null - " + $"doc: {doc}, placeHolder: {placeHolder}, newParaContent: {newParaContent}."); } //search for the place holder TextSelection ts = doc.FindString(placeHolder, true, false); if (ts == null || ts.Count < 1) { return(false); } //get the paragram which contains the place holder Paragraph para = ts.GetAsOneRange().OwnerParagraph; Section sec = para.Owner.Owner as Section; //get index of this paragraph int index = sec.Body.Paragraphs.IndexOf(para); //remove paragraph //sec.Body.Paragraphs.RemoveAt(index); sec.Body.Paragraphs.RemoveAt(index); //add a new paragram to the current location Paragraph NewPara = new Paragraph(doc); NewPara.AppendText(newParaContent); sec.Body.ChildObjects.Insert(index, NewPara); return(true); }
/// <summary> /// Insert battery information (table) in template /// </summary> /// <param name="path">path to template</param> /// <param name="batteryInfo">battery information</param> public void InsertBatteryInfoIntoTemplate(string path, List <BatteryProperty> batteryInfo) { try { using (Document doc = new Document()) { doc.LoadFromFile(path); TextSelection selection = doc.FindString(SPECIAL_STRING_TO_REPLACE_WITH_TABLE, true, true); if (selection != null) { TextRange tr = selection.GetAsOneRange(); Paragraph p = tr.OwnerParagraph; Body body = p.OwnerTextBody; int index = body.ChildObjects.IndexOf(p); body.ChildObjects.Remove(p); Table table = body.AddTable(true); FillOutTable(table, batteryInfo); body.ChildObjects.Insert(index, table); doc.SaveToFile(path, FileFormat.Auto); } } } catch (IOException) { throw new IOException("Не удалось получить доступ к файлу, возможно он открыт в другом приложении\n"); } catch (Exception e) { throw new Exception("Неопознання ошибка! \n Системное описание ошибки:" + e.Message); } }
private void button1_Click(object sender, EventArgs e) { Document document = new Document(); document.LoadFromFile(@"..\..\..\..\..\..\Data\FootnoteExample.docx"); //finds the first matched string. TextSelection selection = document.FindString("Spire.Doc", false, true); TextRange textRange = selection.GetAsOneRange(); Paragraph paragraph = textRange.OwnerParagraph; int index = paragraph.ChildObjects.IndexOf(textRange); Footnote footnote = paragraph.AppendFootnote(FootnoteType.Footnote); paragraph.ChildObjects.Insert(index + 1, footnote); textRange = footnote.TextBody.AddParagraph().AppendText("Welcome to evaluate Spire.Doc"); textRange.CharacterFormat.FontName = "Arial Black"; textRange.CharacterFormat.FontSize = 10; textRange.CharacterFormat.TextColor = Color.DarkGray; footnote.MarkerCharacterFormat.FontName = "Calibri"; footnote.MarkerCharacterFormat.FontSize = 12; footnote.MarkerCharacterFormat.Bold = true; footnote.MarkerCharacterFormat.TextColor = Color.DarkGreen; document.SaveToFile("AddFootnote.docx", FileFormat.Docx2010); //view the Word file. WordDocViewer("AddFootnote.docx"); }
private void method_40(TextSelection A_0, string A_1) { if (A_0 != null) { A_0.GetAsOneRange().Text = A_1; } }
private void button1_Click(object sender, EventArgs e) { //Create Word document. Document document = new Document(); //Load the file from disk. document.LoadFromFile(@"..\..\..\..\..\..\Data\Template_Docx_1.docx"); //Get a paragraph. Paragraph paragaph = document.Sections[0].Paragraphs[0]; //Set background color for the paragraph. paragaph.Format.BackColor = Color.Yellow; //Set background color for the selected text of paragraph. paragaph = document.Sections[0].Paragraphs[2]; TextSelection selection = paragaph.Find("Christmas", true, false); TextRange range = selection.GetAsOneRange(); range.CharacterFormat.TextBackgroundColor = Color.Yellow; String result = "Result-SetParagraphShading.docx"; //Save to file. document.SaveToFile(result, FileFormat.Docx2013); //Launch the MS Word file. WordDocViewer(result); }
internal void method_1(TextSelection[] A_0, string A_1) { if ((A_0 != null) && (A_0.Length != 0)) { TextSelection selection = null; int num2 = A_0.Length - 1; for (int i = num2; i > 0; i--) { selection = A_0[i]; selection.method_0(); this.method_4(selection); } selection = A_0[0]; selection.GetAsOneRange().Text = A_1; } }
/// <summary> /// Prepísanie #Stanice na stanicu pre kotú sa robý vývseka a nastavenie času platnosti podla vybraného projektu /// </summary> private void NastavDokument() { ParagraphStyle style = new ParagraphStyle(_document); style.Name = "FontStyle"; style.CharacterFormat.FontSize = 18; style.CharacterFormat.Bold = true; _document.Styles.Add(style); CultureInfo ci = CultureInfo.InvariantCulture; // prepíše v pripravenom dokumente #Stanica za vybranú stanicu a #Datum za datum v projekte for (int i = 0; i < 2; i++) { //nazov stanice TextSelection selection = _document.FindString("#Stanica", true, true); TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; Body body = paragraph.OwnerTextBody; int index = body.ChildObjects.IndexOf(paragraph); Section section = _document.Sections[0]; Paragraph para = section.AddParagraph(); para.AppendText(_dopravnyBod.Nazov); para.ApplyStyle(style.Name); para.Format.HorizontalAlignment = HorizontalAlignment.Right; body.ChildObjects.Remove(paragraph); body.ChildObjects.Insert(index, para); //datum TextSelection selectionOd = _document.FindString("#Datum", true, true); TextRange rangeOd = selectionOd.GetAsOneRange(); Paragraph paragraphOd = rangeOd.OwnerParagraph; Body bodyOd = paragraphOd.OwnerTextBody; int indexOd = bodyOd.ChildObjects.IndexOf(paragraphOd); Section sectionOd = _document.Sections[0]; Paragraph paraOd = sectionOd.AddParagraph(); string text = "Platí od " + _projekt.PlatnostOd.ToString("dd.MM.yyyy", ci) + " do " + _projekt.PlatnostDo.ToString("dd.MM.yyyy", ci); paraOd.AppendText(text); paraOd.Format.HorizontalAlignment = HorizontalAlignment.Center; bodyOd.ChildObjects.Remove(paragraphOd); bodyOd.ChildObjects.Insert(indexOd, paraOd); } }
private void method_37(TextRange A_0, Paragraph A_1, TextSelection A_2) { int num2 = 9; if (A_2 == null) { A_1.Items.Insert(0, A_0); TextRange entity = new TextRange(A_1.Document) { Text = BookmarkStart.b("༮", num2) }; A_1.Items.Insert(1, entity); } else { TextRange asOneRange = A_2.GetAsOneRange(); int index = asOneRange.method_5(); A_1.Items.Remove(asOneRange); A_1.Items.Insert(index, A_0); } }
private void button1_Click(object sender, EventArgs e) { //Create Word document. Document document = new Document(); //Load the file from disk. document.LoadFromFile(@"..\..\..\..\..\..\Data\Template_Docx_2.docx"); //Define the text string that we need to get the height and width. string text = "Your Office Development Master"; //Finds and returns the string with formatting TextSelection selection = document.FindString(text, true, true); //Get the font Font font = selection.GetAsOneRange().CharacterFormat.Font; //Initialize graphics object Image fakeImage = new Bitmap(1, 1); Graphics graphics = Graphics.FromImage(fakeImage); //Measure string SizeF size = graphics.MeasureString(text, font); //Get the height and width of the text. StringBuilder content = new StringBuilder(); content.AppendLine("text height: " + size.Height); content.AppendLine("text width: " + size.Width); String result = "Result-GetHeightAndWidthOfText.txt"; //Save to file. File.WriteAllText(result, content.ToString()); //Launch the file. WordDocViewer(result); }
private void button1_Click(object sender, EventArgs e) { //Create Word document. Document document = new Document(); //Load the file from disk. document.LoadFromFile(@"..\..\..\..\..\..\Data\Template_Docx_1.docx"); //Return TextSection by finding the key text string "Christmas Day, December 25". Section section = document.Sections[0]; TextSelection selection = document.FindString("Christmas Day, December 25", true, true); //Return TextRange from TextSection, then get OwnerParagraph through TextRange. TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; //Return the zero-based index of the specified paragraph. Body body = paragraph.OwnerTextBody; int index = body.ChildObjects.IndexOf(paragraph); //Create a new table. Table table = section.AddTable(true); table.ResetCells(3, 3); //Remove the paragraph and insert table into the collection at the specified index. body.ChildObjects.Remove(paragraph); body.ChildObjects.Insert(index, table); String result = "Result-ReplaceTextWithTable.docx"; //Save to file. document.SaveToFile(result, FileFormat.Docx2013); //Launch the MS Word file. WordDocViewer(result); }
private static void RepalcePicture(Document doc, TargetRect item, string picPath) { if (!File.Exists(picPath)) { throw new MyException("报告生成失败,未找到对应图片!"); } DocPicture pic = new DocPicture(doc); string ss = "Illustration" + item.id.ToString(); TextSelection selection = doc.FindString(ss, true, true); if (selection.Count < 1) { return; } pic.LoadImage(Image.FromFile(picPath)); pic.Width = 250; pic.Height = 240; TextRange range = selection.GetAsOneRange(); int index = range.OwnerParagraph.ChildObjects.IndexOf(range); range.OwnerParagraph.ChildObjects.Insert(index, pic); range.OwnerParagraph.ChildObjects.Remove(range); }
public string create() { string nameCompany = "Công ty định vị Bách Khoa"; string taxCompany = "101010101010"; string addressCompany = "560 Nguyễn Bỉnh Khiêm Hải Phòng"; string phoneCompany = "0775 225 222"; string accountNumber = "12121212121"; //data info Customer string customerName = "Trần Tăng Đoan"; string customerCompany = "Định vị bách khoa"; string taxCustomerCompany = "13131313131"; string customerCompanyAddress = "Big C, Nguyễn Bỉnh Khiêm, Hải Phòng"; string kingOfPayment = "Visa"; string customerAccountNumber = "19001009"; //Code search eBilling string codeSearch = Guid.NewGuid().ToString(); Document doc = new Document(); //Gọi file mẫu doc.LoadFromFile(@"D:\Demo\demoSpire\demoSpire\Content\demo.docx"); //info Company sale doc.Replace("<nameCompany>", nameCompany.ToUpper(), true, true); doc.Replace("<taxCompany>", taxCompany, true, true); doc.Replace("<addressCompany>", addressCompany, true, true); doc.Replace("<phoneCompany>", phoneCompany, true, true); doc.Replace("<accountNumber>", accountNumber, true, true); //info Customer doc.Replace("<customerName>", customerName, true, true); doc.Replace("<customerCompany>", customerCompany, true, true); doc.Replace("<taxCustomerCompany>", taxCustomerCompany, true, true); doc.Replace("<customerCompanyAddress>", customerCompanyAddress, true, true); doc.Replace("<kingOfPayment>", kingOfPayment, true, true); doc.Replace("<customerAccountNumber>", customerAccountNumber, true, true); //Code search eBilling doc.Replace("<codeSearch>", codeSearch, true, true); //create Table Table table = new Table(doc, true); DataTable dt = new DataTable(); PreferredWidth width = new PreferredWidth(WidthType.Percentage, 100); table.PreferredWidth = width; dt.Columns.Add("STT", typeof(string)); dt.Columns.Add("Tên hang hóa, dịch vụ", typeof(string)); dt.Columns.Add("Đơn vị tính", typeof(string)); dt.Columns.Add("Số lượng", typeof(string)); dt.Columns.Add("Đơn giá", typeof(string)); dt.Columns.Add("Thành tiền", typeof(string)); dt.Rows.Add(new string[] { "STT", "Tên hàng hóa, dịch vụ", "Đơn vị tính", "Số lượng", "Đơn giá", "Thành tiền" }); int n = 5; for (int i = 0; i < n; i++) { dt.Rows.Add(new String[] { i.ToString(), i.ToString(), i.ToString(), i.ToString(), i.ToString(), i.ToString() }); } dt.Rows.Add(new string[] { "Cộng tiền hàng: " }); dt.Rows.Add(new string[] { "Tiền thuế giá trị gia tăng: " }); dt.Rows.Add(new string[] { "Tổng tiền thanh toán: " }); table.ResetCells(dt.Rows.Count, dt.Columns.Count); 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()); } } table.Rows[0].Cells[0].SetCellWidth(7, CellWidthType.Percentage); table.Rows[0].Cells[1].SetCellWidth(30, CellWidthType.Percentage); table.Rows[0].Cells[2].SetCellWidth(15, CellWidthType.Percentage); table.Rows[0].Cells[3].SetCellWidth(10, CellWidthType.Percentage); table.Rows[0].Cells[4].SetCellWidth(18, CellWidthType.Percentage); table.Rows[0].Cells[5].SetCellWidth(20, CellWidthType.Percentage); table.ApplyHorizontalMerge(n + 1, 0, 5); table.ApplyHorizontalMerge(n + 2, 0, 5); table.ApplyHorizontalMerge(n + 3, 0, 5); Section section = doc.Sections[0]; TextSelection selection = doc.FindString("[billing_Datatable]", true, true); //find position to customize TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; Body body = paragraph.OwnerTextBody; int index = body.ChildObjects.IndexOf(paragraph); body.ChildObjects.Remove(paragraph); //remove string body.ChildObjects.Insert(index, table); //insert datatable to position //save file doc.SaveToFile(@"D:\Demo\demoSpire\demoSpire\wwwroot\test4.pdf", Spire.Doc.FileFormat.PDF); PdfDocument pdf = new PdfDocument(); string pathFilePdf = @"D:\Demo\demoSpire\demoSpire\wwwroot\test4.pdf"; pdf.LoadFromFile(pathFilePdf); PdfPageBase page = pdf.Pages[0]; Image backgroundImage = Image.FromFile(@"D:\Demo\demoSpire\demoSpire\wwwroot\background.jpg"); page.BackgroundImage = backgroundImage; pdf.SaveToFile(pathFilePdf); return(pathFilePdf); }
public ActionResult PieChart(string Group1) { if (Group1 == null) { return(View()); } string basePath = _hostingEnvironment.WebRootPath; string datapath = basePath + @"/DocIO/PieChart.docx"; //A new document is created. FileStream fileStream = new FileStream(datapath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); WordDocument document = new WordDocument(fileStream, FormatType.Docx); //Create MailMergeDataTable MailMergeDataTable mailMergeDataTable = GetMailMergeDataTableProductDetails(); //Merge the product table in the Word document document.MailMerge.ExecuteGroup(mailMergeDataTable); //Find the Placeholder of Pie chart to insert TextSelection selection = document.Find("<Pie Chart>", false, false); WParagraph paragraph = selection.GetAsOneRange().OwnerParagraph; paragraph.ChildEntities.Clear(); //Create and Append chart to the paragraph WChart pieChart = paragraph.AppendChart(446, 270); //Set chart data pieChart.ChartType = OfficeChartType.Pie; pieChart.ChartTitle = "Best Selling Products"; pieChart.ChartTitleArea.FontName = "Calibri (Body)"; pieChart.ChartTitleArea.Size = 14; GetChartData(pieChart, 0); //Create a new chart series with the name “Sales” IOfficeChartSerie pieSeries = pieChart.Series.Add("Sales"); pieSeries.Values = pieChart.ChartData[2, 2, 11, 2]; //Setting data label pieSeries.DataPoints.DefaultDataPoint.DataLabels.IsPercentage = true; pieSeries.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Outside; //Setting background color pieChart.ChartArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242); pieChart.PlotArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242); pieChart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None; pieChart.PrimaryCategoryAxis.CategoryLabels = pieChart.ChartData[2, 1, 11, 1]; string filename = ""; string contenttype = ""; MemoryStream ms = new MemoryStream(); #region Document SaveOption if (Group1 == "WordDocx") { filename = "Sample.docx"; contenttype = "application/msword"; document.Save(ms, FormatType.Docx); } else if (Group1 == "WordML") { filename = "Sample.xml"; contenttype = "application/msword"; document.Save(ms, FormatType.WordML); } else { filename = "Sample.pdf"; contenttype = "application/pdf"; DocIORenderer renderer = new DocIORenderer(); renderer.ConvertToPDF(document).Save(ms); } #endregion Document SaveOption document.Close(); ms.Position = 0; return(File(ms, contenttype, filename)); }
private void Bwprint_DoWork(object sender, DoWorkEventArgs e) { if (done) { try { WordDocument document = new WordDocument(System.Windows.Forms.Application.StartupPath + @"\Samples\defaulters_sample.docx", FormatType.Docx); var schoolname = db.Randoms.Where(c => c.ID == 1).FirstOrDefault(); var address = db.Randoms.Where(c => c.ID == 2).FirstOrDefault(); var contact = db.Randoms.Where(c => c.ID == 3).FirstOrDefault(); var email = db.Randoms.Where(c => c.ID == 4).FirstOrDefault(); #region SchoolName TextSelection textSelection = document.Find("{SchoolName}", false, true); IWTextRange textRange = textSelection.GetAsOneRange(); //Modifies the text textRange.Text = schoolname.Text.ToString(); textRange.CharacterFormat.FontName = "Times New Roman"; #endregion #region Address textSelection = document.Find("{Address}", false, true); WTextRange addr = textSelection.GetAsOneRange(); addr.Text = address.Text.ToString(); #endregion #region Contact textSelection = document.Find("{Contact}", false, true); WTextRange con = textSelection.GetAsOneRange(); con.Text = contact.Text.ToString(); #endregion #region Email textSelection = document.Find("{Email}", false, true); WTextRange Email = textSelection.GetAsOneRange(); Email.Text = email.Text.ToString(); #endregion #region Class Section textSelection = document.Find("{ClassSection}", false, true); WTextRange classsection = textSelection.GetAsOneRange(); classsection.Text = comboboxclass.Text + " " + comboboxsection.Text; #endregion #region Month Year textSelection = document.Find("{MonthYear}", false, true); WTextRange MonthYear = textSelection.GetAsOneRange(); MonthYear.Text = DateTime.Now.ToString("MMMM yyyy"); #endregion #region Total Defaulters textSelection = document.Find("{Defaulters}", false, true); WTextRange Defaulters = textSelection.GetAsOneRange(); Defaulters.Text = DefaultArray.ToArray().Length.ToString(); #endregion IWSection section = document.Sections[0]; IWTable table = section.AddTable(); ArrayList namearray = new ArrayList(); ArrayList Fatherarray = new ArrayList(); ArrayList montharray = new ArrayList(); ArrayList arrearsarray = new ArrayList(); for (int i = 0; i <= DefaultArray.ToArray().Length - 1; i++) { int ids = (Convert.ToInt32(DefaultArray[i])); var data = db.StudentDatas.Where(c => c.ID == ids).FirstOrDefault(); namearray.Add(data.StudentName.ToString()); Fatherarray.Add(data.FatherName.ToString()); var list = db.StudentFees.Where(c => c.ID == data.ID).FirstOrDefault(); int month = TutionFee((Convert.ToInt32(DefaultArray[i]))) + list.TransportFee + list.ExamFee + list.OthersFee; montharray.Add(month.ToString()); arrearsarray.Add(list.Arrears.ToString()); } table.ResetCells(DefaultArray.ToArray().Length + 1, 4); //Header 1 IWParagraph wParagraph = table[0, 0].AddParagraph(); wParagraph.ParagraphFormat.AfterSpacing = 2f; wParagraph.ParagraphFormat.BeforeSpacing = 2f; wParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left; textRange = wParagraph.AppendText("Student’s Name"); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = true; //Header 2 wParagraph = table[0, 1].AddParagraph(); wParagraph.ParagraphFormat.AfterSpacing = 2f; wParagraph.ParagraphFormat.BeforeSpacing = 2f; wParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left; textRange = wParagraph.AppendText("Father's Name"); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = true; //Header 3 wParagraph = table[0, 2].AddParagraph(); wParagraph.ParagraphFormat.AfterSpacing = 2f; wParagraph.ParagraphFormat.BeforeSpacing = 2f; wParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; textRange = wParagraph.AppendText("This Month"); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = true; //Header 4 wParagraph = table[0, 3].AddParagraph(); wParagraph.ParagraphFormat.AfterSpacing = 2f; wParagraph.ParagraphFormat.BeforeSpacing = 2f; wParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; textRange = wParagraph.AppendText("Arrears"); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = true; for (int i = 0; i <= DefaultArray.ToArray().Length - 1; i++) { int index = i + 1; IWParagraph Paragraph = table[index, 0].AddParagraph(); Paragraph.ParagraphFormat.AfterSpacing = 2f; Paragraph.ParagraphFormat.BeforeSpacing = 2f; Paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left; textRange = Paragraph.AppendText(namearray[i].ToString()); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = false; Paragraph = table[index, 1].AddParagraph(); Paragraph.ParagraphFormat.AfterSpacing = 2f; Paragraph.ParagraphFormat.BeforeSpacing = 2f; Paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left; textRange = Paragraph.AppendText(Fatherarray[i].ToString()); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = false; Paragraph = table[index, 2].AddParagraph(); Paragraph.ParagraphFormat.AfterSpacing = 2f; Paragraph.ParagraphFormat.BeforeSpacing = 2f; Paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; textRange = Paragraph.AppendText("Rs. " + montharray[i].ToString()); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = false; Paragraph = table[index, 3].AddParagraph(); Paragraph.ParagraphFormat.AfterSpacing = 2f; Paragraph.ParagraphFormat.BeforeSpacing = 2f; Paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; textRange = Paragraph.AppendText("Rs. " + arrearsarray[i].ToString()); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = false; } //Saves the document in the given name and format string savepath = "DefaulterList-" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".docx"; document.Save(savepath, FormatType.Docx); //Releases the resources occupied by WordDocument instance document.Close(); PrintWord(System.Windows.Forms.Application.StartupPath + @"\" + savepath, "Microsoft Print to PDF"); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "Error - Student Management System", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
internal static bool IsToc(this TextSelection textSelection) { return(textSelection?.GetAsOneRange().OwnerParagraph.IsToc() ?? false); }
/// <summary> /// 透過既有的套印檔匯出 Word 文件 (以「取代文字」方式套印) /// </summary> /// <param name="result">回傳: 執行結果</param> /// <param name="msg">回傳: 訊息</param> /// <returns>串流資訊</returns> public byte[] ExportResumeByDocx_ReplaceText(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.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 套印內容 document.Replace("{$Name$}", string.IsNullOrEmpty(model.Name) ? "" : model.Name, false, true); document.Replace("{$Gender$}", string.IsNullOrEmpty(model.Gender) ? "" : model.Gender, false, true); document.Replace("{$Email$}", string.IsNullOrEmpty(model.Email) ? "" : model.Email, false, true); document.Replace("{$Address$}", string.IsNullOrEmpty(model.Address) ? "" : model.Address, false, true); document.Replace("{$Phone$}", string.IsNullOrEmpty(model.Phone) ? "" : model.Phone, false, true); document.Replace("{$Mobile$}", string.IsNullOrEmpty(model.Mobile) ? "" : model.Mobile, false, true); //包含 HTML 字串需放置在 paragraph 內, //因此套印檔中的 {$Description1$} 及 {$Description2$} 需透過「以 paragraph 取代文字」方式替代 //Replace {$Description1$} with paragraph TextSelection selection = document.FindString("{$Description1$}", false, true); TextRange range = selection.GetAsOneRange(); Spire.Doc.Documents.Paragraph paragraph = range.OwnerParagraph; paragraph.ApplyStyle("Basic"); paragraph.Replace("{$Description1$}", "", false, false); paragraph.AppendHTML(string.IsNullOrEmpty(model.Description1) ? "" : HttpUtility.HtmlDecode(model.Description1)); //Replace {$Description2$} with paragraph selection = document.FindString("{$Description2$}", false, true); range = selection.GetAsOneRange(); paragraph = range.OwnerParagraph; paragraph.ApplyStyle("Basic"); paragraph.Replace("{$Description2$}", "", false, false); paragraph.AppendHTML(string.IsNullOrEmpty(model.Description2) ? "" : HttpUtility.HtmlDecode(model.Description2)); //Replace {$Img$} with Image DocPicture pic = new DocPicture(document); pic.LoadImage(Image.FromFile(HttpContext.Current.Server.MapPath("~/App_Data/Penguins.jpg"))); selection = document.FindString("{$Img$}", false, true); range = selection.GetAsOneRange(); range.OwnerParagraph.ChildObjects.Insert(0, pic); range.OwnerParagraph.ChildObjects.Remove(range); #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; } } //Replace text with Table TextSelection selectionTable = document.FindString("{$JobHistory$}", true, true); TextRange rangeTable = selectionTable.GetAsOneRange(); Spire.Doc.Documents.Paragraph paragraphTable = rangeTable.OwnerParagraph; Body body = paragraphTable.OwnerTextBody; int index = body.ChildObjects.IndexOf(paragraphTable); body.ChildObjects.Remove(paragraphTable); body.ChildObjects.Insert(index, table); } #endregion #region 套用樣式 //套用文章段落樣式 for (int s = 0; s < document.Sections.Count; s++) { Spire.Doc.Section section = document.Sections[s]; //套用文章段落樣式 for (int p = 0; p < section.Paragraphs.Count; p++) { Spire.Doc.Documents.Paragraph pgh = section.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); } }
public void СoncealmentMethod() { Document document = new Document(); if (pathDocument != "") { document.LoadFromFile(pathDocument); string str = document.GetText(); //labelForCountSymbol.Text = "Количество символов, которые можно скрыть: " + (str.Length / 7).ToString(); if (TBForMessage.Text != "") { messEncrypt = ConvertToByte(ConvertToASCII(TBForMessage.Text)); ////////////////////////////////////////////////////////////////// Document doc = new Document(); Paragraph paragraph1 = doc.AddSection().AddParagraph(); paragraph1.AppendText(str); int part = str.Length / messEncrypt.Length; if (part > 1) { TextRange range = new TextRange(doc); if (singleBitValue != 0 && zeroBitValue != 0 && strFormatExport != "") { if (singleBitValue != zeroBitValue) { for (int i = 0; i < messEncrypt.Length; i++) { var randPositin = rand.Next(part * i + 1, part * (i + 1)); TextSelection selections = new TextSelection(paragraph1, randPositin, randPositin + 1); range = selections.GetAsOneRange(); if (strForCheckColor == "Да") { if (messEncrypt[i] == '1') { range.CharacterFormat.CharacterSpacing = singleBitValue; range.CharacterFormat.TextColor = Color.Red; } if (messEncrypt[i] == '0') { range.CharacterFormat.CharacterSpacing = zeroBitValue; range.CharacterFormat.TextColor = Color.BlueViolet; } if (messEncrypt[i] == ' ') { range.CharacterFormat.CharacterSpacing = 0.05f; } } else { if (messEncrypt[i] == '1') { range.CharacterFormat.CharacterSpacing = singleBitValue; } if (messEncrypt[i] == '0') { range.CharacterFormat.CharacterSpacing = zeroBitValue; } if (messEncrypt[i] == ' ') { range.CharacterFormat.CharacterSpacing = 0.05f; } } } if (saveFileDialog1.ShowDialog() == DialogResult.OK) { string filename = saveFileDialog1.FileName; labelPathSaveFile.Text = Path.GetFullPath(filename); pathSaveReceivedFile = Path.GetFullPath(filename); if (strFormatExport == "Doc") { doc.SaveToFile(pathSaveReceivedFile, FileFormat.Doc); labelForStatusScritiya.Text = "СООБЩЕНИЕ СКРЫТО УСПЕШНО!"; } if (strFormatExport == "Docx") { doc.SaveToFile(pathSaveReceivedFile, FileFormat.Docx); labelForStatusScritiya.Text = "СООБЩЕНИЕ СКРЫТО УСПЕШНО!"; } if (strFormatExport == "Docm") { doc.SaveToFile(pathSaveReceivedFile, FileFormat.Docm); labelForStatusScritiya.Text = "СООБЩЕНИЕ СКРЫТО УСПЕШНО!"; } if (strFormatExport == "Dot") { doc.SaveToFile(pathSaveReceivedFile, FileFormat.Dot); labelForStatusScritiya.Text = "СООБЩЕНИЕ СКРЫТО УСПЕШНО!"; } if (strFormatExport == "Dotm") { doc.SaveToFile(pathSaveReceivedFile, FileFormat.Dotm); labelForStatusScritiya.Text = "СООБЩЕНИЕ СКРЫТО УСПЕШНО!"; } if (strFormatExport == "Dotx") { doc.SaveToFile(pathSaveReceivedFile, FileFormat.Dotx); labelForStatusScritiya.Text = "СООБЩЕНИЕ СКРЫТО УСПЕШНО!"; } if (strFormatExport == "Xml") { doc.SaveToFile(pathSaveReceivedFile, FileFormat.Xml); labelForStatusScritiya.Text = "СООБЩЕНИЕ СКРЫТО УСПЕШНО!"; } if (strFormatExport == "Rtf") { doc.SaveToFile(pathSaveReceivedFile, FileFormat.Rtf); labelForStatusScritiya.Text = "СООБЩЕНИЕ СКРЫТО УСПЕШНО!"; } } } else { MessageBox.Show("Значение Апроша для \nнулевого и единичного битa \nне должно совпадать!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Выберите все параметры!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Количество символов в выбранном тексте недостаточно\nдля сокрытия сообщения такой длины!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Введите сообщение, которое\nнужно скрыть!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Выберите файл с текстом!", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private string CreateFile(FileFormat fileFormat) { string pdfPath = ""; try { //initialize word object Document document = new Document(); try { document.LoadFromFile(samplePath, FileFormat.Docx); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } //Create Invoice document.Replace("#Date#", invoice.date.ToString(Config.FORMAT_DATETIME), true, true); document.Replace("#InvoiceNo#", invoice.invoiceNo, true, true); document.Replace("#CoverNoteNo#", invoice.coverNoteNo, true, true); document.Replace("#PolicyNo#", invoice.policyNo, true, true); document.Replace("#EndorsementNo#", invoice.endorsementNo, true, true); document.Replace("#SumInsured#", invoice.sumInsured, true, true); document.Replace("#EffDate#", invoice.effectiveDate.ToString(Config.FORMAT_DATETIME), true, true); document.Replace("#ExpDate#", invoice.expiryDate.ToString(Config.FORMAT_DATETIME), true, true); document.Replace("#InsuranceClass#", invoice.insuranceClass, true, true); document.Replace("#BankAccountNo#", invoice.bankAccountNo, true, true); document.Replace("#BankName#", invoice.bankName, true, true); document.Replace("#Agent#", invoice.agent, true, true); document.Replace("#Total#", invoice.totalAmount, true, true); document.Replace("#RinggitMalaysia#", invoice.totalAmountString, true, true); document.Replace("#Name#", invoice.clientName, true, true); //Special handling for address TextSelection selection = document.FindString("#Address#", true, true); TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; paragraph.Text = ""; paragraph.AppendRTF(invoice.clientAddress); foreach (var invoiceItem in invoice.invoiceItems) { document.Replace("#Description" + invoiceItem.itemNo + "#", invoiceItem.description, true, true); document.Replace("#Amount" + invoiceItem.itemNo + "#", invoiceItem.amount, true, true); } pdfPath = Application.StartupPath + Path.DirectorySeparatorChar + Config.INVOICE_FOLDER + Path.DirectorySeparatorChar + invoice.invoiceNo + ".pdf"; string docPath = Application.StartupPath + Path.DirectorySeparatorChar + Config.DOC_FOLDER + Path.DirectorySeparatorChar + invoice.invoiceNo + ".docx"; document.SaveToFile(docPath, FileFormat.Docx); document.SaveToFile(pdfPath, FileFormat.PDF); document.Close(); } catch (Exception ex) { logger.Error("Class: " + this.GetType().FullName + "; Method: " + System.Reflection.MethodBase.GetCurrentMethod().Name + "; Message: " + ex.Message); } return(pdfPath); }
/// <summary> /// 队选中的文本区域进行格式设置 /// </summary> /// <param name="myts"></param> /// <param name="f"></param> public void FormatSet(TextSelection myts, Format f) { //Regex.Replace(myts.SelectedText, "\v", "\r\n"); TextRange asOneRange; Paragraph mypara; string str3; bool flag1; if (!f.enable || (myts == null))//判断该格式是否启用,如果f.enable是false,则退出本方法 { flag1 = true; } else { flag1 = myts.Count == 0; } if (!flag1) { //var myranges= myts.GetRanges(); asOneRange = myts.GetAsOneRange(); asOneRange.CharacterFormat.FontName = f.fontname; asOneRange.CharacterFormat.FontSize = f.fontsize; mypara = asOneRange.OwnerParagraph; mypara.Text = mypara.Text.Trim(); if (asOneRange == null) { return; } //asOneRange.CharacterFormat.ClearFormatting(); //asOneRange.Document.SaveToFile(@"C:\Users\瑞腾软件\Desktop\正文字体问题\ceshi.docx",FileFormat.Docx); asOneRange.CharacterFormat.Bold = f.bold == 1; string lstype = f.lstype; if (lstype != null) { if (lstype == "单倍行距") { mypara.Format.LineSpacingRule = LineSpacingRule.AtLeast; goto TR_000D; } else if (lstype == "1.5倍行距") { mypara.Format.LineSpacingRule = LineSpacingRule.Exactly; goto TR_000D; } else if (lstype == "2倍行距") { mypara.Format.LineSpacingRule = LineSpacingRule.Multiple; goto TR_000D; } } //if (asOneRange.OwnerParagraph==null) //{ // return; //} mypara.Format.LineSpacingRule = LineSpacingRule.Exactly; //设置行距 mypara.Format.LineSpacing = f.lsvalue; //设置段落前后距 //asOneRange.OwnerParagraph.Format.AfterSpacing = 0; mypara.Format.BeforeSpacing = 0;; } else { return; } TR_000D: str3 = f.juzhong; if (str3 != null) { if (str3 == "左对齐") { mypara.Format.HorizontalAlignment = HorizontalAlignment.Left; } else if (str3 == "居中") { mypara.Format.HorizontalAlignment = HorizontalAlignment.Center; } else if (str3 == "右对齐") { mypara.Format.HorizontalAlignment = HorizontalAlignment.Right; } } //调整缩进和空行 int space = f.space; int num2 = 0; while (true) { if (num2 >= space) { //pire.Doc.Formatting.ParagraphFormat format = new Spire.Doc.Formatting.ParagraphFormat(); mypara.Format.FirstLineIndent = f.suojin; //asOneRange.OwnerParagraph.Format break; } mypara.AppendText("\n"); num2++; } }
/// <summary> /// 使用spire设置文本格式 /// </summary> /// <param name="myts"></param> /// <param name="f"></param> public void FormatSet(TextSelection myts, Format f) { //如果该格式未启用,不执行任何方法 if (!f.enable || myts == null || myts.Count == 0) { return; } //得到文本区域 TextRange mytr = myts.GetAsOneRange(); //设置字体名称 mytr.CharacterFormat.FontName = f.fontname; //设置字体大小 mytr.CharacterFormat.FontSize = f.fontsize; //设置粗体 mytr.CharacterFormat.Bold = f.bold == 1 ? true : false; //设置行距 switch (f.lstype) { case "单倍行距": mytr.OwnerParagraph.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.AtLeast; break; case "1.5倍行距": mytr.OwnerParagraph.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.Exactly; break; case "2倍行距": mytr.OwnerParagraph.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.Multiple; break; default: mytr.OwnerParagraph.Format.LineSpacingRule = Spire.Doc.LineSpacingRule.Exactly; mytr.OwnerParagraph.Format.LineSpacing = f.lsvalue; break; } //设置居中 switch (f.juzhong) { case "左对齐": mytr.OwnerParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left; break; case "居中": mytr.OwnerParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; break; case "右对齐": mytr.OwnerParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right; break; } //先删除空格 //增加空行 int spacenum = f.space; for (int spaceindex = 0; spaceindex < spacenum; spaceindex++) { mytr.OwnerParagraph.AppendText("\n"); } //设置缩进 Spire.Doc.Formatting.ParagraphFormat mypformat = new Spire.Doc.Formatting.ParagraphFormat(); mytr.OwnerParagraph.Format.FirstLineIndent = f.suojin; }
public ActionResult FindandHighlight(string Group1, string Button, string Group2) { if (Group1 == null) { return(View()); } if (Button == "View Template") { return(new TemplateResult("Adventure.docx", ResolveApplicationDataPath("Data\\DocIO"), HttpContext.ApplicationInstance.Response)); } try { //Load template document WordDocument doc = new WordDocument(ResolveApplicationDataPath("Adventure.docx", "Data\\DocIO")); //Get the pattern for regular expression Regex regex = new Regex(Group2); //Find the first occurrence of the text in the Word document. TextSelection text = doc.Find(regex); //Set the highlight color for the text. text.GetAsOneRange().CharacterFormat.HighlightColor = Color.Green; try { #region Document SaveOption //Save as .doc format if (Group1 == "WordDoc") { return(doc.ExportAsActionResult("Sample.doc", FormatType.Doc, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment)); } //Save as .docx format else if (Group1 == "WordDocx") { return(doc.ExportAsActionResult("Sample.docx", FormatType.Docx, HttpContext.ApplicationInstance.Response, HttpContentDisposition.Attachment)); } // Save as WordML(.xml) format else if (Group1 == "WordML") { return(doc.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(doc); return(pdfDoc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save)); } #endregion Document SaveOption } catch (Exception) { } } catch (Exception Ex) { System.Diagnostics.Trace.WriteLine(Ex.Message + "\n\n\n" + Ex.StackTrace); } return(View()); }
private void button1_Click(object sender, System.EventArgs e) { try { //Getting Data files path. string dataPath = Application.StartupPath + @"..\..\..\..\..\..\..\common\Data\DocIO\"; //A new document is created. WordDocument document = new WordDocument(dataPath + "PieChart.docx"); //Get chart data from xml file DataSet ds = new DataSet(); ds.ReadXml(dataPath + "Products.xml"); //Merge the product table in the Word document document.MailMerge.ExecuteGroup(ds.Tables["Product"]); //Find the Placeholder of Pie chart to insert TextSelection selection = document.Find("<Pie Chart>", false, false); WParagraph paragraph = selection.GetAsOneRange().OwnerParagraph; paragraph.ChildEntities.Clear(); //Create and Append chart to the paragraph WChart pieChart = paragraph.AppendChart(446, 270); //Set chart data pieChart.ChartType = OfficeChartType.Pie; pieChart.ChartTitle = "Best Selling Products"; pieChart.ChartTitleArea.FontName = "Calibri (Body)"; pieChart.ChartTitleArea.Size = 14; for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { pieChart.ChartData.SetValue(i + 2, 1, ds.Tables[0].Rows[i].ItemArray[1]); pieChart.ChartData.SetValue(i + 2, 2, ds.Tables[0].Rows[i].ItemArray[2]); } //Create a new chart series with the name “Sales” IOfficeChartSerie pieSeries = pieChart.Series.Add("Sales"); pieSeries.Values = pieChart.ChartData[2, 2, 11, 2]; //Setting data label pieSeries.DataPoints.DefaultDataPoint.DataLabels.IsPercentage = true; pieSeries.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Outside; //Setting background color pieChart.ChartArea.Fill.ForeColor = Color.FromArgb(242, 242, 242); pieChart.PlotArea.Fill.ForeColor = Color.FromArgb(242, 242, 242); pieChart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None; pieChart.PrimaryCategoryAxis.CategoryLabels = pieChart.ChartData[2, 1, 11, 1]; //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] #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()); } } } catch (Exception Ex) { MessageBox.Show(Ex.Message); } }
private void Bwgenmon_DoWork(object sender, DoWorkEventArgs e) { int index = 0; switch (DateTime.Now.Month) { case 1: index = 0; break; case 2: index = 1; break; case 3: index = 2; break; case 4: index = 3; break; case 5: index = 4; break; case 6: index = 5; break; case 7: index = 6; break; case 8: index = 7; break; case 9: index = 8; break; case 10: index = 9; break; case 11: index = 10; break; case 12: index = 11; break; } var dates = db.Randoms.Where(c => c.ID == 16).FirstOrDefault(); var datearray = dates.Text.Split(';'); var marray = datearray[index].Split(','); var amounts = db.Randoms.Where(c => c.ID == 15).FirstOrDefault(); var amountarray = amounts.Text.Split(';'); var amarray = amountarray[index].Split(','); var names = db.Randoms.Where(c => c.ID == 17).FirstOrDefault(); var namearray = names.Text.Split(';'); var narray = namearray[index].Split(','); ArrayList marrayList = new ArrayList(); marrayList.AddRange(marray); ArrayList amarrayList = new ArrayList(); amarrayList.AddRange(amarray); ArrayList narraylist = new ArrayList(); narraylist.AddRange(narray); ArrayList farrayList = new ArrayList(); for (int i = 0; i <= marrayList.ToArray().Length - 2; i++) { string a = narraylist[i].ToString(); var data = db.StudentDatas.Where(c => c.StudentName == a).FirstOrDefault(); farrayList.Add(data.FatherName); } try { WordDocument document = new WordDocument(System.Windows.Forms.Application.StartupPath + @"\Samples\submission_sample.docx", FormatType.Docx); var schoolname = db.Randoms.Where(c => c.ID == 1).FirstOrDefault(); var address = db.Randoms.Where(c => c.ID == 2).FirstOrDefault(); var contact = db.Randoms.Where(c => c.ID == 3).FirstOrDefault(); var email = db.Randoms.Where(c => c.ID == 4).FirstOrDefault(); #region SchoolName TextSelection textSelection = document.Find("{SchoolName}", false, true); IWTextRange textRange = textSelection.GetAsOneRange(); //Modifies the text textRange.Text = schoolname.Text.ToString(); textRange.CharacterFormat.FontName = "Times New Roman"; #endregion #region Address textSelection = document.Find("{Address}", false, true); WTextRange addr = textSelection.GetAsOneRange(); addr.Text = address.Text.ToString(); #endregion #region Contact textSelection = document.Find("{Contact}", false, true); WTextRange con = textSelection.GetAsOneRange(); con.Text = contact.Text.ToString(); #endregion #region Email textSelection = document.Find("{Email}", false, true); WTextRange Email = textSelection.GetAsOneRange(); Email.Text = email.Text.ToString(); #endregion #region DateMonth textSelection = document.Find("{DateMonth}", false, true); WTextRange DateMonth = textSelection.GetAsOneRange(); DateMonth.Text = "Month"; #endregion #region MonthDate textSelection = document.Find("{MonthDate}", false, true); WTextRange MonthDate = textSelection.GetAsOneRange(); MonthDate.Text = DateTime.Now.ToString("MMMM yyyy"); #endregion #region Time textSelection = document.Find("{Time}", false, true); WTextRange Time = textSelection.GetAsOneRange(); Time.Text = DateTime.Now.ToString("hh:mm tt"); #endregion #region Amount int amt = 0; for (int i = 0; i <= amarrayList.ToArray().Length - 2; i++) { amt = amt + Convert.ToInt32(amarrayList[i]); } textSelection = document.Find("{Amount}", false, true); WTextRange Amount = textSelection.GetAsOneRange(); Amount.Text = "Rs. " + amt.ToString(); #endregion IWSection section = document.Sections[0]; IWTable table = section.AddTable(); table.ResetCells(farrayList.ToArray().Length + 1, 4); //Header 1 IWParagraph wParagraph = table[0, 0].AddParagraph(); wParagraph.ParagraphFormat.AfterSpacing = 2f; wParagraph.ParagraphFormat.BeforeSpacing = 2f; wParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left; textRange = wParagraph.AppendText("Student’s Name"); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = true; //Header 2 wParagraph = table[0, 1].AddParagraph(); wParagraph.ParagraphFormat.AfterSpacing = 2f; wParagraph.ParagraphFormat.BeforeSpacing = 2f; wParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left; textRange = wParagraph.AppendText("Father's Name"); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = true; //Header 3 wParagraph = table[0, 2].AddParagraph(); wParagraph.ParagraphFormat.AfterSpacing = 2f; wParagraph.ParagraphFormat.BeforeSpacing = 2f; wParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; textRange = wParagraph.AppendText("Amount"); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = true; //Header 4 wParagraph = table[0, 3].AddParagraph(); wParagraph.ParagraphFormat.AfterSpacing = 2f; wParagraph.ParagraphFormat.BeforeSpacing = 2f; wParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; textRange = wParagraph.AppendText("Date & Time"); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = true; for (int i = 0; i <= farrayList.ToArray().Length - 1; i++) { int inc = i + 1; //Column 1 wParagraph = table[inc, 0].AddParagraph(); wParagraph.ParagraphFormat.AfterSpacing = 2f; wParagraph.ParagraphFormat.BeforeSpacing = 2f; wParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left; textRange = wParagraph.AppendText(narraylist[i].ToString()); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = false; //Column 2 wParagraph = table[inc, 1].AddParagraph(); wParagraph.ParagraphFormat.AfterSpacing = 2f; wParagraph.ParagraphFormat.BeforeSpacing = 2f; wParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left; textRange = wParagraph.AppendText(farrayList[i].ToString()); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = false; //Column 3 wParagraph = table[inc, 2].AddParagraph(); wParagraph.ParagraphFormat.AfterSpacing = 2f; wParagraph.ParagraphFormat.BeforeSpacing = 2f; wParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; textRange = wParagraph.AppendText(amarrayList[i].ToString()); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = false; //Column 4 wParagraph = table[inc, 3].AddParagraph(); wParagraph.ParagraphFormat.AfterSpacing = 2f; wParagraph.ParagraphFormat.BeforeSpacing = 2f; wParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; textRange = wParagraph.AppendText(marrayList[i].ToString()); textRange.CharacterFormat.FontName = "Century Gothic"; textRange.CharacterFormat.FontSize = 9; textRange.CharacterFormat.Bold = false; } string savepath = "FeeSubmissionList-" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".docx"; document.Save(savepath, FormatType.Docx); PrintWord(System.Windows.Forms.Application.StartupPath + @"\" + savepath, DefaultPrinterName); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } }
public ActionResult PieChart(string Group1) { if (Group1 == null) { return(View()); } //A new document is created. WordDocument document = new WordDocument(ResolveApplicationDataPath("PieChart.docx", "App_Data\\DocIO")); //Get chart data from xml file DataSet ds = new DataSet(); ds.ReadXml(ResolveApplicationDataPath("Products.xml", "App_Data\\DocIO")); //Merge the product table in the Word document document.MailMerge.ExecuteGroup(ds.Tables["Product"]); //Find the Placeholder of Pie chart to insert TextSelection selection = document.Find("<Pie Chart>", false, false); WParagraph paragraph = selection.GetAsOneRange().OwnerParagraph; paragraph.ChildEntities.Clear(); //Create and Append chart to the paragraph WChart pieChart = paragraph.AppendChart(446, 270); //Set chart data pieChart.ChartType = OfficeChartType.Pie; pieChart.ChartTitle = "Best Selling Products"; pieChart.ChartTitleArea.FontName = "Calibri (Body)"; pieChart.ChartTitleArea.Size = 14; for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { pieChart.ChartData.SetValue(i + 2, 1, ds.Tables[0].Rows[i].ItemArray[1]); pieChart.ChartData.SetValue(i + 2, 2, ds.Tables[0].Rows[i].ItemArray[2]); } //Create a new chart series with the name “Sales” IOfficeChartSerie pieSeries = pieChart.Series.Add("Sales"); pieSeries.Values = pieChart.ChartData[2, 2, 11, 2]; //Setting data label pieSeries.DataPoints.DefaultDataPoint.DataLabels.IsPercentage = true; pieSeries.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Outside; //Setting background color pieChart.ChartArea.Fill.ForeColor = System.Drawing.Color.FromArgb(242, 242, 242); pieChart.PlotArea.Fill.ForeColor = System.Drawing.Color.FromArgb(242, 242, 242); pieChart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None; pieChart.PrimaryCategoryAxis.CategoryLabels = pieChart.ChartData[2, 1, 11, 1]; #region Document save option //Save as .docx format 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)); } return(View()); #endregion Document save option }
/// <summary> /// 类型编号3.用于海水浴场的海浪数据输入 /// </summary> /// <param name="path"></param> /// <param name="outPath"></param> /// <param name="missionInfo"></param> public static void WaveHSYC(string path, string outPath, MissionInfo missionInfo) { Document document = new Document(path, FileFormat.Doc); TextSelection[] textFW = document.FindAllString("{fw}", true, false); TextSelection[] textFWYC = document.FindAllString("{fwyc}", true, false); TextSelection textY = document.FindString("{yyyy}", true, false); TextSelection textM = document.FindString("{mm}", true, false); TextSelection textD = document.FindString("{dd}", true, false); textY.GetAsOneRange().Text = DateTime.Today.ToString("yyyy"); textM.GetAsOneRange().Text = DateTime.Today.ToString("MM"); textD.GetAsOneRange().Text = DateTime.Today.ToString("dd"); //获取模板文件信息 //var enc= GetEncoding(path); //path = Path.GetDirectoryName(path) + "\\word\\document.xml"; //读取模板 //string modelText = TxtLoad(path,enc); //替换海浪预报数据{fwqq}、{fw} var forecastList = ReshapeWave(missionInfo); int i = 0; try { foreach (var temp in forecastList) { //按规则将浪高转换为适宜、较适宜、不适宜 float h = float.Parse(temp); string s = ""; if (h < 0) { s = "缺报"; } if (h <= 1) { s = "适宜"; } if (h > 1 & h <= 1.8) { s = "较适宜"; } if (h > 1.8) { s = "不适宜"; } //modelText = ForecastReplace.Replace(modelText, "{fwyc}", s); //modelText = ForecastReplace.Replace(modelText, "{fw}", temp); textFW[i].GetAsOneRange().Text = temp; textFWYC[i].GetAsOneRange().Text = s; i++; } //检查目录是否存在 if (!Directory.Exists(Path.GetDirectoryName(outPath))) { Directory.CreateDirectory(Path.GetDirectoryName(outPath)); } document.SaveToFile(outPath); } catch (Exception e) { throw e; } //存储修改后的模板文件 //var xmlOutPath= Path.GetDirectoryName(outPath) + "\\Temp\\word\\document.xml"; //if (!TxtWrite(xmlOutPath, modelText, enc)) throw new Exception("产品存储失败"); }
public ActionResult FindandHighlight(string Group1, string Button, string Group2) { if (Group1 == null) { return(View()); } string basePath = _hostingEnvironment.WebRootPath; string dataPath = basePath + @"/DocIO/Adventure.docx"; string contenttype1 = "application/vnd.ms-word.document.12"; FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); if (Button == "View Template") { return(File(fileStream, contenttype1, "Adventure.docx")); } try { //Load template document WordDocument doc = new WordDocument(fileStream, FormatType.Docx); fileStream.Dispose(); fileStream = null; //Get the pattern for regular expression Regex regex = new Regex(Group2); //Find the first occurrence of the text in the Word document. TextSelection text = doc.Find(regex); //Set the highlight color for the text. text.GetAsOneRange().CharacterFormat.HighlightColor = Syncfusion.Drawing.Color.Green; try { 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(); doc.Save(ms, type); doc.Close(); ms.Position = 0; return(File(ms, contenttype, filename)); } catch (Exception) { } } catch (Exception) { } return(View()); }
private void createDoc(string filePath) { //check the template is available if (File.Exists(filePath)) { //load the doc Document document = new Document(filePath); //find and replace the content document.Replace("<Title>", txtTitle.Text, true, true); document.Replace("<name>", txtName.Text, true, true); //find and replace the header & footer document.Replace("<CompanyName>", "冰冰无限公司", true, true); document.Replace("<Date>", DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss").ToString(), true, true); Section section = document.Sections[0]; TextSelection selection = document.FindString("<MyTable>", true, true); TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; Body body = paragraph.OwnerTextBody; int index = body.ChildObjects.IndexOf(paragraph); Table table = section.AddTable(true); DataTable dt = getData(Server.MapPath("Excel/" + DropDownList1.SelectedValue)); string[] header = dt.Columns.Cast <DataColumn>() .Select(x => x.ColumnName) .ToArray(); //Add Cells table.ResetCells(dt.Rows.Count + 1, header.Length); //Header Row TableRow FRow = table.Rows[0]; FRow.IsHeader = true; //Row Height FRow.Height = 23; //Header Format FRow.RowFormat.BackColor = Color.AliceBlue; for (int x = 0; x < header.Length; x++) { //Cell Alignment Paragraph p = FRow.Cells[x].AddParagraph(); FRow.Cells[x].CellFormat.VerticalAlignment = VerticalAlignment.Middle; p.Format.HorizontalAlignment = HorizontalAlignment.Center; //Data Format TextRange tr = p.AppendText(header[x]); tr.CharacterFormat.FontName = "Calibri"; tr.CharacterFormat.FontSize = 14; tr.CharacterFormat.TextColor = Color.Teal; tr.CharacterFormat.Bold = true; } for (int x = 0; x < dt.Rows.Count; x++) { TableRow DataRow = table.Rows[x + 1]; DataRow.Height = 20; for (int y = 0; y < dt.Columns.Count; y++) { //Cell Alignment DataRow.Cells[y].CellFormat.VerticalAlignment = VerticalAlignment.Middle; //Fill Data in Rows Paragraph p2 = DataRow.Cells[y].AddParagraph(); TextRange tr2 = p2.AppendText(dt.Rows[x][y].ToString()); //Format Cells p2.Format.HorizontalAlignment = HorizontalAlignment.Center; tr2.CharacterFormat.FontName = "Calibri"; tr2.CharacterFormat.FontSize = 12; tr2.CharacterFormat.TextColor = Color.Brown; } } body.ChildObjects.Remove(paragraph); body.ChildObjects.Insert(index, table); //save the doc in temporarily folder string tempPath = Server.MapPath("Temporarily/" + DateTime.Now.ToString("ddmmyyyyhhmmssffffff") + ".docx"); document.SaveToFile(tempPath, Spire.Doc.FileFormat.Docx); //let the user download and delete it the doc Response.ContentType = "Application/msword"; Response.AddHeader("Content-Disposition", "attachment;filename= Example.docx"); Response.TransmitFile(Path.Combine(tempPath.ToString())); Response.Flush(); File.Delete(tempPath); Response.End(); } }