using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.IO;
class Program
{
static void Main()
{
try
{
// 输入 PDF 文件路径
string inputPdfPath = @"path/to/your/input.pdf";
// 印章图片路径
string sealImagePath = @"path/to/your/seal.png";
// 输出 PDF 文件路径
string outputPdfPath = @"path/to/your/output.pdf";
AddRidingSealToPdf(inputPdfPath, sealImagePath, outputPdfPath);
Console.WriteLine("骑缝章添加成功!");
}
catch (Exception ex)
{
Console.WriteLine("发生错误: " + ex.Message);
}
}
static void AddRidingSealToPdf(string inputPdfPath, string sealImagePath, string outputPdfPath)
{
using (PdfReader reader = new PdfReader(inputPdfPath))
{
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(outputPdfPath, FileMode.Create)))
{
int pageCount = reader.NumberOfPages;
// 加载印章图片
Image sealImage = Image.GetInstance(sealImagePath);
// 设置印章的整体宽度和高度,这里可以根据需要调整大小
float desiredSealWidth = 300;
float desiredSealHeight = 100;
// 计算每一页显示的印章宽度
float sealWidth = desiredSealWidth / pageCount;
float sealHeight = desiredSealHeight;
for (int i = 1; i <= pageCount; i++)
{
PdfContentByte contentByte = stamper.GetOverContent(i);
// 计算当前页要显示的印章部分的起始位置
float startX = (i - 1) * sealWidth;
// 设置印章的位置,这里设置印章在页面底部居中
float xPosition = (reader.GetPageSize(i).Width - sealWidth) / 2;
float yPosition = 20; // 距离页面底部的距离
// 创建一个矩形来裁剪印章图片
Rectangle rect = new Rectangle(startX, 0, startX + sealWidth, sealHeight);
sealImage.SetAbsolutePosition(xPosition, yPosition);
sealImage.ScaleAbsolute(sealWidth, sealHeight);
// 裁剪印章图片
sealImage.Alignment = Image.UNDERLYING;
sealImage.Crop = rect;
contentByte.AddImage(sealImage);
}
}
}
}
}