在文档电子化管理中会遇到 对PDF进行水印化的需求,如图
private string AddWaterMark(Stream stream,string waterName) {
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
var tempPath = $"wwwroot/tempFile_{Guid.NewGuid()}.pdf";
try
{
pdfReader = new PdfReader(stream);
pdfStamper = new PdfStamper(pdfReader, new FileStream(tempPath, FileMode.Create));
int total = pdfReader.NumberOfPages + 1;
iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
PdfContentByte content;
// 中文适配
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
PdfGState gs = new PdfGState();
for (int i = 1; i < total; i++)
{
content = pdfStamper.GetOverContent(i);//在内容上方加水印
//content = pdfStamper.GetUnderContent(i);//在内容下方加水印
//透明度
gs.FillOpacity = 0.4f;
content.SetGState(gs);
//content.SetGrayFill(0.3f);
//开始写入文本
content.BeginText();
content.SetColorFill(BaseColor.GRAY);
content.SetFontAndSize(font, 20);
content.SetTextMatrix(0, 0);
content.ShowTextAligned(Element.ALIGN_CENTER, waterName, width - 120, height - 120, -45);
if (width > 240 && height > 240)
{
content.ShowTextAligned(Element.ALIGN_CENTER, waterName, width - 240, height - 240, -45);
}
if (width > 360 && height > 360)
{
content.ShowTextAligned(Element.ALIGN_CENTER, waterName, width - 360, height - 360, -45);
}
if (width > 480 && height > 480)
{
content.ShowTextAligned(Element.ALIGN_CENTER, waterName, width - 480, height - 480, -45);
}
//content.SetColorFill(BaseColor.BLACK);
//content.SetFontAndSize(font, 8);
//content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, 0, 0, 0);
content.EndText();
}
if (pdfStamper != null)
pdfStamper.Close();
if (pdfReader != null)
pdfReader.Close();
}
catch (Exception ex)
{
return "";
}
return tempPath;
}