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路径。

相关推荐
Jay_Franklin1 小时前
SRIM通过python计算dap
开发语言·python
dly_blog1 小时前
Vue 响应式陷阱与解决方案(第19节)
前端·javascript·vue.js
Slow菜鸟1 小时前
Java基础架构设计(三)| 通用响应与异常处理(分布式应用通用方案)
java·开发语言
消失的旧时光-19432 小时前
401 自动刷新 Token 的完整架构设计(Dio 实战版)
开发语言·前端·javascript
wadesir2 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
tap.AI2 小时前
RAG系列(二)数据准备与向量索引
开发语言·人工智能
console.log('npc')2 小时前
Table,vue3在父组件调用子组件columns列的方法展示弹窗文件预览效果
前端·javascript·vue.js
阿蒙Amon2 小时前
C#每日面试题-重写和重载的区别
开发语言·c#
是一个Bug2 小时前
Java基础20道经典面试题(二)
java·开发语言
Z_Easen2 小时前
Spring 之元编程
java·开发语言