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

相关推荐
帅那个帅18 分钟前
PHP里面的抽象类和接口类
开发语言·php
咖啡の猫6 小时前
Python字典推导式
开发语言·python
leiming67 小时前
C++ vector容器
开发语言·c++·算法
SystickInt7 小时前
C语言 strcpy和memcpy 异同/区别
c语言·开发语言
CS Beginner7 小时前
【C语言】windows下编译mingw版本的glew库
c语言·开发语言·windows
FJW0208147 小时前
Python_work4
开发语言·python
多看书少吃饭8 小时前
从Vue到Nuxt.js
前端·javascript·vue.js
大学生资源网8 小时前
java毕业设计之儿童福利院管理系统的设计与实现(源码+)
java·开发语言·spring boot·mysql·毕业设计·源码·课程设计
JasmineWr8 小时前
JVM栈空间的使用和优化
java·开发语言
前端一小卒8 小时前
从 v5 到 v6:这次 Ant Design 升级真的香
前端·javascript