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