itextsharp操作pdf——插入图片

itextsharp 插入图片操作 asp.net

用于审核后签字或者其他需要对pdf进行插入图片的操作。

在pdf添加图片方法:

 protected void AddImg(string oldP, string newP, string imP, int x, int y)
    {
        using (Stream inputPdfStream = new FileStream(oldP, FileMode.Open, FileAccess.Read, FileShare.Read))
        using (Stream inputImageStream = new FileStream(imP, FileMode.Open, FileAccess.Read, FileShare.Read))
        using (Stream outputPdfStream = new FileStream(newP, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            var reader = new PdfReader(inputPdfStream);//读取原有pdf
            var stamper = new PdfStamper(reader, outputPdfStream);
            var pdfContentByte = stamper.GetOverContent(1);//获取内容
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);//获取图片
            image.ScalePercent(40);//设置图片比例
            image.SetAbsolutePosition(x, y);//设置图片的绝对位置
            pdfContentByte.AddImage(image);
            stamper.Close(); 
        }
    }

调用插入图片方法:

string newFileName = ("xxxx"+ "0.pdf");//原pdf文件名
string newFileName1 = ("xxxx"+ "1.pdf");//插入图片后pdf名
string path = ("~/xxxx/").ToString();//pdf所在文件夹路径
string destPhysicalFile = Server.MapPath(path + newFileName);
string destPhysicalFile1 = Server.MapPath(path + newFileName1);
string Img = Server.MapPath("~/xxx/" + "xxx.png");//图片文件路径
AddImg(destPhysicalFile, destPhysicalFile1, Img, 129, 574);
//删除原文件
 File.Delete(destPhysicalFile);

删除原pdf文件:

 public static void DeleteFolder(string dir)
    {
        foreach (string d in Directory.GetFileSystemEntries(dir))
        {
            if (File.Exists(d))
            {
                FileInfo fi = new FileInfo(d);
                if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)//判断文件是否只读
                    fi.Attributes = FileAttributes.Normal;//更改其只读属性
                File.Delete(d);//直接删除其中的文件  
            }
            else
            {
                DirectoryInfo d1 = new DirectoryInfo(d);
                if (d1.GetFiles().Length != 0)
                {
                    DeleteFolder(d1.FullName);//递归删除子文件夹
                }
                Directory.Delete(d);
            }
        }
    }

谢谢!

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值