给一个PDF的所有页加上文字水印,效果如下
新建一个项目,直接上代码了:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.IO;
using System.Windows.Forms;
namespace _111
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string p = Application.StartupPath + "\";
string r = AddTextShuiYin(p + "test.pdf", p + "test1.pdf", 0.5f, "HELLO");
MessageBox.Show(r);
}
public static string AddTextShuiYin(string PdfPath, string OutPdfPath, float toumingdu, string ShuiYinText)
{
if (File.Exists(OutPdfPath))
{
File.Delete(OutPdfPath);
}
PdfReader reader = null;
PdfStamper ShuiYinOBJ = null;
PdfContentByte ShuiYinQu;
try
{
reader = new PdfReader(PdfPath);
//得到原PDF的页数和宽高
PDFATT att = new PDFATT(PdfPath);
int n = att.PageCount();
float w = att.Width();
float h = att.Height();
//从第0页开始
int i = 0;
ShuiYinOBJ = new PdfStamper(reader, new FileStream(OutPdfPath, FileMode.Create));
PdfGState gs = new PdfGState();
//设置透明度
gs.FillOpacity = toumingdu;
BaseFont font = BaseFont.CreateFont(@"C:WINDOWSFontsSIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
while (i < n)
{
i++;
//在正文内容下加水印,不挡内容
ShuiYinQu = ShuiYinOBJ.GetUnderContent(i);
//在正文内容上加水印,挡内容
//ShuiYinQu = ShuiYinOBJ.GetOverContent(i);
ShuiYinQu.SetGState(gs);
for (float left = 0; left < w; left += 200)
{
for (float top = 0; top < h; top += 100)
{
//透明度
gs.FillOpacity = toumingdu;
ShuiYinQu.SetGState(gs);
//开始写入文本
ShuiYinQu.BeginText();
ShuiYinQu.SetColorFill(iTextSharp.text.Color.RED);
ShuiYinQu.SetFontAndSize(font, 180);
ShuiYinQu.SetTextMatrix(2, 2);
ShuiYinQu.ShowTextAligned(Element.ALIGN_CENTER, ShuiYinText, w / 2, h / 2, 30);
//ShuiYinQu.AddImage(im);
}
}
ShuiYinQu.EndText();
}
ShuiYinOBJ.Close();
reader.Close();
return "OK";
}
catch (Exception ex)
{
return ex.ToString();
}
}
class PDFATT
{
PdfReader reader;
public PDFATT(string iPdfFilePath)
{
reader = new PdfReader(iPdfFilePath);
}
public int PageCount()
{
return reader.NumberOfPages;
}
public float Width()
{
return reader.GetPageSize(1).Width;
}
public float Height()
{
return reader.GetPageSize(1).Height;
}
}
}
}
调用方法说明
string p = Application.StartupPath + "\";
//参数:源文件地址,新文件地址,透明度(float型),水印文本
string r = AddTextShuiYin(p + "test.pdf", p + "test1.pdf", 0.5f, "HELLO");
MessageBox.Show(r);
水印位置
//这里我是w/2和h/2,大概在页中间,当然这里我为了演示没有精确计算,
//30 是旋转角度
ShuiYinQu.ShowTextAligned(Element.ALIGN_CENTER, ShuiYinText, w / 2, h / 2, 30);