首页 > 其他分享 >.net通过iText操作pdf文件实现查找关键字签字盖章(新)

.net通过iText操作pdf文件实现查找关键字签字盖章(新)

时间:2022-09-05 11:37:00浏览次数:71  
标签:int float new iText imageDatum pdf using net

因为上一篇文章确认有问题,后面复测发现bug,现在重新写了,是基于iText写的,复测多次,基本上没问题了。其他需要使用者自行扩展了

直接贴代码吧。

  1 using iText.IO.Image;
  2 using iText.Kernel.Geom;
  3 using iText.Kernel.Pdf;
  4 using iText.Kernel.Pdf.Canvas;
  5 using iText.Kernel.Pdf.Canvas.Parser;
  6 using iText.Kernel.Pdf.Canvas.Parser.Listener;
  7 using iText.Layout;
  8 using iText.Layout.Element;
  9 using South.Tools.Logger;
 10 using System;
 11 using System.Collections.Generic;
 12 using System.IO;
 13 using System.Linq;
 14 
 15 namespace South.Tools.Helper
 16 {
 17     public class SealSignHelper
 18     {
 19         private static int ReSizeMaxWidth = 45;
 20 
 21         private static int ReSizeMaxHeight = 45;
 22 
 23         /// <summary>
 24         /// 
 25         /// </summary>
 26         /// <param name="bytePdf">pdf文件</param>
 27         /// <param name="SignImgBase64">签字base64图片</param>
 28         /// <param name="SignKeyWord">关键字</param>
 29         /// <param name="StartPageIndex">自定义开始页</param>
 30         /// <param name="EndPageIndex">自定义结束页</param>
 31         /// <returns></returns>
 32         public static Tuple<bool, string, byte[]> SignBase64Img(byte[] bytePdf, string SignImgBase64, string SignKeyWord, int StartPageIndex = 0, int EndPageIndex = 0)
 33         {
 34             byte[] array;
 35             Tuple<bool, string, byte[]> tuple;
 36             int num = 0;
 37             try
 38             {
 39                 using (MemoryStream memoryStream = new MemoryStream())
 40                 {
 41                     using (PdfReader pdfReader = new PdfReader(new MemoryStream(bytePdf)))
 42                     {
 43                         using (PdfDocument pdfDocument = new PdfDocument(pdfReader, new PdfWriter(memoryStream)))
 44                         {
 45                             //获取总页数
 46                             int numberOfPages = pdfDocument.GetNumberOfPages();
 47                             int startPageIndex = 1;
 48                             if (StartPageIndex > 0)
 49                             {
 50                                 //已知关字键所在页码,自定义开始页
 51                                 startPageIndex = StartPageIndex;
 52                             }                            
 53                             if (EndPageIndex > startPageIndex && EndPageIndex <= numberOfPages)
 54                             {
 55                                 //已知关字键所在页码,自定义结束页
 56                                 numberOfPages = EndPageIndex;
 57                             }
 58                             //遍历pdf文档
 59                             for (int i = startPageIndex; i <= numberOfPages; i++)
 60                             {
 61                                 //获取页对象
 62                                 PdfPage page = pdfDocument.GetPage(i);
 63                                 PdfCanvas pdfCanva = new PdfCanvas(page);
 64                                 //创建关键字坐标对象
 65                                 RegexBasedLocationExtractionStrategy regexBasedLocationExtractionStrategy = new RegexBasedLocationExtractionStrategy(SignKeyWord);
 66                                 (new PdfCanvasProcessor(regexBasedLocationExtractionStrategy)).ProcessPageContent(page);
 67                                 //获取当前页所有查询到的关键字坐标
 68                                 List<IPdfTextLocation> list = regexBasedLocationExtractionStrategy.GetResultantLocations().ToList<IPdfTextLocation>();
 69                                 if (list.Count > 0)
 70                                 {
 71                                     num++;
 72                                     //多个关键字,默认取第一个
 73                                     IPdfTextLocation item = list[0];
 74                                     //获取关键字左上角开始坐标
 75                                     float left = item.GetRectangle().GetLeft();
 76                                     float top = item.GetRectangle().GetTop();
 77                                     //获取关键字右下角结束坐标
 78                                     float right = item.GetRectangle().GetRight();
 79                                     float bottom = item.GetRectangle().GetBottom();
 80                                     //计算得到关键字的中心点
 81                                     float x = (right - left) / 2f + left;
 82                                     float y = (top - bottom) / 2f + bottom;
 83                                     //Convert.FromBase64String(SignImgBase64);
 84                                     //等比调整签字图片大小
 85                                     ImageData imageDatum = ImageDataFactory.Create(Convert.FromBase64String(SignImgBase64));
 86                                     float reSizeMaxWidth = 0f;
 87                                     float height = 0f;
 88                                     if (imageDatum.GetWidth() > imageDatum.GetHeight() && imageDatum.GetWidth() > (float)SealSignHelper.ReSizeMaxWidth)
 89                                     {
 90                                         reSizeMaxWidth = (float)SealSignHelper.ReSizeMaxWidth;
 91                                         height = reSizeMaxWidth * imageDatum.GetHeight() / imageDatum.GetWidth();
 92                                     }
 93                                     else if (imageDatum.GetHeight() > imageDatum.GetWidth() && imageDatum.GetHeight() > (float)SealSignHelper.ReSizeMaxHeight)
 94                                     {
 95                                         height = (float)SealSignHelper.ReSizeMaxHeight;
 96                                         reSizeMaxWidth = height * imageDatum.GetWidth() / imageDatum.GetHeight();
 97                                     }
 98                                     //签字图片设置背景透明
 99                                     imageDatum.SetTransparency(new int[] { 255, 255, 255, 255, 255, 255 });
100                                     Image image = new Image(imageDatum);
101                                     image.ScaleAbsolute(reSizeMaxWidth, height);
102                                     Canvas canva = new Canvas(pdfCanva, new Rectangle(x - reSizeMaxWidth / 2f, y - height / 2f, reSizeMaxWidth, height));
103                                     //盖上关键字上面
104                                     canva.Add(image);
105                                     canva.Close();
106                                 }
107                             }
108                         }
109                     }
110                     array = memoryStream.ToArray();
111                 }
112                 tuple = (num != 0 ? new Tuple<bool, string, byte[]>(true, "签字成功", array) : new Tuple<bool, string, byte[]>(false, "未找到签字关键字", null));
113             }
114             catch (Exception exception1)
115             {
116                 Exception exception = exception1;
117                 SaveLogUtil.Error(exception.Message, exception, "SignPicPDF");
118                 tuple = new Tuple<bool, string, byte[]>(false, "签字异常", null);
119             }
120             return tuple;
121         }
122     }
123 }

 

