private bool CheckIfWordDocContainsString(string text) { var flatDoc = new FlatDocument(WordFilePath); var hasString = flatDoc.FindText(text); flatDoc.Close(); flatDoc = null; return(hasString); }
protected void Page_Load(object sender, EventArgs e) { string filename = Session["filename"].ToString(); string pid = Session["newID"].ToString(); if (Session["newID"] != null) { bindEditData(Session["newID"].ToString()); } string inputFile = Server.MapPath("~/TemplateStore/NJ/" + Session["filename"].ToString()); // string inputFile = Request.PhysicalApplicationPath + "\\document\\DisabilityLetterNF.docx"; //System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Upload/")); Session["outfile"] = "1" + Session["filename"].ToString(); System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/document/" + Session["outfile"].ToString())); if (di != null) { //foreach (FileInfo file in di.GetFiles()) //{ // file.Delete(); //} string fileName = di.ToString(); System.IO.File.Delete(fileName); } string outputFile = Server.MapPath("~/document/" + Session["outfile"].ToString()); //string outputFile = Server.MapPath("DisabilityLetterNF1.docx"); //string outputFile = Request.PhysicalApplicationPath + "\\document\\DisabilityLetterNF1.docx"; // Copy Word document. File.Copy(inputFile, outputFile, false); // Open copied document. using (var flatDocument = new FlatDocument(outputFile)) { flatDocument.FindAndReplace("[DATE]", Convert.ToString(System.DateTime.Now.ToString("dd/MM/yyyy"))); flatDocument.FindAndReplace("[NAME]", Session["fname"].ToString() + " " + Session["lname"].ToString()); flatDocument.FindAndReplace("[DOA]", Session["DOA"].ToString()); // Save document on Dispose. } Response.Redirect("~/OpenForm.aspx"); }
private void CreateTemplates(object sender, DoWorkEventArgs e) { var worker = sender as BackgroundWorker; // Список для поиска var toFind = new List <string> { "<Description>", "<GIP>", "<Engineer>", "<Employer>", "<Year>", "<NumProj>", "<Controller>", "<Organization>", "<Resolution>", "<Customer>" }; var assembly = Assembly.GetExecutingAssembly(); worker?.ReportProgress(0, ModPlusAPI.Language.GetItem(LangItem, "h21")); var wordAutomation = new WordAutomation(); // Запускаем Word wordAutomation.CreateWordApplication(); // Проходим по объектам kap foreach (var kapDoc in _kapDocs.Where(x => x.Create)) { if (worker != null && worker.CancellationPending) { wordAutomation.CloseWordApp(); break; } worker?.ReportProgress(0, ModPlusAPI.Language.GetItem(LangItem, "h22") + ": " + ModPlusAPI.Language.GetItem(LangItem, "h15") + ": " + kapDoc.Name); // Временный файл var tmp = Path.GetTempFileName(); var templateFullPath = Path.ChangeExtension(tmp, ".docx"); // Имя внедренного ресурса var resourceName = "mpDocTemplates.Resources.Kap." + kapDoc.Name + ".docx"; // Читаем ресурс в поток и сохраняем как временный файл using (Stream stream = assembly.GetManifestResourceStream(resourceName)) { SaveStreamToFile(templateFullPath, stream); } try { using (FlatDocument flatDocument = new FlatDocument(templateFullPath)) { // Помещаем в список на удаление _fileToDelete?.Add(tmp); _fileToDelete?.Add(templateFullPath); for (var i = 0; i < toFind.Count; i++) { if (worker != null && worker.CancellationPending) { wordAutomation.CloseWordApp(); break; } worker?.ReportProgress( Convert.ToInt32((decimal)i / toFind.Count * 100), ModPlusAPI.Language.GetItem(LangItem, "h22") + ": " + ModPlusAPI.Language.GetItem(LangItem, "h15") + ": " + kapDoc.Name); flatDocument.FindAndReplace(toFind[i], _toReplace[i]); Thread.Sleep(50); } } // Создаем документ, используя временный файл worker?.ReportProgress(0, ModPlusAPI.Language.GetItem(LangItem, "h23") + ": " + ModPlusAPI.Language.GetItem(LangItem, "h15") + ": " + kapDoc.Name); wordAutomation.CreateWordDoc(templateFullPath, true); } catch (System.Exception exception) { // Если словили ошибку, то закрываем ворд wordAutomation.CloseWordApp(); _error = exception; _hasError = true; } } // Проходим по объектам Лин foreach (var linDoc in _linDocs.Where(x => x.Create)) { if (worker != null && worker.CancellationPending) { wordAutomation.CloseWordApp(); break; } worker?.ReportProgress(0, ModPlusAPI.Language.GetItem(LangItem, "h22") + ": " + ModPlusAPI.Language.GetItem(LangItem, "h16") + ": " + linDoc.Name); // Временный файл var tmp = Path.GetTempFileName(); var templateFullPath = Path.ChangeExtension(tmp, ".docx"); // Имя внедренного ресурса var resourceName = "mpDocTemplates.Resources.Lin." + linDoc.Name + ".docx"; // Читаем ресурс в поток и сохраняем как временный файл using (var stream = assembly.GetManifestResourceStream(resourceName)) { SaveStreamToFile(templateFullPath, stream); } try { using (FlatDocument flatDocument = new FlatDocument(templateFullPath)) { // Помещаем в список на удаление _fileToDelete?.Add(tmp); _fileToDelete?.Add(templateFullPath); for (var i = 0; i < toFind.Count; i++) { if (worker != null && worker.CancellationPending) { wordAutomation.CloseWordApp(); break; } worker?.ReportProgress( Convert.ToInt32((decimal)i / toFind.Count * 100), ModPlusAPI.Language.GetItem(LangItem, "h22") + ": " + ModPlusAPI.Language.GetItem(LangItem, "h16") + ": " + linDoc.Name); flatDocument.FindAndReplace(toFind[i], _toReplace[i]); Thread.Sleep(50); } } // Создаем документ, используя временный файл worker?.ReportProgress(0, ModPlusAPI.Language.GetItem(LangItem, "h23") + ": " + ModPlusAPI.Language.GetItem(LangItem, "h16") + ": " + linDoc.Name); wordAutomation.CreateWordDoc(templateFullPath, true); } catch (System.Exception exception) { // Если словили ошибку, то закрываем ворд wordAutomation.CloseWordApp(); _error = exception; _hasError = true; } } // Делаем word видимым wordAutomation.MakeWordAppVisible(); }