PDF文件上增加电子签章

cs 复制代码
 try
 {
     using (PdfReader pdfReader = new PdfReader(sourcePdfPath))
     using (PdfWriter pdfWriter = new PdfWriter(destinationPdfPath))
     using (PdfDocument pdfDoc = new PdfDocument(pdfReader, pdfWriter))
     {
         var page = pdfDoc.GetFirstPage();
         ImageData imageData = ImageDataFactory.Create(stampImagePath);
         var imgWidth = imageData.GetWidth();
         var imgHeight = imageData.GetHeight();

         // 获取页面高度  
         var pageHeight = page.GetPageSize().GetHeight();

         // 获取页面宽度  
         var pageWidth = page.GetPageSize().GetWidth();

         // 设置图像的位置  
         float x = pageWidth - 200; // x 坐标
         float y = 0; // y 坐标  
         // 创建 PdfCanvas  
         var canvas = new PdfCanvas(page);
         canvas.SaveState();
         if (pageWidth > pageHeight)
         {
             // 上下翻转图像  
             canvas.ConcatMatrix(1, 0, 0, -1, x , y + pageHeight); // y轴翻转  
         }
        
         // 创建 Image 对象  
         var image = new Image(imageData);
         image.SetFixedPosition(0, 0);
         image.ScaleToFit(imgWidth * 20 / 100, imgHeight * 20 / 100); // 可选,具体根据需要调整  

         // 嵌入图像到当前页面  
         var document = new Document(pdfDoc);
         document.Add(image);

         document.Close(); // 保证文档被正确关闭  

         MessageBox.Show("已签名成功!!");
     }
 }
 catch (iText.Kernel.Exceptions.PdfException ex)
 {
     Console.WriteLine($"PdfException: {ex.Message}");
 }
 catch (Exception ex)
 {
     Console.WriteLine($"Exception: {ex.Message}");
 }

stampImagePath为图片的路径,sourcePdfPath为PDF的路径,destinationPdfPath为目标PDF路径。

相关推荐
内网渗透9 分钟前
Python 虚拟环境管理:venv 与 conda 的选择与配置
开发语言·python·conda·虚拟环境·venv
兜小糖的小秃毛15 分钟前
两段文本比对,高亮出差异部分
linux·前端·javascript
佛系菜狗23 分钟前
element-ui、element-plus表单resetFields()无效的坑
前端·javascript·vue.js
每次的天空1 小时前
kotlin与MVVM结合使用总结(三)
开发语言·microsoft·kotlin
keep intensify1 小时前
通讯录完善版本(详细讲解+源码)
c语言·开发语言·数据结构·算法
ephemerals__1 小时前
【c++11】c++11新特性(下)(可变参数模板、default和delete、容器新设定、包装器)
开发语言·c++
先生沉默先1 小时前
c#接口_抽象类_多态学习
开发语言·学习·c#
沐土Arvin2 小时前
理解npm的工作原理:优化你的项目依赖管理流程
开发语言·前端·javascript·设计模式·npm·node.js
IT瘾君2 小时前
Java基础:认识注解,模拟junit框架
java·开发语言·junit
爱上解放晚晚2 小时前
QT 的.pro 转 vsproject 工程
开发语言·qt