通过测试,可以在页面中间加入一个倾斜45度的文字水印
实例代码如下:
- Code: Select all
//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
//Load a sample PDF document
pdf.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");
//Create a PdfTrueTypeFont object
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 50f), true);
//Set the watermark text
string text = "CONFIDENTIAL";
//Measure the text size
SizeF textSize = font.MeasureString(text);
//Calculate the values of two offset variables,
//which will be used to calculate the translation amount of the coordinate system
float offset1 = (float)(textSize.Width * System.Math.Sqrt(2) / 4);
float offset2 = (float)(textSize.Height * System.Math.Sqrt(2) / 4);
//Traverse all the pages in the document
foreach (PdfPageBase page in pdf.Pages)
{
//Set the page transparency
page.Canvas.SetTransparency(0.8f);
//Translate the coordinate system by specified coordinates
page.Canvas.TranslateTransform(page.Canvas.Size.Width / 2 - offset1 - offset2, page.Canvas.Size.Height / 2 + offset1 - offset2);
//Rotate the coordinate system 45 degrees counterclockwise
page.Canvas.RotateTransform(-45);
//Draw watermark text on the page
page.Canvas.DrawString(text, font, PdfBrushes.DarkGray, 0, 0);
}
//Save the changes to another file
pdf.SaveToFile("TextWatermark.pdf");
但是对代码看的不是很明白
位置似乎都是通过计算来实现的
没有类似于HorizontalAlignment.Center、VerticalAlignment.Top这种直接可调用的位置参数
如果我想在页面的左上角、顶部中间、右上角、正中间、左下角、底部中间、右下角7个位置同时加入文字水印
代码应该如何写呢?
谢谢!