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

相关推荐
hongtianzai1 分钟前
Laravel7.x十大核心特性解析
java·c语言·开发语言·golang·php
永远睡不够的入4 分钟前
C++庖丁解牛:深入理解多态:从虚函数表到底层实现
开发语言·c++
姚青&6 分钟前
Pytest fixture 参数化(params 参数)
开发语言·python·pytest
qq_334903158 分钟前
C++与人工智能框架
开发语言·c++·算法
2401_8914821710 分钟前
C++中的状态模式
开发语言·c++·算法
9523613 分钟前
初识多线程
java·开发语言·jvm·后端·学习·多线程
m0_7369142215 分钟前
服务器上pip install spacy卡住解决方法
开发语言·python
冰暮流星15 分钟前
javascript之回调函数
开发语言·前端·javascript
qq_4176950518 分钟前
基于C++的区块链实现
开发语言·c++·算法
电商API_1800790524719 分钟前
电商平台公开数据采集实践:基于合规接口的数据分析方案
开发语言·数据库·人工智能·数据挖掘·数据分析·网络爬虫