private void parserText(string s1, string s2, string s3, string file, typeFile tFile, int positonInsertSign) { //string num = s1.Substring(s1.IndexOf("№") + 1, s1.IndexOf("от") - s1.IndexOf("№") - 1).Trim(); string num = s1.Substring(s1.IndexOf("№") + 1).Trim(); num = num.Substring(0, num.IndexOf("от")).Trim(); string sDate = s1.Substring(s1.IndexOf("от")).Replace("от", string.Empty).Replace("г.", string.Empty).Trim(); DateTime date = DateTime.Parse(sDate); string agreement = s2.Replace("Д", string.Empty).Replace("№", string.Empty).Trim(); if (agreement.IndexOf(" ") != -1) { agreement = agreement.Substring(0, agreement.IndexOf(" ")).Trim(); } DataTable dtTmp = Config.hCntMain.FindAgreement1CForAgreement(agreement); if (dtTmp != null && dtTmp.Rows.Count > 0) { int id_agreement = (int)dtTmp.Rows[0]["id"]; bool isAdd = (bool)dtTmp.Rows[0]["isAdd"]; string nameLandLord = (string)dtTmp.Rows[0]["nameLandLord"]; int id_Landlord = (int)dtTmp.Rows[0]["id_Landlord"]; string nameObject = (string)dtTmp.Rows[0]["nameObject"]; FileData fData = new FileData(); fData.setData(file, file, num, date, agreement, s3, id_agreement, isAdd, nameLandLord, tFile, id_Landlord, nameObject, positonInsertSign); if (!AddSignAndConvertToPDF(tFile, fData)) { } } else { FileData fData = new FileData(); fData.setData(file, file, num, date, agreement, s3, 0, true, "", tFile, 0, "", positonInsertSign); lFileData.Add(fData); } }
private bool AddSignAndConvertToPDF(typeFile tFile, FileData fData) { string FileName = fData.FileName; FileInfo newFile = new FileInfo(FileName); string FileNameToSaveAndSign = pathSignTmpPDF + "\\" + Path.GetFileNameWithoutExtension(FileName) + newFile.Extension; string FileAndParse = pathEndParse + "\\" + Path.GetFileNameWithoutExtension(FileName) + newFile.Extension; File.Copy(FileName, FileNameToSaveAndSign, true); string filePDF = pathSignTmpPDF + "\\" + Path.GetFileNameWithoutExtension(FileName) + ".pdf"; newFile = new FileInfo(FileNameToSaveAndSign); Logging.Comment($"Начало обработки файла: { Path.GetFileNameWithoutExtension(filePDF)}"); if (tFile == typeFile.word) { using (var document = DocX.Load(FileNameToSaveAndSign)) { string StrImage = GetImageAgreements(fData.id_Landlord); if (StrImage.Length == 0) { if (File.Exists(FileNameToSaveAndSign)) { File.Delete(FileNameToSaveAndSign); } string sError = $"{fData.nameLandLord}: Отсутствует файлы для подписи"; if (!lStringError.Contains(fData.nameLandLord.Trim())) { lStringError.Add(fData.nameLandLord + "/" + fData.nameObject); } return(false); } Xceed.Document.NET.Image image = document.AddImage(StrImage); Picture picture = image.CreatePicture(); //picture.Rotation = 10; picture.SetPictureShape(BasicShapes.cube); //picture.Height = 115; //picture.Width = 931; //Table table = document.Tables[3]; //table.Rows[7].Remove(); //table.Rows[8].Remove(); //table.Rows[7].MergeCells(0, table.Rows[7].Cells.Count); //table.Rows[7].Cells[0].Paragraphs[0].AppendPicture(picture); Table table = document.Tables[5]; //table.Rows[7].Remove(); table.Rows[10].Remove(); table.Rows[10].MergeCells(0, table.Rows[10].Cells.Count); //table.Rows[10].Cells[0].Paragraphs[0].InsertText("test"); table.Rows[10].Cells[0].Paragraphs[0].AppendPicture(picture); document.Save(); } filePDF = cnvWordToPDF.ConvertData(FileNameToSaveAndSign); } else if (tFile == typeFile.excel) { if (newFile.Extension.Equals(".xls")) { object paramMissing = Type.Missing; string newFileName = newFile.DirectoryName + "\\" + Path.GetFileNameWithoutExtension(FileName) + ".xlsx"; var app = new Microsoft.Office.Interop.Excel.Application(); app.Caption = System.Guid.NewGuid().ToString().ToUpper(); var wb = app.Workbooks.Open(FileName); wb.SaveAs(newFileName, FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook); wb.Close(false, paramMissing, paramMissing); app.Quit(); Config.EnsureProcessKilled(IntPtr.Zero, app.Caption); Marshal.ReleaseComObject(wb); Marshal.FinalReleaseComObject(wb); wb = null; Marshal.ReleaseComObject(app); Marshal.FinalReleaseComObject(app); app = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); File.Delete(FileNameToSaveAndSign); FileNameToSaveAndSign = newFileName; newFile = new FileInfo(FileNameToSaveAndSign); } if (newFile.Extension.Equals(".xlsx")) { string StrImage = GetImageAgreements(fData.id_Landlord); if (StrImage.Length == 0) { if (File.Exists(FileNameToSaveAndSign)) { File.Delete(FileNameToSaveAndSign); } string sError = $"{fData.nameLandLord}: Отсутствует файлы для подписи"; if (!lStringError.Contains(fData.nameLandLord.Trim())) { //lStringError.Add(fData.nameLandLord); lStringError.Add(fData.nameLandLord + "/" + fData.nameObject); } return(false); } ExcelPackage epp = new ExcelPackage(newFile); Bitmap image = new Bitmap(StrImage); OfficeOpenXml.Drawing.ExcelPicture excelImage = null; var worksheet = epp.Workbook.Worksheets[0]; int countRow = worksheet.Dimension.End.Row; int countColumns = worksheet.Dimension.End.Column; bool isStop = false; for (int i = countRow; i > 0; i--) { for (int j = 1; j < countColumns; j++) { object value = worksheet.Cells[i, j].Value; if (value != null) { //Console.WriteLine(value); if (value.ToString().ToLower().Equals("Руководитель".ToLower()) || value.ToString().ToLower().Equals("Предприниматель".ToLower())) { fData.positonInsertSign = i - 1; isStop = true; break; } } } if (isStop) { break; } } excelImage = worksheet.Drawings.AddPicture("image", image); // In .SetPosition, we are using 8th Column and 8th Row, with 0 Offset //var rowCnt = worksheet.Dimension.End.Row; //var colCnt = worksheet.Dimension.End.Column; //worksheet.SetValue(fData.positonInsertSign, 1, "test"); //excelImage.SetPosition(38, 0, 0, 0); excelImage.SetPosition(fData.positonInsertSign, 0, 0, 0); //set size of image, 100= width, 100= height //excelImage.SetSize(931, 115); epp.Save(); //epp.SaveAs() } filePDF = cnvXLSToPDF.ConvertData(FileNameToSaveAndSign); } File.Delete(FileNameToSaveAndSign); newFile = new FileInfo(filePDF); DataTable dtScan = Config.hCntMain.getScan(fData.idAgreement, -1); bool isoverwrite = false; int id_Scane = 0; if (dtScan != null && dtScan.Rows.Count > 0) { EnumerableRowCollection <DataRow> rowCollectScan = dtScan.AsEnumerable().Where(r => r.Field <string>("cName").Contains(Path.GetFileNameWithoutExtension(filePDF))).OrderBy(r => r.Field <int>("id")); if (rowCollectScan.Count() > 0) { DialogResult dlResult = DialogResult.Cancel; Config.DoOnUIThread(() => { dlResult = new MyMessageBox.MyMessageBox($"В каталоге арендатора уже существует файл с сохраняемым именем \r\n \"{Path.GetFileNameWithoutExtension(filePDF)}\"", "Сохранение PDF файла счёта", MyMessageBox.MessageBoxButtons.YesNoCancel, new List <string>(new string[] { "Перезаписать", "Создать копию", "Отмена" })) { Owner = this }.ShowDialog(); }, this); if (dlResult == DialogResult.Cancel) { if (File.Exists(filePDF)) { File.Delete(filePDF); } Logging.Comment($"{Path.GetFileNameWithoutExtension(filePDF)}: файл счёта не сохранён. Операция прервана пользователем"); MessageBox.Show(Config.centralText("PDF файл счёта не сохранён.\nОперация прервана пользователем\n"), "Сохранение PDF файла счёта", MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } if (dlResult == DialogResult.Yes) { Logging.Comment($"{Path.GetFileNameWithoutExtension(filePDF)}: Перезапись"); isoverwrite = true; //id_Scane = (int)rowCollectScan.First()["id"]; } else if (dlResult == DialogResult.No) { string filePDFTmp = filePDF.Replace(Path.GetFileNameWithoutExtension(filePDF), Path.GetFileNameWithoutExtension(filePDF) + $"({rowCollectScan.Count()})"); File.Move(filePDF, filePDFTmp); Logging.Comment($"{Path.GetFileNameWithoutExtension(filePDF)}: Копирование: Новое наименование файла: {Path.GetFileNameWithoutExtension(filePDFTmp)}"); filePDF = filePDFTmp; } } } string ServerPath = $"{net.server}\\{fData.idAgreement}"; //if (id_Scane == 0) //{ DataTable dtResult = Config.hCntMain.setScan(fData.idAgreement, Path.GetFileNameWithoutExtension(filePDF), newFile.Extension, 11, fData.Date, ServerPath); if (dtResult != null && dtResult.Rows.Count > 0) { id_Scane = (int)dtResult.Rows[0]["id"]; net.CopyFile(fData.idAgreement.ToString(), filePDF, Path.GetFileNameWithoutExtension(filePDF) + newFile.Extension, isoverwrite); } //} //else //{ // net.CopyFile(fData.idAgreement.ToString(), filePDF, Path.GetFileNameWithoutExtension(filePDF) + newFile.Extension, isoverwrite); //} Config.hCntMain.SetAgreement1CForAgreement(fData.idAgreement, fData.Number, fData.Date, fData.Agreement, fData.TypePay, fData.isAdd, id_Scane, !isoverwrite); Logging.Comment($"Запись в БД:[idAgreement:{fData.idAgreement};Номер: {fData.Number};Дата: {fData.Date}; Agreement: {fData.Agreement}; Тип оплаты:{fData.TypePay}]"); File.Delete(filePDF); try { File.Move(FileName, FileAndParse); } catch (IOException ex) { newFile = new FileInfo(FileName); string[] listFileInDir = Directory.GetFiles(pathEndParse + "\\", Path.GetFileNameWithoutExtension(FileName) + "*"); if (listFileInDir.Count() > 0) { FileAndParse = pathEndParse + "\\" + Path.GetFileNameWithoutExtension(FileName) + $"({listFileInDir.Count()})" + newFile.Extension; } File.Move(FileName, FileAndParse); } Logging.Comment($"Завершение обработки файла: { Path.GetFileNameWithoutExtension(filePDF)}"); return(true); }
public void setData(string FileName, string Path, string Number, DateTime Date, string Agreement, string TypePay, int idAgreement, bool isAdd, string nameLandLord, typeFile tFile, int id_LandLord, string nameObject, int positonInsertSign) { this.FileName = FileName; this.Path = Path; this.Number = Number; this.Date = Date; this.Agreement = Agreement; this.TypePay = TypePay; this.idAgreement = idAgreement; this.isAdd = isAdd; this.nameLandLord = nameLandLord; this.tFile = tFile; this.id_Landlord = id_LandLord; this.nameObject = nameObject; this.positonInsertSign = positonInsertSign; }