在代码中设置印章的位置和大小

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);
                }
            }
        }
    }
}
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

幽兰的天空

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值