C# 使用 itextsharp,版本 5.5.12.0
一、添加水印
参数inContent可以是byte,也可以是string类型文本路径。
using System;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
/// <summary>
/// 添加文本水印
/// </summary>
/// <param name="Content">文本字节流</param>
/// <param name="shuiyin">想要添加的水印</param>
/// <returns></returns>
public static byte[] AddTextWatermark(byte[] Content, string shuiyin)
{
using (PdfReader reader = new PdfReader(Content))
{
using (MemoryStream outputStream = new MemoryStream())
{
// 加完水印的文件
PdfStamper pdfStamper = new PdfStamper(reader, outputStream);
int pageNumber = reader.NumberOfPages + 1;
PdfContentByte content;
//创建字体
BaseFont font = BaseFont.CreateFont(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"STKAITI.TTF"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
// 设置水印透明度
PdfGState gs = new PdfGState();
// 设置填充字体不透明度为0.4f
gs.FillOpacity = (0.2f);
int textH = 10;
int textW = 100;
iTextSharp.text.Rectangle pageRect;
// 循环对每页插入水印
for (int i = 1; i < pageNumber; i++)
{
pageRect = reader.GetPageSizeWithRotation(i);
// 水印在之前文本下
content = pdfStamper