using iTextSharp.text; using iTextSharp.text.pdf; using Lskj.Business; using Lskj.Business.Impl; using Lskj.Control; using Lskj.Core; using O2S.Components.PDFView4NET; 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.Windows.Forms; namespace Lskj.PubPdfSign.Controls { public partial class PdfEditorEx : UserControl { public PdfEditorEx() { InitializeComponent(); //this.pdfPageView.ZoomMode = PDFZoomMode.Custom; this.SizeChanged += OnPdfEditorExSizeChanged; this.pdfPageView.SizeChanged += OnPdfEditorExSizeChanged; this.btn_UpPage.Click += OnBtnUpPageClick; this.btn_NextPage.Click += OnBtnNextPageClick; } /// /// PDF页面大小改变时 /// /// /// private void OnPdfPageViewSizeChanged(object sender, EventArgs e) { return; } /// /// PDF页面大小改变时 /// /// /// private void OnPdfEditorExSizeChanged(object sender, EventArgs e) { int pageIndex = pdfPageView.PageNumber; if (pdfDocument.Pages.Count == 0 || pdfPageView.PageNumber > pdfDocument.Pages.Count) { return; } List signBoxes = _signBoxList.Where(n => n.PageNumber == pdfPageView.PageNumber + 1).ToList(); foreach (SignBox item in signBoxes) { if (item.ParentResizeControl != null) { item.ParentResizeControl.Visible = false; } ToSignBoxImage(item, pageIndex, item.AbsoluteX, item.AbsoluteY, item.PdfImageWidth, item.PdfImageHeight); } } /// /// 记录全局选中控件 /// public SignBox _selectedSignBox; /// /// 步骤表 /// public DataTable StepTable = new DataTable(); /// /// 保存完成后 /// public event EventHandler OnAfterSignSaveCallback; /// /// 添加签章完成后 /// public event EventHandler OnAfterSignAddCallback; public ToolStrip EditToolStrip { get { return this.editToolStrip; } } /// /// 关联模板id /// public string VersionCode; /// /// 源文件(该文件不进行编辑) /// public string TempletFilePath; /// /// 当前页码 /// public int CurrentPageNo; /// /// 签名集合 /// public List _signBoxList = new List(); /// /// 当前操作文件 /// private string _currentPdf; #region 事件 /// /// 下一页 /// /// /// private void OnBtnNextPageClick(object sender, EventArgs e) { try { if (this.pdfPageView.PageNumber < this.pdfDocument.PageCount - 1) { this.pdfPageView.PageNumber++; this.CurrentPageNo = this.pdfPageView.PageNumber; this.FindSignBox(); } } catch (Exception ex) { MessageUtil.Show(ex.Message); } } /// /// 上一页 /// /// /// private void OnBtnUpPageClick(object sender, EventArgs e) { try { if (this.pdfPageView.PageNumber > 0) { this.pdfPageView.PageNumber--; this.CurrentPageNo = this.pdfPageView.PageNumber; this.FindSignBox(); } } catch (Exception ex) { MessageUtil.Show(ex.Message); } } /// /// 保存 /// /// /// public void OnBtnSaveClick(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(VersionCode)) { MessageUtil.Show("请先设置版本名称并保存后再设计"); return; } if (string.IsNullOrEmpty(this._currentPdf)) return; string defaultSavePath = $"{Application.StartupPath}\\PdfSign\\PdfFileTemp\\signTempFile.pdf"; string tempSavePath = $"{Application.StartupPath}\\PdfSign\\PdfFileSaveTemp\\signTempFile.pdf"; if (!Directory.Exists(Path.GetDirectoryName(defaultSavePath))) { Directory.CreateDirectory(Path.GetDirectoryName(defaultSavePath)); } if (!Directory.Exists(Path.GetDirectoryName(tempSavePath))) { Directory.CreateDirectory(Path.GetDirectoryName(tempSavePath)); } this.Save(defaultSavePath); this.pdfDocument.Close(); File.Copy(defaultSavePath, tempSavePath, true); foreach (SignBox signBox in this._signBoxList) { if (signBox.ParentPicBox != null) { signBox.ParentPicBox.Dispose(); } if (signBox.ParentResizeControl != null) { signBox.ParentResizeControl.Dispose(); } } this._signBoxList = new List(); this._currentPdf = tempSavePath; this.pdfDocument.Load(this._currentPdf); LoadSign(VersionCode, true); //加载到保存前的页码位置 this.pdfPageView.PageNumber = this.CurrentPageNo; if (OnAfterSignSaveCallback != null) { OnAfterSignSaveCallback(null, null); } } catch (Exception ex) { MessageUtil.Show(ex.Message); } } /// /// 打开文件 /// /// /// private void OnBtnOpenClick(object sender, EventArgs e) { try { OpenLocalFile(); } catch (Exception ex) { MessageUtil.Show(ex.Message); } } /// /// 签名删除 /// /// /// private void OnItemClick(object sender, EventArgs e) { ToolStripMenuItem toolStripMenuItem = (ToolStripMenuItem)sender; PictureBox pictureBox = (PictureBox)toolStripMenuItem.Tag; SignBox signBox = (SignBox)pictureBox.Tag; this._signBoxList.Remove(signBox); if (signBox.ParentPicBox != null) { signBox.ParentPicBox.Dispose(); } if (signBox.ParentResizeControl != null) { signBox.ParentResizeControl.Dispose(); } if (OnAfterSignAddCallback != null) { OnAfterSignAddCallback(null, null); } } /// /// 添加签名控件 /// /// /// public void OnBtnAddSignClick(object sender, EventArgs e) { string selectSql = $"select * from P_SignLocationTable where mainId = '{VersionCode}'"; DataTable dataTable = SqlHelper.ExecuteDataTable(selectSql); foreach (DataRow item in StepTable.Rows) { string stepCode = item["stepCode"] + ""; string stepName = item["stepName"] + ""; bool allowAdd = _signBoxList.Where(n => n.StepCode.Equals(stepCode)).Count() == 0; if (!allowAdd || dataTable.Rows.Cast().Where(n => (n["stepCode"] + "").Equals(stepCode)).Count() > 0) { continue; } else { AddSignPicControl(stepCode); } } if (OnAfterSignAddCallback != null) { OnAfterSignAddCallback(null, null); } } #endregion #region 方法 /// /// 打开本地PDF文件 /// /// private string OpenLocalFile() { string fileName = string.Empty; OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); openFileDialog.Filter = "(*.pdf)|*.pdf"; openFileDialog.RestoreDirectory = true; openFileDialog.FilterIndex = 1; if (openFileDialog.ShowDialog() == DialogResult.OK) { this._currentPdf = TempletFilePath = fileName = openFileDialog.FileName; this.pdfDocument.Load(this._currentPdf); //LoadSign(); this.CurrentPageNo = 0; this.pdfPageView.PageNumber = this.CurrentPageNo; } return fileName; } public void OpenLocalFile(DataRow dataRow, bool allowSetMove = true) { ClearSignBox(); string defaultDownPath = $"{Application.StartupPath}\\PdfSign\\PdfFileTemp\\downTempFile.pdf"; string pdfUrl = dataRow["pdfUrl"] + ""; pdfUrl = pdfUrl.StartsWith("http") ? pdfUrl : SystemInfo.Instance.OAUrl + pdfUrl; CloseDocument(); using (WebClient webClient = new WebClient()) { try { if (!Directory.Exists(Path.GetDirectoryName(defaultDownPath))) { Directory.CreateDirectory(Path.GetDirectoryName(defaultDownPath)); } File.Delete(defaultDownPath); webClient.DownloadFile(pdfUrl, defaultDownPath); } catch (Exception ex) { MessageUtil.Show(ex.Message); } } this._currentPdf = TempletFilePath = defaultDownPath; this.pdfDocument.Load(this._currentPdf); LoadSign(VersionCode, allowSetMove); this.CurrentPageNo = 0; this.pdfPageView.PageNumber = this.CurrentPageNo; } /// /// 加载已经存在的标签 /// public void LoadSign(string versionCode, bool allowSetMove = true) { string selectSql = $"select * from P_SignLocationTable where mainId = '{versionCode}'"; DataTable dataTable = SqlHelper.ExecuteDataTable(selectSql); string url = string.Empty; if (dataTable != null && dataTable.Rows.Count > 0) { this._signBoxList = new List(); foreach (DataRow item in dataTable.Rows) { string stepName = string.Empty; url = item["pdfAdditionalUrl"] + ""; string stepCode = item["stepCode"] + ""; int imageHeight = (int)Convert.ToDecimal(item["pdfImageHeight"] + ""); int imageWidth = (int)Convert.ToDecimal(item["pdfImageWidth"] + ""); Bitmap image = new Bitmap(150, 50); if (stepCode.Equals("9999")) { url = "@select convert(varchar,getdate(),23)"; } if (!string.IsNullOrEmpty(url)) { if (url.StartsWith("http")) { using (WebClient webClient = new WebClient()) { byte[] data = webClient.DownloadData(url); using (MemoryStream stream = new MemoryStream(data)) { image = new Bitmap(stream); } } } else if (url.StartsWith("@")) { try { string addInfo = BaseImpl.GetResult(url.TrimStart('@')) + ""; using (Graphics graphics = Graphics.FromImage(image)) { 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 System.Drawing.Font("微软雅黑", 16, FontStyle.Regular), new SolidBrush(Color.Black), rect, stringFormat); } } catch (Exception ex) { MessageUtil.Show(ex.Message); } } } else { image = new Bitmap(100, 50); Graphics graphics = Graphics.FromImage(image); DataRow dataRow = StepTable.Rows.Cast().Where(n => (n["stepCode"] + "").Equals(stepCode)).FirstOrDefault(); stepName = dataRow["stepName"] + ""; StringFormat stringFormat = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }; RectangleF rect = new RectangleF(0, 0, 100, 50); graphics.DrawString(stepName, new System.Drawing.Font("微软雅黑", 24, FontStyle.Bold), new SolidBrush(Color.Green), rect, stringFormat); } SignBox signBox = new SignBox(pdfPageView, pdfDocument.Pages[pdfPageView.PageNumber]); PictureBox pictureBox = new PictureBox(); pictureBox.SizeMode = PictureBoxSizeMode.StretchImage; _signBoxList.Add(signBox); try { signBox.pdfAdditionalUrl = url; signBox.StepCode = stepCode; signBox.StepName = stepName; signBox.ParentPicBox = pictureBox; signBox.PageNumber = (int)Convert.ToDecimal(item["pageNum"] + ""); pictureBox.BorderStyle = BorderStyle.None; pictureBox.Image = image; int pdfImageHeight = (int)Convert.ToDecimal(item["pdfImageHeight"] + ""); int pdfImageWidth = (int)Convert.ToDecimal(item["pdfImageWidth"] + ""); int absoluteY = (int)Convert.ToDecimal(item["absoluteY"] + ""); int absoluteX = (int)Convert.ToDecimal(item["absoluteX"] + ""); ToSignBoxImage(signBox, signBox.PageNumber - 1, absoluteX, absoluteY, pdfImageWidth, pdfImageHeight); //pictureBox.Height = signHeight; //pictureBox.Width = signWidth; pictureBox.Tag = signBox; pictureBox.Parent = this.pdfPageView; if (allowSetMove) { pictureBox.SetMove(); } signBox.UpdateLocation(); ContextMenuStrip cms = new ContextMenuStrip(); cms.Items.Add("删除"); cms.Items[0].Click += new EventHandler(OnItemClick); cms.Items[0].Tag = pictureBox; pictureBox.ContextMenuStrip = cms; //pictureBox.BringToFront(); //pictureBox.Location = new Point(signLeft, signTop); //pictureBox.MouseDown += new MouseEventHandler(OnPictureBox_MouseDown); //pictureBox.MouseMove += new MouseEventHandler(OnPictureBox_MouseMove); //pictureBox.MouseUp += new MouseEventHandler(OnPictureBox_MouseUp); //pictureBox.MouseClick += new MouseEventHandler(OnPictureBox_MouseClick); //pictureBox.MouseLeave += new EventHandler(OnPictureBox_MouseLeave); } catch (Exception ex) { MessageUtil.Show(ex.Message); _signBoxList.Remove(signBox); pictureBox.Dispose(); } } } FindSignBox(); } /// /// 加载记录的sign坐标 /// private void FindSignBox() { //翻页切换时候进行画点操作 //List signBoxs = _signBoxList.Where(o => o.PageNumber == this.pdfPageView.PageNumber).ToList(); foreach (SignBox item in this._signBoxList) { if (item.PageNumber != this.CurrentPageNo + 1) { if (item.ParentPicBox != null) { item.ParentPicBox.Parent = null; } if (item.ParentResizeControl != null) { item.ParentResizeControl.Parent = null; } } else { if (item.ParentPicBox != null) { item.ParentPicBox.Parent = this.pdfPageView; } if (item.ParentResizeControl != null) { item.ParentResizeControl.Parent = this.pdfPageView; } } } } /// /// 保存 /// /// public void Save(string savePath) { StringBuilder sqlBulider = new StringBuilder(); sqlBulider.Append($"delete from P_SignLocationTable where mainId = '{VersionCode}';\r\n"); using (FileStream fileStream = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite)) { using (PdfReader reader = new PdfReader(this._currentPdf)) { PdfStamper stamper = new PdfStamper(reader, fileStream); int readPageNum = reader.NumberOfPages; for (int j = 0; j < readPageNum; j++) { double height = this.pdfDocument.Pages[j].Height; float width = (float)this.pdfDocument.Pages[j].Width; List signBoxes = this._signBoxList.Where(n => n.PageNumber == j + 1).ToList(); foreach (SignBox item in signBoxes) { using (Bitmap cloneBitmap = new Bitmap(item.ParentPicBox.Image)) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(cloneBitmap, ImageFormat.Png); } PDFPageRotation rotation = this.pdfDocument.Pages[this.CurrentPageNo].Rotation; int absoluteX = 0; int absoluteY = 0; int pdfImageWidth = 0; int pdfImageHeight = 0; if (rotation == PDFPageRotation.Rotate0Degrees) { PDFPoint pdfpoint = this.pdfPageView.ConvertScreenPointToPDFPoint(new Point(item.SignLeft, item.SignTop)); PDFPoint pdfpoint2 = this.pdfPageView.ConvertScreenPointToPDFPoint(new Point(item.SignLeft + item.SignWidth, item.SignTop + item.SignHeight)); absoluteX = (int)pdfpoint.X; absoluteY = (int)pdfpoint2.Y; pdfImageWidth = (int)(pdfpoint2.X - pdfpoint.X); pdfImageHeight = (int)(pdfpoint.Y - pdfpoint2.Y); } else if (rotation == PDFPageRotation.Rotate90Degrees) { PDFPoint pdfpoint4 = this.pdfPageView.ConvertScreenPointToPDFPoint(new Point(item.SignLeft + item.SignWidth, item.SignTop)); PDFPoint pdfpoint5 = this.pdfPageView.ConvertScreenPointToPDFPoint(new Point(item.SignLeft, item.SignTop + item.SignHeight)); absoluteX = (int)pdfpoint5.Y; absoluteY = (int)(width - (float)pdfpoint5.X); pdfImageWidth = (int)(pdfpoint4.Y - pdfpoint5.Y); pdfImageHeight = (int)(pdfpoint5.X - pdfpoint4.X); } PdfContentByte pdfContentByte = stamper.GetOverContent(j + 1); sqlBulider.Append($"insert into P_SignLocationTable (mainId, stepCode, pageNum, absoluteY, absoluteX, pdfImageWidth, pdfImageHeight, pdfAdditionalUrl) values ('{VersionCode}', '{item.StepCode}', '{item.PageNumber}', '{absoluteY}', '{absoluteX}', '{pdfImageWidth}', '{pdfImageHeight}', '{item.pdfAdditionalUrl}');\r\n"); } } stamper.Close(); } } SqlHelper.ExecuteNonQuery(sqlBulider.ToString()); } /// /// 清理签名控件 /// public void ClearSignBox() { foreach (SignBox signBox in _signBoxList) { if (signBox.ParentPicBox != null) { signBox.ParentPicBox.Dispose(); } if (signBox.ParentResizeControl != null) { signBox.ParentResizeControl.Dispose(); } } this._signBoxList.Clear(); } /// /// 添加签名控件 /// public void AddSignPicControl(string stepCode, String urlPath = "") { Bitmap image = new Bitmap(100, 50); string stepName = string.Empty; if (!String.IsNullOrEmpty(urlPath)) { using (WebClient webClient = new WebClient()) { byte[] data = webClient.DownloadData(urlPath); using (MemoryStream stream = new MemoryStream(data)) { image = new Bitmap(stream); } } } else { Graphics graphics = Graphics.FromImage(image); Pen pen = new Pen(Color.Black, 2);// graphics.DrawRectangle(pen, 0, 0, 100, 50); DataRow dataRow = StepTable.Rows.Cast().Where(n => (n["stepCode"] + "").Equals(stepCode)).FirstOrDefault(); stepName = dataRow["stepName"] + ""; graphics.DrawString(stepName, new System.Drawing.Font("微软雅黑", 26, FontStyle.Bold), Brushes.Green, new PointF(0, 0)); } PictureBox pictureBox = new PictureBox(); pictureBox.SizeMode = PictureBoxSizeMode.StretchImage; SignBox signBox = new SignBox(pdfPageView, pdfDocument.Pages[pdfPageView.PageNumber]); _signBoxList.Add(signBox); try { signBox.StepName = stepName; signBox.pdfAdditionalUrl = urlPath; signBox.StepCode = stepCode; signBox.ParentPicBox = pictureBox; signBox.PageNumber = this.CurrentPageNo + 1; if (string.IsNullOrEmpty(urlPath)) { signBox.SignHeight = 30; signBox.SignWidth = 100; } else { signBox.SignHeight = image.Height; signBox.SignWidth = image.Width; } signBox.SignTop = 0; signBox.SignLeft = 0; pictureBox.BorderStyle = BorderStyle.None; pictureBox.Image = image; //pictureBox.Height = signHeight; //pictureBox.Width = signWidth; pictureBox.Tag = signBox; pictureBox.Parent = this.pdfPageView; pictureBox.SetMove(); signBox.UpdateLocation(); ContextMenuStrip cms = new ContextMenuStrip(); cms.Items.Add("删除"); cms.Items[0].Click += new EventHandler(OnItemClick); cms.Items[0].Tag = pictureBox; pictureBox.ContextMenuStrip = cms; //pictureBox.BringToFront(); //pictureBox.Location = new Point(signLeft, signTop); //pictureBox.MouseDown += new MouseEventHandler(OnPictureBox_MouseDown); //pictureBox.MouseMove += new MouseEventHandler(OnPictureBox_MouseMove); //pictureBox.MouseUp += new MouseEventHandler(OnPictureBox_MouseUp); //pictureBox.MouseClick += new MouseEventHandler(OnPictureBox_MouseClick); //pictureBox.MouseLeave += new EventHandler(OnPictureBox_MouseLeave); } catch (Exception ex) { MessageUtil.Show(ex.Message); _signBoxList.Remove(signBox); pictureBox.Dispose(); } } public iTextSharp.text.Image ToPdfImage(SignBox signBox, int pageIndex) { float width = (float)this.pdfDocument.Pages[pageIndex].Width; iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(signBox.ParentPicBox.Image, ImageFormat.Bmp);//获取图片 PDFPageRotation rotation = this.pdfDocument.Pages[this.CurrentPageNo].Rotation; if (rotation == PDFPageRotation.Rotate0Degrees) { PDFPoint pdfpoint = this.pdfPageView.ConvertScreenPointToPDFPoint(new Point(signBox.SignLeft, signBox.SignTop)); PDFPoint pdfpoint2 = this.pdfPageView.ConvertScreenPointToPDFPoint(new Point(signBox.SignLeft + signBox.SignWidth, signBox.SignTop + signBox.SignHeight)); image.ScaleAbsolute((float)(pdfpoint2.X - pdfpoint.X), (float)(pdfpoint.Y - pdfpoint2.Y)); image.SetAbsolutePosition((float)pdfpoint.X, (float)pdfpoint2.Y); } else if (rotation == PDFPageRotation.Rotate90Degrees) { PDFPoint pdfpoint4 = this.pdfPageView.ConvertScreenPointToPDFPoint(new Point(signBox.SignLeft + signBox.SignWidth, signBox.SignTop)); PDFPoint pdfpoint5 = this.pdfPageView.ConvertScreenPointToPDFPoint(new Point(signBox.SignLeft, signBox.SignTop + signBox.SignHeight)); image.ScaleAbsolute((float)(pdfpoint4.Y - pdfpoint5.Y), (float)(pdfpoint5.X - pdfpoint4.X)); image.SetAbsolutePosition((float)pdfpoint5.Y, width - (float)pdfpoint5.X); } return image; } public SignBox ToSignBoxImage(SignBox signBox, int pageIndex, double absoluteX, double absoluteY, double pdfImageWidth, double pdfImageHeight) { float width = (float)this.pdfDocument.Pages[pageIndex].Width; PDFPageRotation rotation = this.pdfDocument.Pages[this.CurrentPageNo].Rotation; if (rotation == PDFPageRotation.Rotate0Degrees) { PDFPoint pdfpoint = new PDFPoint(absoluteX, pdfImageHeight + absoluteY); PDFPoint pdfpoint2 = new PDFPoint(pdfImageWidth + absoluteX, absoluteY); Point point = this.pdfPageView.ConvertPDFPointToScreenPoint(pdfpoint); Point point2 = this.pdfPageView.ConvertPDFPointToScreenPoint(pdfpoint2); signBox.SignLeft = point.X; signBox.SignTop = point.Y; signBox.SignWidth = point2.X - signBox.SignLeft; signBox.SignHeight = point2.Y - signBox.SignTop; } else if (rotation == PDFPageRotation.Rotate90Degrees) { PDFPoint pdfpoint4 = new PDFPoint(width - absoluteY - pdfImageHeight, pdfImageWidth + absoluteX); PDFPoint pdfpoint5 = new PDFPoint(width - absoluteY, absoluteX); Point point4 = this.pdfPageView.ConvertPDFPointToScreenPoint(pdfpoint4); Point point5 = this.pdfPageView.ConvertPDFPointToScreenPoint(pdfpoint5); signBox.SignLeft = point5.X; signBox.SignTop = point4.Y; signBox.SignWidth = point4.X - signBox.SignLeft; signBox.SignHeight = point5.Y - signBox.SignTop; } return signBox; } /// /// 关闭文档 /// public void CloseDocument() { this.pdfDocument.Close(); this.pdfDocument.Dispose(); } #endregion } }