using DevExpress.XtraTab; using iTextSharp.text.pdf; using Lskj.Business; using Lskj.Business.Impl; using Lskj.Control; using Lskj.Control.Model; using Lskj.Model; using Lskj.PubPdfSign.Model; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; using System.Windows.Forms; namespace Lskj.PubPdfSign { public partial class FrmAddSign : BaseForm { public DynamicPdfSignModel PdfSignModel; public FrmAddSign() { InitializeComponent(); this.SizeChanged += OnSizeChanged; this.tabControl.SelectedPageChanged += OnSelectedPageChanged; this.Load += OnFrmAddSignLoad; } private void OnFrmAddSignLoad(object sender, EventArgs e) { if (PdfSignModel.Type.Equals("2")) { this.Opacity = 0; this.ShowInTaskbar = false; } WaitForm.ShowForm(); try { if (string.IsNullOrEmpty(PdfSignModel.ModuleCode)) { MessageUtil.Show("配置错误,模块编号不能为空"); return; } if (string.IsNullOrEmpty(PdfSignModel.VersionCode)) { MessageUtil.Show("配置错误,签署版本不能为空"); return; } if (string.IsNullOrEmpty(PdfSignModel.PrimaryValue)) { MessageUtil.Show("配置错误,签署单据不能为空"); return; } if (string.IsNullOrEmpty(PdfSignModel.StepCode)) { MessageUtil.Show("配置错误,签署步骤不能为空"); return; } ModuleModel moduleModel = new ModuleModel(MainImpl.GetSystemdllTab(PdfSignModel.ModuleCode)); string paimaryKey = BaseImpl.GetBasePrimaryKey(PdfSignModel.ModuleCode); string stepUsersSql = $"select crm_htp_examinename from {moduleModel.MenuTable} where {paimaryKey} = '{PdfSignModel.PrimaryValue}'"; string stepUsers = BaseImpl.GetResult(stepUsersSql) + ""; string allStepSql = $"select *,'' as signUser from p_systemdlltabflowtypestep where typecode = '{PdfSignModel.ModuleCode}' order by stepCode"; DataTable allStepTable = BaseImpl.GetDataTableResult(allStepSql); if (allStepTable == null || allStepTable.Rows.Count == 0) { MessageUtil.Show("配置错误,流转步骤不能为空"); return; } int signStepCode = Convert.ToInt32(PdfSignModel.StepCode); int maxStepCode = Convert.ToInt32(allStepTable.Rows[allStepTable.Rows.Count - 1]["stepCode"] + ""); bool isFinishStep = false; string[] stepUserArray = stepUsers.Trim().TrimStart(',').TrimEnd(',').Split(','); bool isNext = false; for (int i = 0; i < allStepTable.Rows.Count; i++) { DataRow stepRow = allStepTable.Rows[i]; if (stepUserArray.Length > i) { if (isNext) { stepRow["signUser"] = stepUserArray[i - 1]; } else { stepRow["signUser"] = stepUserArray[i]; } } isNext = false; DataRow nextStepRow = null; if (i + 1 < allStepTable.Rows.Count) { nextStepRow = allStepTable.Rows[i + 1]; } int stepCode = Convert.ToInt32(stepRow["stepCode"] + ""); if (stepCode == maxStepCode) { isFinishStep = true; signStepCode = stepCode; break; } bool canSign = CanSign(stepRow, nextStepRow, ref isNext); if (canSign) { signStepCode = stepCode; break; } } string allFileSql = $"select * from P_fm_FileTab where dllcoid = '{PdfSignModel.ModuleCode}' and parentid =(select dirid from P_fm_DirectoryTab where PID = '{PdfSignModel.PrimaryValue}')"; DataTable allFileTable = BaseImpl.GetDataTableResult(allFileSql); string selectSql = $"select * from P_SignLocationTable where mainId = '{PdfSignModel.VersionCode}'"; DataTable allSignTable = BaseImpl.GetDataTableResult(selectSql); List signRows = allSignTable.Rows.Cast().Where(n => !string.IsNullOrEmpty((n["stepCode"] + "")) && !(n["stepCode"] + "").Equals("0") && !(n["stepCode"] + "").Equals("9999") && (Convert.ToInt32(n["stepCode"] + "") <= Convert.ToInt32(signStepCode))).ToList(); List otherSignRows = allSignTable.Rows.Cast().Where(n => string.IsNullOrEmpty(n["stepCode"] + "") || (n["stepCode"] + "").Equals("0") || (n["stepCode"] + "").Equals("9999")).ToList(); if (allFileTable == null || allFileTable.Rows.Count == 0) { MessageUtil.Show("没有查询到需要签署的文件"); return; } if (signRows == null || signRows.Count == 0) { MessageUtil.Show("没有需要签署的步骤"); return; } string tempDirectory = $"{Application.StartupPath}\\PdfSign\\PdfFileTemp"; if (Directory.Exists(tempDirectory)) { Directory.Delete(tempDirectory, true); } for (int i = 0; i < allFileTable.Rows.Count; i++) { bool canSign = true; DataRow fileRow = allFileTable.Rows[i]; string fileId = fileRow["fileId"] + ""; string fileName = fileRow["sName"] + ""; if (fileName.Contains("技术更改通知单")) { continue; } string speciesno = fileRow["speciesno"] + ""; string parentid = fileRow["parentid"] + ""; int.TryParse(fileRow["signed"] + "", out int signed); string savePath = $"{Application.StartupPath}\\PdfSign\\PdfFileTemp\\saveSignTempFile{i}.pdf"; string fileWebPath = fileRow["webPath"] + ""; string fileUrl = fileWebPath.StartsWith("http") ? fileWebPath : SystemInfo.Instance.OAUrl + fileWebPath; string defaultDownPath = $"{Application.StartupPath}\\PdfSign\\PdfFileTemp\\addSignTempFile.pdf"; using (WebClient webClient = new WebClient()) { try { if (!Directory.Exists(Path.GetDirectoryName(defaultDownPath))) { Directory.CreateDirectory(Path.GetDirectoryName(defaultDownPath)); } File.Delete(defaultDownPath); for (int j = 0; j < 6; j++) { fileUrl = HttpUtility.UrlDecode(fileUrl); } webClient.DownloadFile(fileUrl, defaultDownPath); } catch (Exception) { throw; } } if (!File.Exists(defaultDownPath)) { MessageUtil.Show("文件下载失败"); return; } if (!Directory.Exists(Path.GetDirectoryName(savePath))) { Directory.CreateDirectory(Path.GetDirectoryName(savePath)); } File.Delete(savePath); using (FileStream fileStream = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite)) { using (PdfReader reader = new PdfReader(defaultDownPath)) { using (PdfStamper stamper = new PdfStamper(reader, fileStream)) { for (int j = 0; j < signRows.Count; j++) { DataRow signRow = signRows[j]; DataRow dataRow = allStepTable.Rows.Cast().Where(n => (n["stepCode"] + "").Equals(signRow["stepCode"] + "")).FirstOrDefault(); if (dataRow != null) { string userId = ""; if (Convert.ToInt32(signRow["stepCode"] + "") < Convert.ToInt32(PdfSignModel.StepCode)) { userId = dataRow["signUser"] + ""; } else { userId = ERPInfo.Instance.UserId; } string userSignDownPath = $"{Application.StartupPath}\\PdfSign\\PdfFileTemp\\userSignTempImage.png"; if (!GetSignUser(userSignDownPath, userId)) { MessageUtil.Show("获取签名失败"); canSign = false; break; } int pageNum = Convert.ToInt32(signRow["pageNum"] + ""); float absoluteY = (float)Convert.ToDouble(signRow["absoluteY"] + ""); float absoluteX = (float)Convert.ToDouble(signRow["absoluteX"] + ""); float pdfImageWidth = (float)Convert.ToDouble(signRow["pdfImageWidth"] + ""); float pdfImageHeight = (float)Convert.ToDouble(signRow["pdfImageHeight"] + ""); int readPageNum = reader.NumberOfPages; PdfContentByte pdfContentByte = stamper.GetOverContent(pageNum);//获取内容 using (Stream inputImageStream = new FileStream(userSignDownPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);//获取图片 image.ScaleAbsolute(pdfImageWidth, pdfImageHeight);//设置图片比例 image.SetAbsolutePosition(absoluteX, absoluteY);//设置图片的绝对位置 pdfContentByte.AddImage(image); } } } if (isFinishStep) { foreach (DataRow otherSignRow in otherSignRows) { int pageNum = Convert.ToInt32(otherSignRow["pageNum"] + ""); float absoluteY = (float)Convert.ToDouble(otherSignRow["absoluteY"] + ""); float absoluteX = (float)Convert.ToDouble(otherSignRow["absoluteX"] + ""); float pdfImageWidth = (float)Convert.ToDouble(otherSignRow["pdfImageWidth"] + ""); float pdfImageHeight = (float)Convert.ToDouble(otherSignRow["pdfImageHeight"] + ""); int readPageNum = reader.NumberOfPages; PdfContentByte pdfContentByte = stamper.GetOverContent(pageNum);//获取内容 string signInfo = (otherSignRow["pdfAdditionalUrl"] + "").Trim(); if ((otherSignRow["stepCode"] + "").Equals("9999")) { signInfo = "@select convert(varchar,getdate(),23)"; } if (!string.IsNullOrEmpty(signInfo)) { if (signInfo.StartsWith("@")) { try { string addInfo = BaseImpl.GetResult(signInfo.TrimStart('@')) + ""; using (Bitmap bitmap = new Bitmap(150, 50)) { using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.Clear(Color.Transparent); StringFormat stringFormat = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }; RectangleF rect = new RectangleF(0, 0, 150, 50); graphics.DrawString(addInfo, new Font("微软雅黑", 16, FontStyle.Regular), new SolidBrush(Color.Black), rect, stringFormat); } using (MemoryStream memoryStream = new MemoryStream()) { bitmap.Save(memoryStream, ImageFormat.Png); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(memoryStream.ToArray());//获取图片 image.ScaleAbsolute(pdfImageWidth, pdfImageHeight);//设置图片比例 image.SetAbsolutePosition(absoluteX, absoluteY);//设置图片的绝对位置 pdfContentByte.AddImage(image); } } } catch (Exception ex) { canSign = false; MessageUtil.Show($"添加自定义文本异常:{ex.Message}"); } } else if (signInfo.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { try { string otherDownPath = $"{Application.StartupPath}\\PdfSign\\PdfFileTemp\\otherSignTemp.png"; using (WebClient webClient = new WebClient()) { if (!Directory.Exists(Path.GetDirectoryName(otherDownPath))) { Directory.CreateDirectory(Path.GetDirectoryName(otherDownPath)); } File.Delete(otherDownPath); for (int j = 0; j < 6; j++) { signInfo = HttpUtility.UrlDecode(signInfo); } webClient.DownloadFile(signInfo, otherDownPath); } using (Stream stream = new FileStream(otherDownPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(stream);//获取图片 image.ScaleAbsolute(pdfImageWidth, pdfImageHeight);//设置图片比例 image.SetAbsolutePosition(absoluteX, absoluteY);//设置图片的绝对位置 pdfContentByte.AddImage(image); } } catch (Exception ex) { canSign = false; MessageUtil.Show($"签名添加异常:{ex.Message}\r\nUrl:{signInfo}"); } } } } } } } } if (isFinishStep && PdfSignModel.Type.Equals("2")) { DataRow dataRow = BaseImpl.GetDataRowResult("select top 1 * from p_systemtab"); string newfileOAUrl = dataRow.Table.Columns.Contains("fileOAUrl") ? dataRow["fileOAUrl"] + "" : ""; //终审移动文件到历史文件夹 if (!string.IsNullOrEmpty(newfileOAUrl)) { string baseSpeciesNo = speciesno.Length >= 6 ? speciesno.Substring(0, 6) : ""; int revIndex = fileName.IndexOf("Rev", StringComparison.OrdinalIgnoreCase); string baseFileName = revIndex > 0 ? fileName.Substring(0, revIndex) : ""; string baseRev = revIndex > 0 ? fileName.Substring(revIndex + 3, 4) : ""; List fileids = new List(); #region 老文件判断 string selectsql = $"SELECT * FROM P_FileSpeciesInfoTab WHERE LEFT(speciesno, 6) = '{baseSpeciesNo}' and (vname = '{fileName}' or (SUBSTRING(vname, 1, CHARINDEX('Rev', vname) - 1) = '{baseFileName}' and SUBSTRING(vname, CHARINDEX('Rev', vname)+3,4) <> '{baseRev}')) and isnull(isMove,'1') = '1'"; DataTable oldmMoveFileTable = BaseImpl.GetDataTableResult(selectsql); foreach (DataRow item in oldmMoveFileTable.Rows) { if ((item["vname"] + "").Contains("技术更改通知单")) { continue; } UploadModel moveModel = new UploadModel(); string filePath = BaseImpl.GetResult($"select lserp_xt01.[dbo].[fun_fm_getAbsolutePath]({item["fileId"]})") + ""; string newDir = BaseImpl.GetResult($"select moveNewDir from p_systemtab") + ""; string newFilePath = filePath; if (!string.IsNullOrEmpty(newFilePath)) { // 找到第一个斜杠的位置 int firstSlashIndex = newFilePath.IndexOf('/'); if (firstSlashIndex >= 0) { newFilePath = newFilePath.Substring(firstSlashIndex + 1); } int secondSlashIndex = newFilePath.IndexOf('/'); if (secondSlashIndex >= 0) { newFilePath = newFilePath.Substring(secondSlashIndex + 1); } newFilePath = Path.GetDirectoryName(newFilePath); newDir = $"{newDir}\\{newFilePath}"; bool isMove = FileUploadUtil.MoveFileTo(newfileOAUrl, item["fileId"] + "", filePath, newDir, PdfSignModel, ref moveModel); //插入日志 string logSql = $"insert into P_UploadFileLogTab (step,msg,mainKey,date) values ('移动文件:{item["fileId"] + ""}到历史文件夹','{isMove},{moveModel.Msg}','{PdfSignModel.PrimaryValue}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')"; BaseImpl.ExecSqlValue(logSql); if (isMove) { fileids.Add(item["fileId"] + ""); string moveWebpath = BaseImpl.GetResult($"select webpath from lserp_xt01.[dbo].[p_fm_filetab] where fileid = '{item["fileId"]}'") + ""; BaseImpl.ExecSqlValue($"update P_FileSpeciesInfoTab set isMove = '2' where fileId = '{item["fileId"]}'"); } } } #endregion string sql = $"SELECT * FROM p_fm_signFileTab WHERE LEFT(speciesno, 6) = '{baseSpeciesNo}' and (sname = '{fileName}' or (SUBSTRING(sName, 1, CHARINDEX('Rev', sName) - 1) = '{baseFileName}' and SUBSTRING(sName, CHARINDEX('Rev', sName)+3,4) <> '{baseRev}')) and isMove = '1'"; //if (!string.IsNullOrEmpty(sql)) //{ // Clipboard.SetText(sql); //} DataTable moveFileTable = BaseImpl.GetDataTableResult(sql); foreach (DataRow item in moveFileTable.Rows) { if (fileids.Contains(item["fileId"] + "")) { continue; } if ((item["sname"] + "").Contains("技术更改通知单")) { continue; } UploadModel moveModel = new UploadModel(); string filePath = BaseImpl.GetResult($"select lserp_xt01.[dbo].[fun_fm_getAbsolutePath]({item["fileId"]})") + ""; string newDir = BaseImpl.GetResult($"select moveNewDir from p_systemtab") + ""; string newFilePath = filePath; if (!string.IsNullOrEmpty(newFilePath)) { // 找到第一个斜杠的位置 int firstSlashIndex = newFilePath.IndexOf('/'); if (firstSlashIndex >= 0) { newFilePath = newFilePath.Substring(firstSlashIndex + 1); } int secondSlashIndex = newFilePath.IndexOf('/'); if (secondSlashIndex >= 0) { newFilePath = newFilePath.Substring(secondSlashIndex + 1); } newFilePath = Path.GetDirectoryName(newFilePath); newDir = $"{newDir}\\{newFilePath}"; bool isMove = FileUploadUtil.MoveFileTo(newfileOAUrl, item["fileId"] + "", filePath, newDir, PdfSignModel, ref moveModel); //插入日志 string logSql = $"insert into P_UploadFileLogTab (step,msg,mainKey,date) values ('移动文件:{item["fileId"] + ""}到历史文件夹','{isMove},{moveModel.Msg}','{PdfSignModel.PrimaryValue}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')"; BaseImpl.ExecSqlValue(logSql); if (isMove) { string moveWebpath = BaseImpl.GetResult($"select webpath from lserp_xt01.[dbo].[p_fm_filetab] where fileid = '{item["fileId"]}'") + ""; BaseImpl.ExecSqlValue($"update p_fm_SignFileTab set isMove = '2',webpath = '{moveWebpath}' where fileId = '{item["fileId"]}'"); } } } } //先上传到新的服务器 if (!string.IsNullOrEmpty(newfileOAUrl)) { UploadModel uploadModel = new UploadModel() { FileName = fileName, SpeciesNo = speciesno }; bool isUpload = FileUploadUtil.UploadFileToServer(newfileOAUrl, savePath, PdfSignModel, ref uploadModel); //插入日志 string logSql = $"insert into P_UploadFileLogTab (step,msg,mainKey,date) values ('上传文件到终审服务器','{isUpload},{uploadModel.Msg}','{PdfSignModel.PrimaryValue}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')"; BaseImpl.ExecSqlValue(logSql); if (isUpload) { string primaryKey = BaseImpl.GetResult($"select pid from p_fm_directorytab where dirid = '{parentid}'") + ""; BaseImpl.ExecSqlValue($"update lserp_xt01.[dbo].[p_fm_filetab] set primaryKey = '{primaryKey}',datetime = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' where fileId = '{uploadModel.FileId}'"); BaseImpl.ExecSqlValue($"delete from p_fm_SignFileTab where fileId = '{uploadModel.FileId}'"); BaseImpl.ExecSqlValue($"insert into p_fm_SignFileTab (fileId,sName,webPath,speciesno,primaryKey) values ('{uploadModel.FileId}','{uploadModel.FileName}','{uploadModel.Webpath}','{uploadModel.SpeciesNo}','{primaryKey}')"); } else { canSign = false; MessageUtil.Show($"文件上传失败,{uploadModel.Msg}"); } if (isUpload) { UploadModel deleteModel = new UploadModel() { FileId = fileId }; bool isDelete = FileUploadUtil.DeleteFile(deleteModel); //插入日志 string deleteLogSql = $"insert into P_UploadFileLogTab (step,msg,mainKey,date) values ('删除原始文件fileId:{fileId}','{isDelete},{deleteModel.Msg}','{PdfSignModel.PrimaryValue}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')"; BaseImpl.ExecSqlValue(deleteLogSql); } } else { MessageUtil.Show("文件上传失败,上传地址异常"); } } if (PdfSignModel.Type.Equals("1") || PdfSignModel.Type.Equals("2")) { if (canSign && signed <= signStepCode) { BaseImpl.ExecSqlValue($"update P_fm_FileTab set signed = '{PdfSignModel.StepCode}' where fileId = '{fileId}'"); } } //添加预览页签 if (PdfSignModel.Type.Equals("1")) { XtraTabPage xtraTabPage = new XtraTabPage(); xtraTabPage.Text = fileName; FrmWebBrowser frmWebBrowser = new FrmWebBrowser(); frmWebBrowser.FrmLoad(savePath); frmWebBrowser.Dock = DockStyle.Fill; xtraTabPage.Controls.Add(frmWebBrowser); xtraTabPage.Tag = frmWebBrowser; tabControl.TabPages.Add(xtraTabPage); } } } catch (Exception ex) { MessageUtil.Show($"签章异常:{ex.Message}"); } finally { WaitForm.HideForm(); if (PdfSignModel.Type.Equals("2")) { this.DialogResult = DialogResult.OK; this.Close(); this.Dispose(); } } } /// /// 判断是否可以签章 /// /// private bool CanSign(DataRow stepRow, DataRow nextStepRow, ref bool isNext) { bool canSign = true; int signStepCode = Convert.ToInt32(PdfSignModel.StepCode); int stepCode = Convert.ToInt32(stepRow["stepCode"] + ""); string autoStep = stepRow["autoStep"] + ""; string sameAudited = stepRow["sameAudited"] + ""; if (stepCode >= signStepCode) { if (autoStep.Equals("1") && nextStepRow != null && (nextStepRow["autoStep"] + "").Equals("1")) { canSign = false; isNext = true; } if (sameAudited.Equals("1") && nextStepRow != null && (nextStepRow["sameAudited"] + "").Equals("1")) { canSign = false; isNext = true; } } else { canSign = false; } return canSign; } /// /// 获取签章人员 /// /// private bool GetSignUser(string savePath, string userId) { bool isDownLoad = false; if (!string.IsNullOrEmpty(userId)) { string signWebPath = BaseImpl.GetResult($"select bmp from p_employeetab where employeeid = '{userId}'") + ""; string signUrl = signWebPath.StartsWith("http") ? signWebPath : SystemInfo.Instance.OAUrl + signWebPath; using (WebClient webClient = new WebClient()) { try { if (!Directory.Exists(Path.GetDirectoryName(savePath))) { Directory.CreateDirectory(Path.GetDirectoryName(savePath)); } File.Delete(savePath); for (int j = 0; j < 6; j++) { signUrl = HttpUtility.UrlDecode(signUrl); } webClient.DownloadFile(signUrl, savePath); isDownLoad = true; } catch (Exception) { isDownLoad = false; } } if (!File.Exists(savePath)) { isDownLoad = false; } } return isDownLoad; } /// /// 窗体大小改变时 /// /// /// private void OnSizeChanged(object sender, EventArgs e) { foreach (XtraTabPage xtraTabPage in tabControl.TabPages) { System.Windows.Forms.Control[] controls = xtraTabPage.Controls.Find("FrmWebBrowser", true); if (controls.Length > 0) { FrmWebBrowser frmWebBrowser = (FrmWebBrowser)controls[0]; if (frmWebBrowser.cefBrowserSettings != null) { var handle = frmWebBrowser.cefBrowserSettings.GetHost().GetWindowHandle(); frmWebBrowser.ResizeWindow(handle, this.Width, this.Height); } } } } /// /// 页签改变时 /// /// /// private void OnSelectedPageChanged(object sender, TabPageChangedEventArgs e) { if (e.Page.Tag != null && e.Page.Tag is FrmWebBrowser) { FrmWebBrowser frmWebBrowser = (FrmWebBrowser)e.Page.Tag; if (frmWebBrowser.cefBrowserSettings != null) { frmWebBrowser.ResizeWindow(frmWebBrowser.cefBrowserSettings.GetHost().GetWindowHandle(), frmWebBrowser.Width, frmWebBrowser.Height); } } } } }