首先Nuget安装FreeSpire.PDF,添加引用。下面具体代码
public void addPicture()
{
//注意:PointF的Y坐标取值离底部边界100px 选中出现红框,红款据底部80px;
//PointF由左下角开始,距离底部100px位置
//pdf比例调节成75%为真实尺寸,在我这里
PdfDocument doc = new PdfDocument();
doc.LoadFromFile("D:\\1.pdf");
//开始处理分页
for (int i = 0; i < doc.Pages.Count; i++)
{
//打印当前页面的宽高
Console.WriteLine(doc.Pages[i].Size.Width + "====" + doc.Pages[i].Size.Height);
//得到当前页
PdfPageBase page = doc.Pages[i];
//新建一个PDF文件的橡皮图章对象,指定其注释的范围和大小 距离 大小
//首页和中页位置固定,尾页查找关键字盖章
PdfRubberStampAnnotation loStamp = null;
if (i == 0)
{
loStamp = new PdfRubberStampAnnotation(new RectangleF(new PointF(400, 100), new SizeF(80, 80)));
}
else if (i == doc.Pages.Count - 1)
{
//得到根据关键字得到的结果集
PdfTextFind result = page.FindText("合计").Finds[0];
//计算坐标,因为PointF(0,0)距离底部还有100px距离,且由底部开始
//所以减去100同时减去顶部到关键字的距离
float pointY = page.Size.Height - result.Position.Y - 100;
loStamp = new PdfRubberStampAnnotation(new RectangleF(new PointF(result.Position.X, pointY), new SizeF(80, 80)));
}
else
{
loStamp = new PdfRubberStampAnnotation(new RectangleF(new PointF(675, 0), new SizeF(80, 80)));
}
//表示注释的外观
PdfAppearance loApprearance = new PdfAppearance(loStamp);
//加载用作印章的图片
PdfImage image = PdfImage.FromFile("D:\\1.jpg");
//新建一个PDF模板,并在模板里绘制图片。设置图片的原始比例
PdfTemplate template = new PdfTemplate(300, 300);
//开始画图,坐标位置要设置成0
template.Graphics.DrawImage(image, 0, 0);
//设置注释的一般状态
loApprearance.Normal = template;
//获取或设置注释的外观
loStamp.Appearance = loApprearance;
//将此注释(图章)加入当前页的字段中
page.AnnotationsWidget.Add(loStamp);
}
string output = "D:\\temp.pdf";
doc.SaveToFile(output);
doc.Dispose();
}