c# – PDFsharp水印

我正在创建一个应用程序,在用户选择的PDF上创建水印,我似乎无法在所选PDF上显示水印,但我也没有错误.任何帮助,将不胜感激.

我使用的是PDFsharp版本1.50.4000

public void WaterMarkPDF(string sourceFileName)
    {
        try
        {
            string watermark = "watermark";
            int emSize = 100;
            string file ="test.pdf";

            File.Copy(sourceFileName, file, true);
            File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly);

            // Take in pdf from the form
            PdfDocument document = PdfReader.Open(file);

            // change the version cause sometimes newer versions break it
            if (document.Version < 14)
                document.Version = 14;

            XFont font = new XFont("Times New Roman", emSize, XFontStyle.BoldItalic);
            for (int idx = 0; idx < document.Pages.Count; idx++)
            {
                var page = document.Pages[idx];

                // Get an XGraphics object for drawing beneath the existing content.
                var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);

                // Get the size (in points) of the text.
                var size = gfx.MeasureString(watermark, font);

                // Define a rotation transformation at the center of the page.
                gfx.TranslateTransform(page.Width / 2, page.Height / 2);
                gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
                gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);

                // Create a string format.
                var format = new XStringFormat();
                format.Alignment = XStringAlignment.Near;
                format.LineAlignment = XLineAlignment.Near;

                // Create a dimmed red brush.
                XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));

                // Draw the string.
                gfx.DrawString(watermark, font, brush,
                    new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                    format);
                // Save the document...
                 document.Save(file);

                // ...and start a viewer.
                Process.Start(file);
            }
        }
        catch (Exception e)
        {
            throw e;
        }

    }

解决方法:

也许尝试XGraphicsPdfPageOptions.Append以及XGraphicsPdfPageOptions.Prepend.

调用document.Save和Process.Startoutside for for循环.

更新:说明:使用XGraphicsPdfPageOptions.Prepend,水印将绘制在原始PDF页面下方.大多数PDF文件由透明背景上的黑色文本组成,水印将在那里可见(您可以通过在Adobe Reader中激活透明网格来检查).对于具有纯背景的PDF页面(例如图像,具有背景颜色的表格,……),水印将不可见.

PDFsharp源代码包含一个Watermark示例:
http://pdfsharp.net/wiki/Watermark-sample.ashx
有两种变体可在现有PDF页面的顶部添加半透明文本.这些变体也适用于没有透明度的PDF页面.

上一篇:SELECT list is not in GROUP BY clause and contains nonaggregated


下一篇:c# – 更改PDF – 文本重新定位