public void WriteToFile(string fileName, List<Problem> source, int numberOfPage) { DocX doc = DocX.Create(fileName); var font = new System.Drawing.FontFamily("Consolas"); var rand = new Random(DateTime.Now.Millisecond); var gap = new string(' ', spaceBetweenProblem - 1); var totalCount = colCount * rowCount * numberOfPage; List<Problem> allItems = new List<Problem>(); while (allItems.Count < totalCount) { var problems = source.ToArray(); Utils.Shuffle(problems); allItems.AddRange(problems); } Paragraph lastLine = null; for (int page = 0; page < numberOfPage; page++) { var from = colCount * rowCount * page; for (int row = 0; row < rowCount; row++) { var line1 = doc.InsertParagraph(); lastLine = doc.InsertParagraph(); for (int col = 0; col < colCount; col++) { line1.Append(string.Format("{0} ", allItems[from].LeftNumber.ToString().PadLeft(maxDigits + 1, ' '))).Font(font).FontSize(fontSize).Append(gap).Font(font).FontSize(fontSize); lastLine.Append(string.Format("{0}{1} ", allItems[from].Sign, allItems[from].RightNumber.ToString().PadLeft(maxDigits, ' '))).Font(font).FontSize(fontSize).UnderlineStyle(UnderlineStyle.thick).Append(gap).Font(font).FontSize(fontSize); from++; } if (row != rowCount - 1) { for (int i = 0; i < spaceLinesBetweenItem; i++) { lastLine = doc.InsertParagraph(); } } } if (page != numberOfPage - 1 && addPageBreak) { lastLine.InsertPageBreakAfterSelf(); } } doc.Save(); }
public List InsertList(int index, List list) { Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index); XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex); var elements = new List<XElement> { split[0] }; elements.AddRange(list.Items.Select(i => new XElement(i.Xml))); elements.Add(split[1]); p.Xml.ReplaceWith(elements.ToArray()); return list; }
/// <summary> /// Find all unique instances of the given Regex Pattern, /// returning the list of the unique strings found /// </summary> /// <param name="pattern"></param> /// <param name="options"></param> /// <returns></returns> public virtual List<string> FindUniqueByPattern(string pattern, RegexOptions options) { List<string> rawResults = new List<string>(); foreach (Paragraph p in Paragraphs) { // accumulate the search results from all paragraphs List<string> partials = p.FindAllByPattern(pattern, options); rawResults.AddRange(partials); } // this dictionary is used to collect results and test for uniqueness Dictionary<string, int> uniqueResults = new Dictionary<string, int>(); foreach (string currValue in rawResults) { if (!uniqueResults.ContainsKey(currValue)) { // if the dictionary doesn't have it, add it uniqueResults.Add(currValue, 0); } } return uniqueResults.Keys.ToList(); // return the unique list of results }
public virtual List<int> FindAll(string str, RegexOptions options) { List<int> list = new List<int>(); foreach (Paragraph p in Paragraphs) { List<int> indexes = p.FindAll(str, options); for (int i = 0; i < indexes.Count(); i++) indexes[0] += p.startIndex; list.AddRange(indexes); } return list; }
private void LoadTemplateSets() { var ds = new List<string>(); ds.Add(string.Empty); ds.Add(ITEM_CHOOSE); if (Directory.Exists(SUBS_PATH)) { var files = Directory.GetFiles(SUBS_PATH, SUBS_SEARCH_PATTERN); ds.AddRange(files.Select(s => s.Replace(SUBS_PATH, ""))); } cbSubstitutions.DataSource = ds; }
private void LoadSubstitutions() { var ds = new List<string>(); ds.Add(string.Empty); ds.Add(ITEM_CHOOSE); if (Directory.Exists(TEMPLATES_PATH)) { var dirs = Directory.GetDirectories(TEMPLATES_PATH); ds.AddRange(dirs.Select(s => s.Replace(TEMPLATES_PATH, ""))); } cbTemplate.DataSource = ds; }
//public ActionResult PrintOrder(string codDocument) //{ // //carico l'ordine // Order order = documentRepository.GetAll().OfType<Order>().FirstOrDefault(x => x.CodDocument == codDocument); // //cliente dell'ordine // Customer cust = (Customer)customerSupplierRepository.GetSingle(order.CodCustomer); // order.CustomerSupplier = cust; // //il suo prodotto con la sua quantità // order.OrderProduct = documentRepository.GetDocumentProductByCodDocumentProduct(order.CodDocumentProduct); // //estimate // order.OrderProduct.Document = (Estimate)documentRepository.GetSingle(order.OrderProduct.CodDocument); // string fileNameMain = Path.Combine(Server.MapPath(@"~/Report"), "OrderHead.docx"); // string fileNameCost = Path.Combine(Server.MapPath(@"~/Report"), "Cost.docx"); // string fileNameSaveAs = Path.Combine(Server.MapPath(@"~/Report"), order.OrderNumberSerie + "-" + order.OrderNumber + ".docx"); // string fileNameSaveAsAfterRepair = Path.Combine(Server.MapPath(@"~/Report"), order.OrderNumberSerie + "-" + order.OrderNumber + "AfterRepair.docx"); // // Store a global reference to the executing assembly. // g_assembly = Assembly.GetExecutingAssembly(); // // Create the document in memory: // var docMain = DocX.Load(fileNameMain); // order.MergeField(docMain); // order.OrderProduct.MergeField(docMain); // order.OrderProduct.Product.MergeField(docMain); // var product = productRepository.GetSingle(order.OrderProduct.Product.CodProduct); // product.ProductParts.FirstOrDefault().MergeField(docMain); // // product.ProductParts.FirstOrDefault().ProductPartPrintableArticles.FirstOrDefault().MergeField(docMain); // foreach (var cost in order.OrderProduct.Costs) // { // // Create the document in memory: // //var docCost = DocX.Load(fileNameCost); // // cost.MergeField(docCost); // //try // //{ // var cd = cost.CostDetails.FirstOrDefault(); // if (cd != null) // { // cd = costDetailRepository.GetSingle(cd.CodCostDetail); // cd.InitCostDetail(taskExecutorRepository.GetAll(), articleRepository.GetAll()); // if (cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString() == "PrintedRollArticleCostDetail" || // cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString() == "PrintingZRollCostDetail" || // cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString() == "ControlTableCostDetail") // { // var docPrintCD = DocX.Load(Path.Combine(Server.MapPath(@"~/Report"), cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString() + ".docx")); // cd.MergeField(docPrintCD); // cd.TaskCost.MergeField(docPrintCD); // //il merge con il cost // try // { // cd.TaskCost.ProductPartTask.ProductPart.MergeField(docPrintCD); // } // catch // { } // docMain.InsertDocument(docPrintCD); // docPrintCD.Dispose(); // } // else // { // } // // docMain.InsertDocument(docCost); // } // //} // //catch // //{ } // // docCost.Dispose(); // } // docMain.SaveAs(fileNameSaveAs); // docMain.Dispose(); // // Open a doc file. // Application application = new Application(); // Microsoft.Office.Interop.Word.Document document = application.Documents.Open(fileNameSaveAs, OpenAndRepair: true); // Object fnsa = (Object)fileNameSaveAsAfterRepair; // // Object of Missing "Null Value". // Object oMissing = System.Reflection.Missing.Value; // // Object of false. // Object oFalse = false; // // Save the document. // document.SaveAs // ( // ref fnsa, ref oMissing, ref oMissing, ref oMissing, // ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, // ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, // ref oMissing, ref oMissing // ); // Close word. // document.Close(); // application.Quit(); // return File(fileNameSaveAsAfterRepair, "application/file", "stampa.docx"); //} public ActionResult PrintOrder(string codDocument, string reportName) { int id; var dbName = reportName.Replace("LabelRollHead", ""); //carico l'ordine Order order = documentRepository.GetAll().OfType<Order>().FirstOrDefault(x => x.CodDocument == codDocument); //cliente dell'ordine Customer cust = (Customer)customerSupplierRepository.GetSingle(order.CodCustomer); order.CustomerSupplier = cust; //il suo prodotto con la sua quantità order.OrderProduct = documentRepository.GetDocumentProductByCodDocumentProduct(order.CodDocumentProduct); //estimate order.OrderProduct.Document = documentRepository.GetSingle(order.OrderProduct.CodDocument); string fileNameMain = Path.Combine(Server.MapPath(@"~/Report"), (reportName == "" || reportName == null) ? "OrderHead.docx" : (reportName + ".docx")); string fileNameCost = Path.Combine(Server.MapPath(@"~/Report"), "Cost" + dbName + ".docx"); if (!System.IO.File.Exists(fileNameCost)) { fileNameCost = Path.Combine(Server.MapPath(@"~/Report"), "Cost" + ".docx"); } string retName = order.OrderNumberSerie + "-" + order.OrderNumber; retName = retName.PurgeFileName(); string fileNameSaveAs = Path.Combine(Server.MapPath(@"~/Report"), retName + dbName + ".docx"); string fileNameSaveAsAfterRepair = fileNameSaveAs;// Path.Combine(Server.MapPath(@"~/Report"), retName + "AfterRepair.docx"); // Store a global reference to the executing assembly. g_assembly = Assembly.GetExecutingAssembly(); //// Create the document in memory: var docMain = DocX.Load(fileNameMain); //questo array mi serve per il merge Queue<string> files = new Queue<string>(); //questo array mi serve per il merge Queue<string> filesExtCost = new Queue<string>(); //questo array mi serve per il merge Queue<string> RepassCost = new Queue<string>(); //questo array mi serve per il merge Queue<string> filesDelivery = new Queue<string>(); order.MergeField(docMain); order.OrderProduct.MergeField(docMain); order.OrderProduct.Product.MergeField(docMain); var product = productRepository.GetSingle(order.OrderProduct.Product.CodProduct); product.ProductParts.FirstOrDefault().MergeField(docMain); try { product.ProductParts.FirstOrDefault().productpartprintings.FirstOrDefault().MergeField(docMain); } catch (Exception) { } // product.ProductParts.FirstOrDefault().ProductPartPrintableArticles.FirstOrDefault().MergeField(docMain); var costs = order.OrderProduct.Costs.OrderBy(x => x.IndexOf); Console.WriteLine(costs); //group costdetails by taskexecutor List<CostDetail> costDetails = new List<CostDetail>(); foreach (var item in costs) { costDetails.AddRange(item.CostDetails); } var TaskExecutorGroups = costDetails.GroupBy(p => p.CodTaskExecutorSelected, p => p, (key, g) => new CostDetailGrouped { CodTaskExecutorSelected = key, CostDetails = g.ToList() }); Console.WriteLine(TaskExecutorGroups); //end grouping foreach (var cost in costs) { // Create the document in memory: //var docCost = DocX.Load(fileNameCost); // cost.MergeField(docCost); //try //{ var cd = cost.CostDetails.FirstOrDefault(); if (cd != null) { cd = costDetailRepository.GetSingle(cd.CodCostDetail); cd.InitCostDetail(taskExecutorRepository.GetAll(), articleRepository.GetAll()); if (cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString() == "PrintedRollArticleCostDetail" || cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString() == "PrintingZRollCostDetail" || cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString() == "PrintedSheetArticleCostDetail" || cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString() == "PrintingSheetCostDetail" || cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString() == "ControlTableCostDetail") { #region SingleCostDetail var cDFileName = Path.Combine(Server.MapPath(@"~/Report"), cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString() + dbName + ".docx"); if (!System.IO.File.Exists(cDFileName)) { cDFileName = Path.Combine(Server.MapPath(@"~/Report"), cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString() + ".docx"); } var docPrintCD = DocX.Load(cDFileName); cd.MergeField(docPrintCD); cd.TaskCost.MergeField(docPrintCD); cd.MergeField(docMain); cd.TaskCost.MergeField(docMain); try { cd.TaskCost.ProductPartTask.ProductPart.MergeField(docPrintCD); cd.TaskCost.ProductPartTask.ProductPart.MergeField(docMain); } catch { } docPrintCD.SaveAs(Path.Combine(Server.MapPath(@"~/Report"), "Cost" + cost.CodCost + ".docx")); files.Enqueue(Path.Combine(Server.MapPath(@"~/Report"), "Cost" + cost.CodCost + ".docx")); #region Merge con Docx (vecchio metodo) //var xxx = DocX.Load(Path.Combine(Server.MapPath(@"~/Report"), "Cost" + cost.CodCost + ".docx")); //docMain.InsertDocument(xxx); //docPrintCD.Dispose(); //xxx.Dispose(); #endregion #endregion } else { if (!cost.CostDetails.FirstOrDefault().JustPrintedInOrder) { if (cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString() == "RepassRollCostDetail") { //il ripasso potrebbe includere diverse lavorazioni!!! //ripassi con macchine uguali ---> unisco e salvo #region RepassRollCostDetail //apro l'header dei costi supplementari e lo salvo var nomeRepass = Path.Combine(Server.MapPath(@"~/Report"), "RepassCostHeader" + order.CodDocument + ".docx"); var docRepassHeaderFile = Path.Combine(Server.MapPath(@"~/Report"), "RepassRollCostHeader" + dbName + ".docx"); if (!System.IO.File.Exists(docRepassHeaderFile)) { docRepassHeaderFile = Path.Combine(Server.MapPath(@"~/Report"), "RepassRollCostHeader.docx"); } var docRepassHeader = DocX.Load(docRepassHeaderFile); //estraggo per macchina var relatedCostDetails = TaskExecutorGroups.Where(x => x.CodTaskExecutorSelected == cost.CostDetails.FirstOrDefault().CodTaskExecutorSelected).FirstOrDefault().CostDetails; docRepassHeader.SaveAs(nomeRepass); files.Enqueue(nomeRepass); foreach (var i in relatedCostDetails) { var docPrePressFile = Path.Combine(Server.MapPath(@"~/Report"), "RepassRollCostDetail" + dbName + ".docx"); if (!System.IO.File.Exists(docPrePressFile)) { docPrePressFile = Path.Combine(Server.MapPath(@"~/Report"), "RepassRollCostDetail.docx"); } var docPrePress = DocX.Load(docPrePressFile); var cv = costDetailRepository.GetSingle(i.CodCost); var print = true; if (cv.TaskCost.ProductPartTask != null) { print = !cv.TaskCost.ProductPartTask.OptionTypeOfTask.CodOptionTypeOfTask.Contains("_NO"); } if (cv.TaskCost.ProductTask != null) { print = !cv.TaskCost.ProductTask.OptionTypeOfTask.CodOptionTypeOfTask.Contains("_NO"); } if (print) { cv.MergeField(docPrePress); docPrePress.SaveAs(Path.Combine(Server.MapPath(@"~/Report"), "RepassRollCost" + i.CodCost + ".docx")); RepassCost.Enqueue(Path.Combine(Server.MapPath(@"~/Report"), "RepassRollCost" + i.CodCost + ".docx")); } i.JustPrintedInOrder = true; } id = 0; foreach (var file in RepassCost.Reverse()) { using (WordprocessingDocument myDoc = WordprocessingDocument.Open(nomeRepass, true)) { var altChunkId = "AltChunkId" + id++; Console.WriteLine(altChunkId); var mainPart = myDoc.MainDocumentPart; var chunk = mainPart.AddAlternativeFormatImportPart(DocumentFormat.OpenXml.Packaging.AlternativeFormatImportPartType.WordprocessingML, altChunkId); using (System.IO.FileStream fileStream = System.IO.File.Open(file, System.IO.FileMode.Open)) { chunk.FeedData(fileStream); } var altChunk = new DocumentFormat.OpenXml.Wordprocessing.AltChunk(); altChunk.Id = altChunkId; var last = mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last(); mainPart.Document.Body.InsertAfter(altChunk, last); mainPart.Document.Save(); } } #endregion } } var res = cost.CostDetails.FirstOrDefault().TypeOfCostDetail.ToString(); Console.WriteLine(res); } // docMain.InsertDocument(docCost); } } #region costi supplementari //apro l'header dei costi supplementari e lo salvo var nomeExt = Path.Combine(Server.MapPath(@"~/Report"), "ExtCostHeader" + order.CodDocument + ".docx"); var docECHeaderFile = Path.Combine(Server.MapPath(@"~/Report"), "ExternalCostHeader" + dbName + ".docx"); if (!System.IO.File.Exists(docECHeaderFile)) { docECHeaderFile = Path.Combine(Server.MapPath(@"~/Report"), "ExternalCostHeader.docx"); } var docECHeader = DocX.Load(docECHeaderFile); docECHeader.SaveAs(nomeExt); files.Enqueue(nomeExt); //0=incluso, 1=Aux, 2=escluso var extCost = costs.Where(x => x.TypeOfCalcolous == 1 && (x.Quantity ?? 0) != 0); //prestampa foreach (var cost in extCost) { var docPrePressFile = Path.Combine(Server.MapPath(@"~/Report"), "ExternalCost" + dbName + ".docx"); if (!System.IO.File.Exists(docPrePressFile)) { docPrePressFile = Path.Combine(Server.MapPath(@"~/Report"), "ExternalCost.docx"); } var docPrePress = DocX.Load(docPrePressFile); cost.MergeField(docPrePress); docPrePress.SaveAs(Path.Combine(Server.MapPath(@"~/Report"), "ExtCost" + cost.CodCost + ".docx")); filesExtCost.Enqueue(Path.Combine(Server.MapPath(@"~/Report"), "ExtCost" + cost.CodCost + ".docx")); } id = 0; foreach (var file in filesExtCost.Reverse()) { using (WordprocessingDocument myDoc = WordprocessingDocument.Open(nomeExt, true)) { var altChunkId = "AltChunkId" + id++; Console.WriteLine(altChunkId); var mainPart = myDoc.MainDocumentPart; var chunk = mainPart.AddAlternativeFormatImportPart(DocumentFormat.OpenXml.Packaging.AlternativeFormatImportPartType.WordprocessingML, altChunkId); using (System.IO.FileStream fileStream = System.IO.File.Open(file, System.IO.FileMode.Open)) { chunk.FeedData(fileStream); } var altChunk = new DocumentFormat.OpenXml.Wordprocessing.AltChunk(); altChunk.Id = altChunkId; var last = mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last(); mainPart.Document.Body.InsertAfter(altChunk, last); mainPart.Document.Save(); } } #endregion #region consegne //apro l'header dei costi supplementari e lo salvo var nomeDelivery = Path.Combine(Server.MapPath(@"~/Report"), "DeliveryHeader" + order.CodDocument + ".docx"); var docDHeaderFile = Path.Combine(Server.MapPath(@"~/Report"), "DeliveryHeader" + dbName + ".docx"); if (!System.IO.File.Exists(docDHeaderFile)) { docDHeaderFile = Path.Combine(Server.MapPath(@"~/Report"), "DeliveryHeader.docx"); } var docDHeader = DocX.Load(docDHeaderFile); docDHeader.SaveAs(nomeDelivery); files.Enqueue(nomeDelivery); #endregion #region Immagine //using (MemoryStream ms = new MemoryStream()) //{ // System.Drawing.Image myImg = System.Drawing.Image.FromFile(Path.Combine(Server.MapPath(@"~/Report"), "montaggio.png")); // myImg.Save(ms, myImg.RawFormat); // Save your picture in a memory stream. // ms.Seek(0, SeekOrigin.Begin); // Novacode.Image img = docMain.AddImage(ms); // Create image. // // Insert an emptyParagraph into this document. // Novacode.Paragraph p = docMain.InsertParagraph("", false); // Picture pic1 = img.CreatePicture(); // Create picture. // // pic1.SetPictureShape(BasicShapes.cube); // Set picture shape (if needed) // p.InsertPicture(pic1, 0); // Insert picture into paragraph. //} #endregion docMain.SaveAs(fileNameSaveAs); docMain.Dispose(); id = 0; foreach (var file in files.Reverse()) { using (WordprocessingDocument myDoc = WordprocessingDocument.Open(fileNameSaveAs, true)) { var altChunkId = "AltChunkId" + id++; Console.WriteLine(altChunkId); var mainPart = myDoc.MainDocumentPart; var chunk = mainPart.AddAlternativeFormatImportPart(DocumentFormat.OpenXml.Packaging.AlternativeFormatImportPartType.WordprocessingML, altChunkId); using (System.IO.FileStream fileStream = System.IO.File.Open(file, System.IO.FileMode.Open)) { chunk.FeedData(fileStream); } var altChunk = new DocumentFormat.OpenXml.Wordprocessing.AltChunk(); altChunk.Id = altChunkId; var last = mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last(); mainPart.Document.Body.InsertAfter(altChunk, last); mainPart.Document.Save(); } } //// Open a doc file. //Application application = new Application(); //Microsoft.Office.Interop.Word.Document document = application.Documents.Open(fileNameSaveAs, OpenAndRepair: true); //Object fnsa = (Object)fileNameSaveAsAfterRepair; //// Object of Missing "Null Value". //Object oMissing = System.Reflection.Missing.Value; //// Object of false. //Object oFalse = false; //// Save the document. //document.SaveAs //( // ref fnsa, ref oMissing, ref oMissing, ref oMissing, // ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, // ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, // ref oMissing, ref oMissing //); // Close word. //document.Close(); //application.Quit(); return File(fileNameSaveAsAfterRepair, "application/file", retName + ".docx"); }