标签:int,float,new,iText,imageDatum,pdf,using,net
From: https://www.cnblogs.com/abcde102978/p/16657502.html

相关文章

  • ASP.NET总结C#中7种获取当前路径的方法
    1.System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName -获取模块的完整路径。 2.System.Environment.CurrentDirectory -获取和设置当前目录(该进程......
  • Asp.net Mvc 区域路由默认设置
    publicclassRouteConfig{publicstaticvoidRegisterRoutes(RouteCollectionroutes){routes.IgnoreRoute("{resource}.axd/......
  • Kubernetes
    服务部署方式发展传统部署直接将应用程序部署在物理机上优点:简单,不需要其它技术的参与缺点:不能为应用程序定义资源使用边界,很难合理地分配计算资源,而且程序之间容......
  • .NET 6 + 健康检查:实现监控仪表板
    .NET6+健康检查:实现监控仪表板在本文开头的图片中,我们有一个监控仪表板示例(此处列出的服务状态不断更新),一个使用创建的实现.NET6,ASP.NET核心和项目野猪.服务......
  • TransUNet——彻底改变传统的图像分割
    TransUNet——彻底改变传统的图像分割通过结合CNN和Transformer对U-Net进行改造,以在图像分割任务上实现SOTA结果。目录·直觉·TransUNet∘下采样(编码......
  • .Net Core&RabbitMQ优先级队列
    优先级队列消息除了有生命周期长短,也有紧急与非紧急之分,承载了具有优先级消息的队列则为优先级队列。队列优先级设置为消息设置优先级前,队列需要先具备优先级的能力,队......
  • Docker进阶与实战 pdf
    高清扫描版下载链接:https://pan.baidu.com/s/1mmNcrW3WxxHqYoTBv3777g点击这里获取提取码Docker进阶与实战本书由一个真正钻研容器技术的团队写作,他们不仅仅是在使用Docke......
  • Docker容器:利用Kubernetes、Flannel、Cockpit和Atomic构建和部署 pdf
    高清扫描版下载链接:https://pan.baidu.com/s/1bGR-iSE5_jHNvP1QWHKs3g点击这里获取提取码Linux系统或云环境上运行Docker的实用指南!无论是在笔记本上还是在远程云上,Docke......
  • Kubernetes零基础快速入门 pdf
    高清扫描版下载链接:https://pan.baidu.com/s/1ngjbxbqQnSs4K4xd5nzt5Q点击这里获取提取码Kubernetes为容器化的应用提供了资源调度、部署、运行、服务发现、扩容和缩容等......
  • Docker基础与实战 pdf
    高清扫描版下载链接:https://pan.baidu.com/s/1OXDK4BXPRg29N4_02Fm-SQ点击这里获取提取码Docker基础与实战本书围绕已应用于多个项目的Docker技术展开讲解,前半部分以浅显......