最近想实现C#自动批量添加word背景水印,但是找了好久发现都是只有三方商业软件库 有这个功能, 但是调用word原生方法的没有找到 ,于是只有自己去研究了. 资料比较少 ,但我研究的方式是从word自带的宏入手.
1.首先打开word的宏录制 ,然后手动操作打开的word文档 实现添加一个水印 .
2.查看刚才录制的宏代码,然后分析,抽取转换成C#代码
Sub 宏1()
'
' 宏1 宏
'
'
Selection.TypeText Text:="测试"
Selection.Copy
Selection.PasteAndFormat (wdFormatOriginalFormatting)
Selection.PasteAndFormat (wdFormatOriginalFormatting)
Selection.TypeParagraph
Selection.TypeParagraph
ActiveDocument.Sections(1).Range.Select
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Selection.HeaderFooter.Shapes.AddTextEffect( _
PowerPlusWaterMarkObject307329625, "水印文字", "等线", 1, False, False, 0, 0) _
.Select
Selection.ShapeRange.Name = "PowerPlusWaterMarkObject307329625"
Selection.ShapeRange.TextEffect.NormalizedHeight = False
Selection.ShapeRange.Line.Visible = False
Selection.ShapeRange.Fill.Visible = True
Selection.ShapeRange.Fill.Solid
Selection.ShapeRange.Fill.ForeColor.RGB = RGB(192, 192, 192)
Selection.ShapeRange.Fill.Transparency = 0.5
Selection.ShapeRange.Rotation = 315
Selection.ShapeRange.LockAspectRatio = True
Selection.ShapeRange.Height = CentimetersToPoints(4.13)
Selection.ShapeRange.Width = CentimetersToPoints(16.52)
Selection.ShapeRange.WrapFormat.AllowOverlap = True
Selection.ShapeRange.WrapFormat.Side = wdWrapNone
Selection.ShapeRange.WrapFormat.Type = 3
Selection.ShapeRange.RelativeHorizontalPosition = _
wdRelativeVerticalPositionMargin
Selection.ShapeRange.RelativeVerticalPosition = _
wdRelativeVerticalPositionMargin
Selection.ShapeRange.Left = wdShapeCenter
Selection.ShapeRange.Top = wdShapeCenter
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub
3.根据自己的实际需要 把添加水印代码进行封装使用.
去掉 Selection.HeaderFooter.Shapes.AddTextEffect 之前的代码 ,把 Selection 替换 成你程序打开的word对应的段落对像即可.
下次再聊一下,如何删除掉已经添加的水印 和修改水印文字内容.