csharp
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public void AddWatermarkToPDF(string inputPath, string outputPath, string watermarkText)
{
// 创建文档对象
Document document = new Document();
// 创建PdfWriter对象
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create));
// 打开文档
document.Open();
// 读取原始PDF文件
PdfReader reader = new PdfReader(inputPath);
// 获取页面数量
int pageCount = reader.NumberOfPages;
// 添加水印到每个页面
for (int i = 1; i <= pageCount; i++)
{
// 获取页面尺寸
Rectangle pageSize = reader.GetPageSize(i);
// 创建PdfContentByte对象
PdfContentByte content = writer.DirectContent;
// 开始写入水印
content.BeginText();
// 设置字体
content.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);
// 设置文字颜色
content.SetColorFill(BaseColor.LIGHT_GRAY);
// 设置文字旋转角度
content.SetTextMatrix(30, 30);
// 添加水印文字
content.ShowTextAligned(Element.ALIGN_CENTER, watermarkText, pageSize.Width / 2, pageSize.Height / 2, 45);
// 结束写入水印
content.EndText();
}
// 添加原始PDF内容到新的PDF文档
for (int i = 1; i <= pageCount; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
writer.DirectContent.AddTemplate(page, 0, 0);
}
// 关闭文档
document.Close();
// 关闭PdfReader对象
reader.Close();
}