为奇数/偶数页和首页的 Word 文档添加水印

Adding Watermark to Word Document for Odd/Even and First Pages

提问人:Tim Kempster 提问时间:6/27/2023 最后编辑:Tim Kempster 更新时间:6/27/2023 访问量:61

问:

我已经成功地编写了一些代码来为 word 文档页面添加水印。这遵循一个标准表单,该表单将 Shape 添加到每个部分的标题中。

当您在标题中选择奇数/偶数页和不同的首页时,会出现问题

enter image description here

在这种情况下,代码会失败,所有水印最终都会出现在 secon 的最后一页上,或者类似地出错。

我知道您可以使用 WdHeaderFooterIndex.wdHeaderFooterPrimary、WdHeaderFooterIndex.wdHeaderFooterEvenPages、WdHeaderFooterIndex.wdHeaderFooterFirstPage 选择标题来选择该部分。Headers.Item() 项,但即使我使用这些,它也不起作用。以下是我的代码:

`

    private static void CutPageHeader(Section section, HeaderFooter hdr)
    {
        hdr.Range.Cut();
    }
    private static void PastePageHeader(Section section, HeaderFooter hdr)
    {
        Word.Range headerRange = hdr.Range;
        headerRange.Collapse(Word.WdCollapseDirection.wdCollapseStart);
        headerRange.Paste();
        headerRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
        headerRange.Delete(Word.WdUnits.wdCharacter, -1); //deletes paste-generated extra carriage return (Word ignores this when extra carriage return does not exist)

    }


    public static bool InsertWatermark(string watermarkText, int opacity, int orientation, int fontSize, int YOffset, int XOffset, bool firstPageOnly, bool centerOnPage)
    {
        if (string.IsNullOrEmpty(watermarkText)) return true;

        if (wordApp == null) wordApp = (Application)TraySelectorOne.AddinModule.CurrentInstance.WordApp;
        doc = wordApp.ActiveDocument;

        int sectionCount = 1;
        foreach (Section section in doc.Sections)
        {

            foreach (HeaderFooter hdr in section.Headers)
            {
                Word.Shape shw;
                CutPageHeader(section, hdr);

                shw = InsertWatermarkInHeader(hdr, section, watermarkText,
                        opacity, orientation, fontSize, YOffset, XOffset, centerOnPage, firstPageOnly ? "" : "");
                PastePageHeader(section, hdr);
            }

            WdHeaderFooterIndex.wdHeaderFooterPrimary  
        }

        return true;
    }

    private static Word.Shape InsertWatermarkInHeader(HeaderFooter header, Section section, string watermarkText, int opacity, int orientation, int fontSize, int YOffset, int XOffset, bool centerOnPage, string postfix)
    {
        // Ensure we don't place in the same header twice when section breaks on same page
        for (int i = 1; i <= header.Shapes.Count; i++)
        {
            try
            {
               //if (header.Shapes.Item(i).Name.StartsWith("TS-WaterMark")) return null;
            }
            catch (Exception) { }
        }
        Word.Shape wm = null;
        try
        {
            wm = header.Shapes.AddTextEffect(MsoPresetTextEffect.msoTextEffect1, watermarkText, "Times New Roman", fontSize,
                MsoTriState.msoFalse, MsoTriState.msoFalse, 0, 0, header.Range);
            wm.Visible = MsoTriState.msoCTrue;
            Random r = new Random();
            int random = r.Next(0, int.MaxValue);
            wm.Name = "TS-WaterMark_"+ postfix + random.ToString();
            wm.TextEffect.NormalizedHeight = MsoTriState.msoFalse;
            wm.Line.Visible = MsoTriState.msoFalse;
            wm.Fill.Visible = MsoTriState.msoTrue;
            wm.LockAspectRatio = MsoTriState.msoTrue;
            float f = (float)(100-opacity) / 100 * 255;
            int intf = (int)f;
            wm.Fill.ForeColor.RGB = (intf + (int)(0x100 * intf) + (int)(0x10000 * intf));
            wm.Fill.Transparency = (float)(100-opacity)/100;
            wm.Fill.Solid();
            wm.Rotation = orientation;


            wm.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
            wm.RelativeHorizontalPosition = WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;
            // Seems to scale up the watermark to the whole page 
            //wm.Height = section.PageSetup.PageHeight;
            //wm.Width = section.PageSetup.PageWidth;

            wm.WrapFormat.AllowOverlap = -1;
            wm.WrapFormat.Side = WdWrapSideType.wdWrapBoth;
            wm.WrapFormat.Type = WdWrapType.wdWrapNone;

            if (centerOnPage)
            {
                wm.Left = (float)WdShapePosition.wdShapeCenter;
                wm.Top = (float)WdShapePosition.wdShapeCenter;
            }
            else 
            {
                wm.Left = XOffset;
                wm.Top = YOffset;
            }
            wm.Visible = MsoTriState.msoCTrue;
        }
        catch (Exception ex)
        {
            Logging.WriteLog("Error adding watermark " + ex.Message);
        }
        return wm;
    }

`

我尝试了多种解决方案,但到目前为止还没有奏效。我还录制了宏,以查看 Word 如何实现在特定页面上放置水印,但它也无法正常工作(水印被文本覆盖)。

这似乎是一件很简单的事情

C# VBA MS-Word 办公互 Word-互操作

评论

0赞 Charles Kenyon 6/27/2023
我在 WaterMarks 上的文章可能会对您有所帮助:addbalance.com/usersguide/sections2007.htm#Watermarksaddbalance.com/usersguide/......这些不是代码,而是对 Word 如何插入和使用水印以及它们在 Word UI 中的内容的检查。您可以在标题中使用图像,而不是使用 Word 中的水印功能。特别是,请参阅在偶数页或奇数页上插入水印的部分。

答: 暂无答案