private static void Action(FileInfo file) { // Load the document. using (DocX document = DocX.Load(file.FullName)) { // Replace texts in this document. document.ReplaceText("Apples", "Potatoes"); document.ReplaceText("An Apple", "A Potato"); // create the new image var newImage = document.AddImage(ParallelSample.ParallelSampleResourcesDirectory + @"potato.jpg"); // Look in each paragraph and remove its first image to replace it with the new one. foreach (var p in document.Paragraphs) { var oldPicture = p.Pictures.FirstOrDefault(); if (oldPicture != null) { oldPicture.Remove(); p.AppendPicture(newImage.CreatePicture(150, 150)); } } document.SaveAs(ParallelSample.ParallelSampleOutputDirectory + "Output" + file.Name); Console.WriteLine("\tCreated: Output" + file.Name + ".docx\n"); } }
string createPdf(int UserID) { string filename = ""; UserBAL obj = new UserBAL(); DataTable dt = obj.GetUserDetails(UserID); if (dt.Rows.Count > 0) { using (DocX doc = DocX.Load(HttpContext.Current.Server.MapPath("~/Content/Certificate-TEXAS.docx"))) { // Save this document as the users name followed by .docx doc.ReplaceText("%Name%", dt.Rows[0]["FirstName"] + " " + dt.Rows[0]["LastName"]); doc.ReplaceText("%DATE%", DateTime.Now.ToShortDateString()); doc.SaveAs(HttpContext.Current.Server.MapPath("~/Content/" + dt.Rows[0]["FirstName"] + ".docx")); }// Release this document from memory using (var document = new Document()) { document.LoadFromFile(HttpContext.Current.Server.MapPath("~/Content/" + dt.Rows[0]["FirstName"] + ".docx")); filename = HttpContext.Current.Server.MapPath("~/Content/" + dt.Rows[0]["FirstName"] + ".pdf"); //Save doc file to pdf. document.SaveToFile(filename, FileFormat.PDF); } } return(filename); }
/// <summary> /// Replace Invoice Detauils /// </summary> /// <param name="document"></param> /// <param name="inv_Info"></param> private static void ReplaceInvoiceDetails(DocX document, tblInv_Info inv_Info) { document.ReplaceText("{InvNum}", inv_Info.Inv_Num); document.ReplaceText("{InvDate}", inv_Info.Inv_Date.ToDateFormat()); document.ReplaceText("{PaymentDate}", inv_Info.Inv_Paid ? "Payment Date" : string.Empty); document.ReplaceText("{PDate}", inv_Info.Inv_Paid ? $": {inv_Info.Inv_Paid_Date.FromNullableDateToDateFormat()}": string.Empty); }
public static void CreateWordDocument2(string file_location, string output_location, List <string> list_nguon1, List <string> list_dich1, List <string> list_nguon2, List <string> list_dich2) { // Load the document. using (DocX document = DocX.Load(file_location)) { if (list_nguon1.Count == list_dich1.Count) { for (int i = 0; i < list_nguon1.Count; i++) { // Replace text in this document. document.ReplaceText(list_nguon1[i], list_dich1[i]); } } if (list_nguon2.Count == list_dich2.Count) { for (int i = 0; i < list_nguon2.Count; i++) { // Replace text in this document. document.ReplaceText(list_nguon2[i], list_dich2[i]); } } // Save changes made to this document. //document.Save(); try { document.SaveAs(output_location); } catch { MessageBox.Show("File đang được sử dụng!", "Thông báo", MessageBoxButtons.OK); } } // Release this document from memory. }
public void crearwordasignarrevisor() { string destinipath = "Formatos\\" + solicitante.NoControl; if (!Directory.Exists(destinipath)) { Directory.CreateDirectory(destinipath); } DocX testTemplate = DocX.Load(@"Templatesformatos\asignarevisor.docx"); //Paragraph p = testTemplate.InsertParagraph("Hello World."); DocX testDoc = testTemplate; //Paragraph pa = testDoc.InsertParagraph("Foo."); testDoc.ReplaceText("{nombreproyecto}", solicitante.Proyecto_Residencia.Nombre_Proyecto); testDoc.ReplaceText("{Nombrealumno}", solicitante.Nombre + " " + solicitante.Apellido_Paterno + " " + solicitante.Apellido_Materno); testDoc.SaveAs(destinipath + @"\asignarevisor" + solicitante.NoControl + ".docx"); testTemplate.Save(); }
/// <summary> /// 第二部分(经费以前) /// </summary> /// <param name="jinFeis"></param> /// <returns></returns> public DocX WriteDocs(List <JingFei> jinFeis) { DocX doc = null; double num = 0; try { doc = DocX.Load("wwwroot/Templates/last.docx"); //经费表 jinFeis.ForEach(x => { num += x.JinE.Value; switch (x.MingCheng) { case "资料费": doc.ReplaceText("{jfje1}", x.JinE.ToString()); break; case "调研差旅费": doc.ReplaceText("{jfje2}", x.JinE.ToString()); break; case "材料费": doc.ReplaceText("{jfje3}", x.JinE.ToString()); break; case "制作费": doc.ReplaceText("{jfje4}", x.JinE.ToString()); break; case "软件开发费": doc.ReplaceText("{jfje5}", x.JinE.ToString()); break; case "咨询费": doc.ReplaceText("{jfje6}", x.JinE.ToString()); break; case "知识产权服务费等费用": doc.ReplaceText("{jfje7}", x.JinE.ToString()); break; case "其他": doc.ReplaceText("{jfje8}", x.JinE.ToString()); break; } }); doc.ReplaceText("{zongjine}", num.ToString()); //默认给空 for (int i = 1; i < 9; i++) { doc.ReplaceText("{jfje" + i + "}", " "); } } catch (Exception ex) { throw ex; } return(doc); }
public static void ReplaceWordsBasedOnGender(DocX document, InternalDetails internDetails) { Regex replaceTag = new Regex(@"(<<[a-zA-Z]*\/.*?>>)"); Regex reg_male = new Regex(@"(<<.*?\/)"); Regex reg_female = new Regex(@"(\/.*?>>)"); string word = "DUMMY/FEHLER"; string text = document.Text.ToString(); MatchCollection mc = replaceTag.Matches(text); var matches = new string[mc.Count]; for (int i = 0; i < matches.Length; i++) { matches[i] = mc[i].ToString(); if (internDetails.Sex == Sex.Male) { string tempMale = reg_male.Match(matches[i].ToString()).ToString(); word = tempMale.Substring(2, tempMale.Length - 3); document.ReplaceText(mc[i].ToString(), word); } else { string tempFemale = reg_female.Match(matches[i].ToString()).ToString(); word = tempFemale.Substring(1, tempFemale.Length - 3); document.ReplaceText(mc[i].ToString(), word); } } }
private void ReplaqceWords(DocX document, RequestViewModel requestViewModel) { document.ReplaceText("{department}", db.GetDepartment(requestViewModel.DepartmentId).Name); document.ReplaceText("{year}", DateTime.Now.Year.ToString()); }
/// <summary> /// Ajout le nom du signataire sur /// le document /// </summary> /// <param name="path"></param> private void AjoutNomSignataire(String path) { DocX documentModele = DocX.Load(path); documentModele.ReplaceText("{{PrenomEComptable}}", Page_Principale.Utilisateur.prenom_utilisateur); documentModele.ReplaceText("{{NomEComptable}}", Page_Principale.Utilisateur.nom_utilisateur); documentModele.SaveAs(path); }
public void crearwordRegistroproyecto() { string destinipath = "Formatos\\" + solicitante.NoControl; if (!Directory.Exists(destinipath)) { Directory.CreateDirectory(destinipath); } DocX testTemplate = DocX.Load(@"Templatesformatos\Registrodeproyecto.docx"); //Paragraph p = testTemplate.InsertParagraph("Hello World."); DocX testDoc = testTemplate; //Paragraph pa = testDoc.InsertParagraph("Foo."); try { testDoc.ReplaceText("{fecha}", DateTime.Now.Date.ToString()); testDoc.ReplaceText("{correoelectronico}", solicitante.Correo); testDoc.ReplaceText("{numtelefono}", solicitante.Telefono); testDoc.ReplaceText("{nombreproyecto}", solicitante.Proyecto_Residencia.Nombre_Proyecto); testDoc.ReplaceText("{nombreestudiante}", solicitante.Nombre + " " + solicitante.Apellido_Paterno + " " + solicitante.Apellido_Materno); testDoc.ReplaceText("{numestudiantes}", "1"); testDoc.ReplaceText("{asesorinterno}", solicitante.Proyecto_Residencia.Asesor_Interno.Nombre); testDoc.ReplaceText("{nombreempresa}", solicitante.Proyecto_Residencia.Nombre_de_la_Empresa); testDoc.ReplaceText("{nocontrol}", solicitante.NoControl.ToString()); } catch { } testDoc.SaveAs(destinipath + @"\Registrodeproyecto" + solicitante.NoControl + ".docx"); testTemplate.Save(); }
public ActionResult ExportByDocx() { // 樣板路徑 string TemplatePath = Server.MapPath("~/Templates/TestTemplate.docx"); // 儲存路徑 string SavePath = @"D:/test.docx"; DocX document = DocX.Load(TemplatePath); document.ReplaceText("{{OrderNumber}}", "555555"); document.ReplaceText("{{Name}}", "Kyle"); document.ReplaceText("{{CurrTime}}", DateTime.Now.ToShortTimeString()); document.SaveAs(SavePath); return(File(SavePath, "application/docx", "Report.docx")); }
/// <summary> /// Replace Invoice Items /// </summary> /// <param name="document">Document</param> /// <param name="cartItems">List of invoice items</param> /// <param name="invoicePaid">Invoice Paid</param> private static void ReplaceInvoiceItems(DocX document, List <spGetCartItems_Result> cartItems, bool invoicePaid) { var invoiceItems = cartItems.Select(cart => new { cart.Supplement_Description, cart.Item_Quantity, Price = cart.Item_Price.AddCurrency(), Quantity = cart.Item_Quantity.ToString(), SubTotal = (cart.SubTotal ?? 0M).AddCurrency() }).ToList(); document.ReplaceText("{Description}", string.Join(Environment.NewLine, invoiceItems.Select(p => p.Supplement_Description).ToList())); document.ReplaceText("{Quantity}", string.Join(Environment.NewLine, invoiceItems.Select(p => p.Quantity).ToList())); document.ReplaceText("{Price}", string.Join(Environment.NewLine, invoiceItems.Select(p => p.Price).ToList())); document.ReplaceText("{Amount}", string.Join(Environment.NewLine, invoiceItems.Select(p => p.SubTotal).ToList())); decimal subTotal = cartItems.Sum(p => p.SubTotal) ?? 0M; decimal vat = subTotal * (decimal.Parse(ConfigurationManager.AppSettings["VAT"]) / 100M); document.ReplaceText("{SubTotal}", (subTotal - vat).AddCurrency()); document.ReplaceText("{Balance}", invoicePaid ? "Total" : "Balance Due"); document.ReplaceText("{Vat}", vat.AddCurrency()); document.ReplaceText("{Total}", subTotal.AddCurrency()); }
public void crearwordasignacionasesorinterno() { string destinipath = "Formatos\\" + solicitante.NoControl; if (!Directory.Exists(destinipath)) { Directory.CreateDirectory(destinipath); } DocX testTemplate = DocX.Load(@"Templatesformatos\Asignacionasesorinterno.docx"); //Paragraph p = testTemplate.InsertParagraph("Hello World."); DocX testDoc = testTemplate; //Paragraph pa = testDoc.InsertParagraph("Foo."); try { testDoc.ReplaceText("{nombrealumno}", solicitante.Nombre + " " + solicitante.Apellido_Paterno + " " + solicitante.Apellido_Materno); testDoc.ReplaceText("{correoalumno}", solicitante.Correo); testDoc.ReplaceText("{telefonoalumno}", solicitante.Telefono); testDoc.ReplaceText("{nombreproyecto}", solicitante.Proyecto_Residencia.Nombre_Proyecto); testDoc.ReplaceText("{nombreempresa}", solicitante.Proyecto_Residencia.Nombre_de_la_Empresa); testDoc.ReplaceText("{telefonoasesor}", solicitante.Proyecto_Residencia.Telefono_Asesor_Externo); testDoc.ReplaceText("{nombreasesor}", solicitante.Proyecto_Residencia.Nombre_Asesor_Externo); testDoc.ReplaceText("{cargoasesor}", solicitante.Proyecto_Residencia.Cargo_Asesor_Externo); } catch { } testDoc.SaveAs(destinipath + @"\Asignacionasesorinterno" + solicitante.NoControl + ".docx"); testTemplate.Save(); }
public static void ReplaceData(Newtonsoft.Json.Linq.JObject dtInfo, DocX doc) { if (dtInfo != null) { foreach (var member in dtInfo.Properties().ToList()) { string value = ""; var lines = member.Value.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < lines.Length; i++) { if (i == 0) { value = lines[i]; } else { value = value + "\r" + lines[i]; } } if (member.Name == "age") { value = LabelHelper.GetAgeFromText(value); } doc.ReplaceText("{" + member.Name + "}", ReplaceHexadecimalSymbols(value)); } } }
//Sử dụng docx dll để tạo file word từ template public static void CreateWordDocument(string file_location, string output_location, List <string> list_nguon, List <string> list_dich) { try { // Load the document. using (DocX document = DocX.Load(file_location)) { if (list_nguon.Count == list_dich.Count) { for (int i = 0; i < list_nguon.Count; i++) { // Replace text in this document. document.ReplaceText(list_nguon[i], list_dich[i]); } } //Remove empty paragraph //document.RemoveParagraphAt //document.ReplaceText("^p^p", "^p"); // Save changes made to this document. //document.Save(); document.SaveAs(output_location); } // Release this document from memory. } catch { MessageBox.Show("File mẫu đang mở, liên hệ bộ phận Điện toán để kiểm tra"); return; } }
private void ReplaceKeysWithValues(DocX document, IEnumerable <KeyValuePair> keyValuePairs) { foreach (var keyValuePair in keyValuePairs) { document.ReplaceText($"<<{keyValuePair.Key}>>", keyValuePair.Value); } }
/// <summary> /// 用某行值替换相应的字符串(表名.字段名) /// </summary> /// <param name="docTemplate"></param> /// <param name="row"></param> /// <param name="replaceValues"></param> /// <param name="index"></param> private static void ReplaceFromDataTable(DocX docTemplate, MDataRow row, string[] replaceValues, int index = -1) { string strIndex = index < 0 ? "" : index.ToString(); var tableName = row.TableName; foreach (var cell in row) { var value = cell.Value; var replaceValue = ""; var colName = cell.ColumnName; if (value != null) { replaceValue = value.GetType().Name.ToLower() == "datetime" ? ((DateTime)value).ToString("yyyy年M月") : value.ToString(); } if (replaceValues != null) { if (replaceValues[0] == colName) { var valueIndex = replaceValues.IndexOf(replaceValue); replaceValue = replaceValues[valueIndex + 1]; } } docTemplate.ReplaceText(tableName + "." + cell.ColumnName + strIndex, replaceValue); } }
protected void ResolveTaxon(DocX doc, int taxonID) { String query = "SELECT * FROM vwTaxon WHERE fTaxonomyID = " + taxonID; using (SqlConnection con = new SqlConnection(DataSources.dbConSpecies)) { con.Open(); using (SqlCommand command = new SqlCommand(query, con)) { using (SqlDataReader set = command.ExecuteReader()) { if (!set.Read()) { Response.Write("Invalid taxon id"); Response.End(); } String rank = "~" + set["fTaxonRankName"].ToString().ToUpper() + "~"; // Response.Write(rank + " = " + set["fTaxonomyName"].ToString() + "<br>"); doc.ReplaceText(rank, set["fTaxonomyName"].ToString()); int parentID = (int)set["fTaxonomyParentID"]; if (parentID != 0) { ResolveTaxon(doc, parentID); } } } } }
public static bool BatchReplaceStringByPlaceHolder(string tempFileName, string outFileName, List <string> wait4ReplaceList, bool removeRedundantPlaceHolder, int placeholdernum) { using (DocX document = DocX.Load(tempFileName)) { for (int i = 0; i < placeholdernum; i++) { string src = "{" + (i + 1) + "}"; string dst; if (i >= wait4ReplaceList.Count && !removeRedundantPlaceHolder) { break; } if (i >= wait4ReplaceList.Count && removeRedundantPlaceHolder) { dst = ""; } else { dst = wait4ReplaceList[i]; } document.ReplaceText(src, dst); } document.SaveAs(outFileName); return(true); } }
public void substituidor(string[,] subst) { // We will need a file name for our output file (change to suit your machine): string origem = functions.word_open(); if (origem != null) { // Let's save the file with a meaningful name, including the // applicant name and the letter date: string destino = functions.word_save(); if (destino != null) { DocX letter = DocX.Load(origem); // Perform the replace: for (int i = 0; i < subst.GetLength(0); i++) { letter.ReplaceText(subst[i, 0], subst[i, 1]); } // Save as New filename: letter.SaveAs(destino); } } }
/// <summary> /// For each of the documents in the folder 'docs\', /// Replace the string a with the string b, /// Do this in Parrallel accross many CPU cores. /// </summary> static void ReplaceTextParallel() { Console.WriteLine("\tReplaceTextParallel()\n"); const string a = "apple"; const string b = "pear"; // Directory containing many .docx documents. DirectoryInfo di = new DirectoryInfo(@"docs\"); // Loop through each document in this specified direction. Parallel.ForEach ( di.GetFiles(), currentFile => { // Load the document. using (DocX document = DocX.Load(currentFile.FullName)) { // Replace text in this document. document.ReplaceText(a, b); // Save changes made to this document. document.Save(); } // Release this document from memory. } ); Console.WriteLine("\tCreated: None\n"); }
private void UpdateDocument(DocX document, DocumentFormValue doc) { foreach (var p in doc.Components) { var key = string.Format("[[{0}]]", p.Key); if (string.IsNullOrEmpty(p.Value) && p.RemoveLineIfResultIsEmpty) { var paragraph = document.Paragraphs.FirstOrDefault(x => x.Text.Contains(key)); if (paragraph != null) { var lines = paragraph.Text.Split('\n'); if (lines.Length <= 1) { paragraph.Remove(false); } else { paragraph.ReplaceText("\n" + key, string.Empty); paragraph.ReplaceText(key + "\n", string.Empty); } } } else { document.ReplaceText(key, p.Value ?? string.Empty, false, RegexOptions.IgnoreCase); } } }
public byte[] FillFieldsDocx(byte[] template, Dictionary <string, string> values) { try { using (var ms = new MemoryStream()) { ms.Write(template, 0, template.Length); using (DocX doc = DocX.Load(ms)) { #region Configuracion del Documento doc.MarginLeft = 40; doc.MarginRight = 40; #endregion foreach (var d in values) { doc.ReplaceText(d.Key, !string.IsNullOrWhiteSpace(d.Value)?d.Value:" "); } doc.Save(); } return(ms.ToArray()); } } catch (Exception ex) { StaticSourcesViewModel.ShowMessageError("Algo pasó...", "Ocurrió un error al cargar documento.", ex); return(null); } }
private void CreateDocument(Person person, IEnumerable <ImageSource> filepathCollection) { try { ImageHelper.CreateAndFitImages(filepathCollection); person.FIO = person.FIO == null ? string.Empty : person.FIO; person.Age = person.Age == null ? string.Empty : person.Age; _document.ReplaceText(FIO, person.FIO); _document.ReplaceText(AGE, person.Age); _document.ReplaceText(DATE, person.Date.ToShortDateString()); var curruntTable = _document.Tables[2]; var count = filepathCollection.Count(); if (count >= 1) { var image = _document.AddImage(Path.Combine(Directory.GetCurrentDirectory(), "1.jpeg")); var picture = image.CreatePicture(height, width); curruntTable.Rows[0].Cells[0].Paragraphs[0].InsertPicture(picture); } if (count >= 2) { var image = _document.AddImage(Path.Combine(Directory.GetCurrentDirectory(), "2.jpeg")); var picture = image.CreatePicture(height, width); curruntTable.Rows[0].Cells[1].Paragraphs[0].InsertPicture(picture); } if (count >= 3) { var image = _document.AddImage(Path.Combine(Directory.GetCurrentDirectory(), "3.jpeg")); var picture = image.CreatePicture(height, width); curruntTable.Rows[1].Cells[0].Paragraphs[0].InsertPicture(picture); //curruntTable.InsertRow(); //curruntTable.Rows[1].Cells[0].Paragraphs[0].InsertPicture(picture); } if (count >= 4) { var image = _document.AddImage(Path.Combine(Directory.GetCurrentDirectory(), "4.jpeg")); var picture = image.CreatePicture(height, width); //curruntTable.Rows[1].Cells[1].Paragraphs[0].InsertPicture(picture); curruntTable.Rows[1].Cells[1].Paragraphs[0].InsertPicture(picture); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private Stream CreateLabel(int id) { var model = new ProfileBoxModel(); var profileBox = _profileBoxService.GetById(id); string label = profileBox.Name.ToUpper(); string profileCount = ""; if (!profileBox.ProfileType.Scanned) { profileCount = profileBox.ProfileCount.ToString(); } else { var profiles = _profileService.SearchProfilesByStatus(id, 0, 1, int.MaxValue, null, null); profileCount = profiles.Count(x => x.StatusId != (short)ProfileStatus.Deleted).ToString(); } string filePath = Server.MapPath(Url.Content("~/Template/Label.docx")); DocX document = DocX.Load(filePath); var outputStream = new MemoryStream(); document.ReplaceText("{Label}", label); document.ReplaceText("{count}", profileCount); // get placeholder image Novacode.Image img = document.Images[0]; // create barcode encoder var barcodeWriter = new BarcodeWriter { Format = BarcodeFormat.CODE_128, Options = new EncodingOptions { PureBarcode = false, Height = 100, Width = 300, Margin = 10 } }; // create barcode image var bitmap = barcodeWriter.Write(label); // replace place holder image in document with barcode image bitmap.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png); document.SaveAs(outputStream); outputStream.Position = 0; document.Dispose(); return(outputStream); }
//генерация квитанции protected void btUAPay_Click(object sender, EventArgs e) { UAbonentDO uaDO = new UAbonentDO(); UOrderDO uoDO = new UOrderDO(); UOrder uo; UAbonent ua; UniversalEntity ue = new UniversalEntity(); int id = Convert.ToInt32(hfODID.Value); ue = uaDO.RetrieveByOrderID(id); UOrderDetailsDO uodDO = new UOrderDetailsDO(); double sum = 0; double sumrub = 0; if (ue.Count > 0) { ua = (UAbonent)ue[0]; ue = uoDO.RetrieveUOrderById(id); if (ue.Count > 0) { uo = (UOrder)ue[0]; ue = uodDO.RetrieveUOrderDetailsByOrderID(id); foreach (UOrderDetails uod in ue) { sum += uod.Price; //sumrub += (uod.Price)*2; } using (DocX document = DocX.Load(Request.MapPath("~\\Templates/kvitua.docx"))) { //DocXEntender.ReplaceFormatedText(document, "DDD", "дата"); document.ReplaceText("TITLE", ua.Title, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase); document.ReplaceText("ADDRESS", ua.Address, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase); document.ReplaceText("PHONE", ua.Phone, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase); document.ReplaceText("DATE", DateTime.Now.ToString("dd MMMM yyyy"), false, System.Text.RegularExpressions.RegexOptions.IgnoreCase); document.ReplaceText("NNN", uo.ID.ToString(), false, System.Text.RegularExpressions.RegexOptions.IgnoreCase); document.ReplaceText("VIEW", uo.ActionType, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase); document.ReplaceText("SUM", sum.ToString("0.00"), false, System.Text.RegularExpressions.RegexOptions.IgnoreCase); document.ReplaceText("VAT", Utilities.GetVAT(sum).ToString("0.00"), false, System.Text.RegularExpressions.RegexOptions.IgnoreCase); document.ReplaceText("ALL", (sum + Utilities.GetVAT(sum)).ToString("0.00"), false, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // document.ReplaceText("CENA", sumrub.ToString("0.00"), false, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // document.ReplaceText("NDS", Utilities.GetVATRubU(sumrub).ToString("0.00"), false, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // document.ReplaceText("VSEGO", (sumrub + Utilities.GetVAT(sumrub)).ToString("0.00"),false, System.Text.RegularExpressions.RegexOptions.IgnoreCase); //VODOMER document.SaveAs(Request.MapPath("~\\Templates/kvituab.docx")); litScript.Text = "<iframe style=\"display:none;\" src=\"../GetDocument.ashx?pay=Corporate\"></iframe>"; } } } }
public static Stream GenerateIndependencyAndAcceptanceAct(int conflictId) { Conflict conflict = BLLConflicts.GetConflictForArbitration(conflictId); var stream = File.OpenWrite(HttpContext.Current.Server.MapPath("~/Templates/C2. Déclaration d'acceptation et d'indépendance_V1.docx")); using (DocX document = DocX.Load(stream)) { document.ReplaceText("[N° du Litige]", conflict.Id.ToString()); document.ReplaceText("[Demandeur]", conflict.CreatedBy.DisplayName); document.ReplaceText("[Défendeur]", conflict.UsersInConflicts.First(c => c.IdUser != conflict.IdCreationUser).User.DisplayName); document.ReplaceText("[Arbitre]", conflict.Arbiter.DisplayName); document.ReplaceText("[Date]", DateTime.Now.ToShortDateString()); } return(stream); }
private void GeneratePayoffLetter() { // identify template string destinationPath = "/Volumes/GoogleDrive/Shared Drives/Resilience/Documents/Payoff Letter (" + this.AddressComboBox.StringValue + ") (" + this.loan.SaleDate().ToString("yyMMdd") + ").docx"; string templatePath = "/Volumes/GoogleDrive/Shared Drives/Resilience/Document Templates/Payoff Letter " + this.lender.PathAbbreviation() + " " + this.borrower.PathAbbreviation() + ".docx"; // copy template to correct folder System.IO.File.Copy(templatePath, destinationPath, true); // find and replace using doc library // get/compute replacement values DateTime letterDate = DateTime.Today.Date; DateTime scheduledSale = this.loan.SaleDate().Date; double dPrincipalRepay = this.loan.LoanAsOf(scheduledSale.AddDays(1), true).PrincipalPaid(scheduledSale.AddDays(1)) - this.loan.PrincipalPaid(); double dHardInterest = this.loan.LoanAsOf(scheduledSale).AccruedInterest(scheduledSale); double perdiem = dHardInterest - this.loan.LoanAsOf(scheduledSale.AddDays(-1)).AccruedInterest(scheduledSale.AddDays(-1)); // find and replace DocX newLetter = DocX.Load(destinationPath); newLetter.ReplaceText("[LETTERDATE]", letterDate.ToString("MMMM d, yyyy")); newLetter.ReplaceText("[SALEDATE]", scheduledSale.ToString("MMMM d, yyyy")); newLetter.ReplaceText("[ADDRESS]", this.AddressComboBox.StringValue); newLetter.ReplaceText("[INTEREST]", dHardInterest.ToString("#,##0.00")); newLetter.ReplaceText("[PRINCIPAL]", dPrincipalRepay.ToString("#,##0.00")); newLetter.ReplaceText("[PAYOFF]", (dHardInterest + dPrincipalRepay).ToString("#,##0.00")); newLetter.ReplaceText("[PERDIEM]", perdiem.ToString("#0.00")); // save new file newLetter.Save(); // notify this.StatusMessageTextField.StringValue = "Payoff Letter Created at " + destinationPath; }
public static Stream GenerateMissionAct(int conflictId) { Conflict conflict = BLLConflicts.GetConflictForArbitration(conflictId); var demandeur = conflict.UsersInConflicts.First(c => c.IdUser == conflict.IdCreationUser); if (demandeur.IsLawyer != null && demandeur.IsLawyer.Value) { demandeur = conflict.UsersInConflicts.First(c => c.IdLawyer == conflict.IdCreationUser); } var defendeur = conflict.UsersInConflicts.First(c => (c.IsLawyer == null || !c.IsLawyer.Value) && c.IdUser != demandeur.IdUser); var stream = File.OpenWrite(HttpContext.Current.Server.MapPath("~/Templates/C1.Acte De Mission.docx")); using (DocX document = DocX.Load(stream)) { document.ReplaceText("[N° du Litige]", conflict.Id.ToString()); document.ReplaceText("[N° RCS Demandeur]", demandeur.UserCompany != null && demandeur.UserCompany.Company != null ? demandeur.UserCompany.Company.RCS : "RCS Inconnu"); document.ReplaceText("[N° RCS Défendeur]", defendeur.UserCompany != null && defendeur.UserCompany.Company != null ? defendeur.UserCompany.Company.RCS : "RCS Inconnu"); document.ReplaceText("[Demandeur]", demandeur.User.DisplayName); document.ReplaceText("[Défendeur]", defendeur.User.DisplayName); document.ReplaceText("[Arbitre]", conflict.Arbiter.DisplayName); document.ReplaceText("[Date]", DateTime.Now.ToShortDateString()); } return(stream); }
public static Stream GenerateCover(int sortMainId) { var sort = SortMainObject.GetSortMain(sortMainId); if (sort != null) { var toReturn = new MemoryStream(); DocX doc = null; if (sort.Title.Trim().Substring(0, 7).Equals("INL-CON", StringComparison.OrdinalIgnoreCase) || sort.Title.Trim().Substring(0, 7).Equals("INL-JOU", StringComparison.OrdinalIgnoreCase)) { doc = GetJouCover(); } else { doc = GetExtCover(); } doc.ReplaceText("{publicationdate}", sort.PublicationDate?.ToString("MMMM yyyy") ?? string.Empty); doc.ReplaceText("{stititle}", sort.Title?.RemoveNonAscii() ?? string.Empty); doc.ReplaceText("{publishtitle}", sort.PublishTitle?.RemoveNonAscii() ?? string.Empty); doc.ReplaceText("{authors}", string.Join(", ", sort.Authors.Select(n => n.FullName))?.RemoveNonAscii() ?? string.Empty); doc.ReplaceText("{doctype}", sort.ProductTypeDisplayName?.RemoveNonAscii() ?? string.Empty); doc.ReplaceText("{contractnumber}", string.Join(", ", sort.Funding.Select(n => n.ContractNumber))?.RemoveNonAscii() ?? string.Empty); doc.ReplaceText("{fundingoffice}", string.Join(", ", sort.Funding.Select(n => n.TitleFundingSourceName))?.RemoveNonAscii() ?? string.Empty); doc.SaveAs(toReturn); return(toReturn); } return(null); }