簡體   English   中英

PDFsharp水印

[英]PDFsharp Watermark

我正在制作一個在用戶選擇的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

for循環外調用document.SaveProcess.Start

更新:說明:使用XGraphicsPdfPageOptions.Prepend ,水印被繪制在原始PDF頁面下方。 大多數PDF文件由透明背景上的黑色文本組成,並且水印將在那里可見(您可以通過在Adobe Reader中激活“透明網格”進行檢查)。 對於具有純色背景的PDF頁面(例如,圖像,具有背景色的表格...),水印將不可見。

PDFsharp源代碼包括一個水印示例:
http://pdfsharp.net/wiki/Watermark-sample.ashx
有兩種變體可以在現有PDF頁面頂部添加半透明文本。 這些變體也適用於不透明的PDF頁面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM