最近接到一个需求是要给PDF加盖印章的在查找相关帖子的时候都在推荐使用Spire.Pdf.dll,但是这个是有水印的
找了半天终于找到应该使用ITextSharp.dll,这个是没有水印的
但是下载都是要积分,对于我这种没有积分的就很惨
网盘地址
链接:https://pan.baidu.com/s/1FHoQ0n-SET8stllU66eSuw
提取码:L886
网盘地址
这个是印章在PDF文字的下面
如果印章想在PDF上面可以设置(但是会遮挡文字)
public void SetPdfBackground(string pdfPath, string imgUrl, string saveUrl)
{
//创建一个新的PDF
FileStream stream = new FileStream(saveUrl, FileMode.Create, FileAccess.ReadWrite);
PdfReader reader = new PdfReader(pdfPath);
//读取PDF
PdfStamper stamper = new PdfStamper(reader, stream);
var page = stamper.GetImportedPage(reader, 1);
//读取印章
System.Drawing.Image image = System.Drawing.Image.FromFile(imgUrl);
var img = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Png);
//img.ScalePercent(20);//设置印章与原图比例
//自定义方法找到最后一页最后一个字的Y轴坐标
float LastPageTextY = YLine(pdfPath);
//默认最后一页章所在的位置
float LastPageImgY = page.Height - LastPageTextY;
float pageWidth = page.Width;
float pageHeight = page.Height;
//如果最后一页文本字符的位置比印章图片Height小,默认PDF减去印章Height
//1距离
if (LastPageTextY < img.Height)
{
LastPageImgY = pageHeight - img.Height;
}
else if (LastPageTextY >= img.Height)
{
LastPageImgY = pageHeight - LastPageTextY;
}
//读取PDF页数,并循环到每一页盖章
int totalPage = reader.NumberOfPages;
for (int current = 1; current <= totalPage; current++)
{
var canvas = stamper.GetUnderContent(current);
if (current < totalPage)
{
img.SetAbsolutePosition(pageWidth - img.Width, 0);//设置印章的绝对位置
}
else
{
img.SetAbsolutePosition(pageWidth - img.Width, LastPageImgY);//设置印章的绝对位置
}
canvas.AddImage(img);
}
stamper.Close();
reader.Close();
//修改文件名称,替换掉之前的文件
//File.Move("原文件","现文件");
}
找到最后一页应该盖章的位置,使用的是Spire.Pdf.dll
private float YLine(string pdfPath)
{
//用Spire.Pdf.dll确定最后一页最后一个文本字符所在Y轴的坐标
Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
doc.LoadFromFile(pdfPath);
//最后一页PDF页数
int PageNo = doc.Pages.Count - 1;
Spire.Pdf.PdfPageBase page = doc.Pages[PageNo];
//将最后一页的文本字符全部读取出来
StringBuilder PDFText = new StringBuilder();
PDFText.Append(page.ExtractText());
string content = PDFText.ToString().Trim();
//将特殊字符去掉
content = System.Text.RegularExpressions.Regex.Replace(content, @"\s", "");
//将空白字符去掉
content = System.Text.RegularExpressions.Regex.Replace(content, " ", "");
//倒叙循环将最后一个字符找出来
//循环次数content.Length - 6 将页脚第?页/共?页排除
char LastFout = 'A';
for (int i = content.Length - 1; i >= content.Length - 7; i--)
{
LastFout = content[i];
}
//查找最后一个字符出现的所有坐标
Spire.Pdf.General.Find.PdfTextFind[] result = page.FindText(LastFout.ToString()).Finds;
//方法一
//获取最后一个坐标
//PointF pf = result[result.Length - 1].Position;
//float value = pf.Y;
//方法二
//将所有坐标拿出来,排序
List<float> resultY = new List<float>();
for (int i = 0; i < result.Length; i++)
{
resultY.Add(result[i].Position.Y);
}
resultY.Sort();
float value = resultY[resultY.Count - 1];
return value;
}
有什么建议欢迎指出,谢谢