这听起来像是一个非常简单的问题,但我似乎无法弄清楚。
我想在我的PDF顶部放一个水印,并希望它从左下角开始,到右上角结束。我的开始的问题是我找不到左下角。我感觉到,根据PDF文档,我打开了0,0坐标更改。
这是我到目前为止所得到的:
static string fontname = "Calibri";
public void WaterMarkPDF3(string sourceFileName)
{
PdfDocument doc = PdfReader.Open(sourceFileName, PdfDocumentOpenMode.Modify);
foreach (PdfPage page in doc.Pages)
{
//First calculate the cross angle from bottom left to top right
double Angle= -Math.Atan(page.Height / page.Width) * 180 / Math.PI;
//here I calculate how long the diagonal is so that my string can have the same length
double watermarkWidth = page.Height / Math.Sin(Angle);
XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
double emSize = 300;
XFont font = new XFont(fontname, emSize, XFontStyle.Bold);
XSize size = gfx.MeasureString("Teststring", font);
gfx.TranslateTransform(page.Width / 2, page.Height / 2);
gfx.RotateTransform(Angle);
gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);
XGraphicsPath path = new XGraphicsPath();
path.AddString("Teststring", font.FontFamily, XFontStyle.Bold, emSize,
new XPoint(0, page.Height), XStringFormats.Default);
// add to color to the outline and filling
XPen pen = new XPen(XColor.FromArgb(75, 0, 152, 163), 2);
XBrush brush = new XSolidBrush(XColor.FromArgb(50, 0, 152, 163));
gfx.DrawPath(pen, brush, path);
}
doc.Save(sourceFileName);
}
根据我的理解,0,0是左上角。通常,如果我从new XPoint(0, page.Height)
开始水印,我希望它位于左下角。就像您在所附图片中看到的那样,它位于看起来“随机”的位置。
水印示例可以在这里找到:https://github.com/empira/PDFsharp-samples/blob/master/samples/core/Watermark/Program.cs
示例与您的代码之间的一个区别是XStringFormat
。这定义了字符串如何相对于给定点对齐。该示例只是将字符串的中心与页面的中心对齐。
您在注释中的“问题”:emSize
是字体的磅数-72磅是1英寸。您的300点是105.833毫米或4.167英寸。
您的代码段围绕页面中心旋转。我认为这也会更改页面角的坐标。如果要从页面的一角开始,则绕页面的一角旋转可能会更简单。该示例在页面中心绘制水印,这是大多数人想要的。