当前位置:   article > 正文

C# 实现 Word 加盖骑缝章效果_c# npoi word 加印章

c# npoi word 加印章

 

目录

实现效果

范例运行环境

Office DCOM 配置

设计实现

创建stamp图章类 

电子章图片的计算与定位

旋转图片方法

总结 


实现效果

OA的自动化处理系统中,通过审批的最终节点,可能会对WORD文件加盖电子章,比如定位带有指定文字的Range周围加盖电子章,骑缝章,甚至水印图片。比如如下效果图:

54f76cb8e6914b3092a5e991c3a83ae1.png

 cd92a2943a0d460dba329084920e7f9c.png

范例运行环境

操作系统: Windows Server 2019 DataCenter

操作系统上安装 Office Word 2016 ,客户端使用的 Office Word 2019

.net版本: .netFramework4.7.1 或以上

开发工具:VS2019  C#

Office DCOM 配置

请参考我的文章《C# 读取Word表格到DataSet》有对Office DCOM详细配置介绍,这里不再赘述。 

设计实现

创建stamp图章类 

导出WORD文件可以传入多个图章类(如果需要的话),图章类主要包括实现如下设置:

1、可设置三种图片(标准的盖章图片、骑缝章图片、水印图片)

2、标准的盖章图片是否显示,不显示则可以只显示骑缝章或水印图片,这个可以模拟多次盖骑缝章的效果

3、定位盖章文字,可以设置一下 x、y的偏移量,以校准指定的模板文件,达到最佳重叠效果。

4、可设置各种章的翻转角度(可随机选取)

示例代码如下: 

  1. public class stamp
  2. {
  3. public string stampImageFilename = ""; //盖章图片
  4. public string stampImageFilename2 = ""; //骑缝章图片
  5. public string stampImageFilename3 = ""; //水印章图片
  6. public bool stampImageVisible = true; //主章是否可显示
  7. public string findWord = ""; //查找盖章定位文字
  8. public int findWordOffsetX = 0; //查找盖章文字后,章的定位偏移量
  9. public int findWordOffsetY = 0; //查找盖章文字后,章的定位偏移量
  10. public int stamp2X = 0; //骑缝章偏移量
  11. public int stamp2Y = 0; //骑缝章偏移量
  12. public int roteAngle = 0; //骑缝章翻转角度,12点方向为0度,顺时针计算角度
  13. public bool roteReFix = false; //骑缝章翻转角度重新计算适应图片(多见于对角线)
  14. public bool randomRoteAngle = false; //骑缝章是否按指定角度的最大随机值提取
  15. public int stampImageWidth = 0; //章宽度
  16. public int stampImageHeight = 0; //章高度
  17. public string stamp2Direction = "right"; //骑缝章盖章方向 默认right ,包括 left/top/bottom
  18. public int stampAngle = 0; //骑缝章翻转角度,12点方向为0度,顺时针计算角度
  19. public bool randomStampAngle = false; //骑缝章是否按指定角度的最大随机值提取
  20. public int stamp3X = 0; //水印章每页X
  21. public int stamp3Y = 0; //水印章每页Y
  22. public int stamp3Angle = 0; //水印章翻转角度,12点方向为0度,顺时针计算角度
  23. }

电子章图片的计算与定位

可以创建多个图章类添加 ArrayList 中进行方法传递, 初始值为public ArrayList Stamps = null;

创建方法  public string setWordStamps(string _filename,ArrayList Stamps)

实现的功能大致如下:

1、主章根据提供查找的关键字,如 “盖章处:”、“盖章:”,然后添加图片重叠在文字的上方周围

2、骑缝章根据页数进行分割计算,每页分隔宽度不小于 1 像素

3、骑缝章可选择“盖”在页面的上下左右位置,如果多个位置方向都需要“盖”,则传递多个 stamp 图章类

4、章可以随机和指定旋转角度

示例代码如下:

  1. public string setWordStamps(string _filename,ArrayList Stamps){
  2. Object Nothing =System.Reflection.Missing.Value;
  3. string _file="",_path=Path.GetDirectoryName(_filename)+"\\tempbfile\\",_ext="";
  4. _file=Path.GetFileNameWithoutExtension(_filename);
  5. _ext=Path.GetExtension(_filename);
  6. string _validfilename=Guid.NewGuid().ToString()+_ext;
  7. string _lastfile=_path+_validfilename;
  8. string _pdfFile = _path + Guid.NewGuid().ToString() + ".pdf";
  9. System.IO.File.Copy(_filename,_lastfile,true);
  10. if(!File.Exists(_lastfile))
  11. {
  12. return "";
  13. }
  14. //取得Word文件保存路径
  15. object filename=_lastfile;
  16. //创建一个名为WordApp的组件对象
  17. Word.Application WordApp=new Word.Application();
  18. //创建一个名为WordDoc的文档对象
  19. WordApp.DisplayAlerts=Word.WdAlertLevel.wdAlertsNone;
  20. Word.Document WordDoc=WordApp.Documents.Open(ref filename,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);
  21. WordDoc.SpellingChecked = false;
  22. WordDoc.ShowSpellingErrors = false;
  23. WordDoc.ActiveWindow.View.Type = Word.WdViewType.wdNormalView;
  24. //遍历stamp图章类
  25. foreach (stamp Stamp in Stamps)
  26. {
  27. bool isfirst = true;
  28. int iii = 0;
  29. int selectStart = 0;
  30. ArrayList restoreRange = new ArrayList();
  31. while (true)
  32. {
  33. iii++;
  34. bool findstamptext = false;
  35. if (Stamp.findWord != "")
  36. {
  37. WordApp.Selection.Range.Start = selectStart;
  38. Word.Find fnd = WordApp.Selection.Find;
  39. Object findText = Stamp.findWord;
  40. Object matchCase = false;
  41. Object matchWholeWord = Type.Missing;
  42. Object matchWildcards = false;
  43. Object matchSoundsLike = false;
  44. Object matchAllWordForms = false;
  45. Object forward = true;
  46. Object wrap = Word.WdFindWrap.wdFindContinue;
  47. Object format = false;
  48. Object replaceWith = "";
  49. Object replace = Type.Missing; ;
  50. Object matchKashida = Type.Missing;
  51. Object matchDiacritics = Type.Missing;
  52. Object matchAlefHamza = Type.Missing;
  53. Object matchControl = Type.Missing;
  54. if (fnd.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms,
  55. ref forward, ref wrap, ref format, ref replaceWith, ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl))
  56. {
  57. selectStart = WordApp.Selection.Range.Start;
  58. restoreRange.Add(WordApp.Selection.Range);
  59. findstamptext = true;
  60. }
  61. else
  62. {
  63. findstamptext = false;
  64. }
  65. }
  66. if (findstamptext == false)
  67. {
  68. break;
  69. }
  70. Word.InlineShape pic = WordApp.Selection.Range.InlineShapes.AddPicture(Stamp.stampImageFilename, false, true);
  71. Word.Shape picshape = pic.ConvertToShape();
  72. picshape.WrapFormat.Type = Word.WdWrapType.wdWrapNone;
  73. if (Stamp.stampImageWidth != 0)
  74. {
  75. picshape.Width = Stamp.stampImageWidth;
  76. }
  77. if (Stamp.stampImageHeight != 0)
  78. {
  79. picshape.Height = Stamp.stampImageHeight;
  80. }
  81. float pagewidth = 0;
  82. float pageheight = 0;
  83. if (findstamptext == true)
  84. {
  85. if (Stamp.stampAngle > 0)
  86. {
  87. Random rnd = new Random();
  88. picshape.Rotation = Stamp.randomStampAngle == false ? Stamp.stampAngle : rnd.Next(Stamp.stampAngle);
  89. }
  90. pagewidth = WordApp.Selection.PageSetup.PageWidth;
  91. pageheight = WordApp.Selection.PageSetup.PageHeight;
  92. int ox = 0; int oy = 0; int ow = 0; int oh = 0;
  93. WordApp.Windows[1].GetPoint(out ox, out oy, out ow, out oh, WordApp.Selection.Range);
  94. WordApp.Selection.Range.Text = "";
  95. picshape.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;
  96. picshape.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
  97. picshape.Left = (float)(ox * 0.405402299) - (picshape.Width / 2);
  98. picshape.Top = WordApp.Selection.Range.Information[Word.WdInformation.wdVerticalPositionRelativeToPage] - (picshape.Height / 2);
  99. if ((bool)WordApp.Selection.Range.Information[Word.WdInformation.wdWithInTable] == true)
  100. {
  101. picshape.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionCharacter;
  102. picshape.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionLine;
  103. picshape.Left = 0;
  104. picshape.Top = 0;
  105. }
  106. }
  107. picshape.Left = picshape.Left + Stamp.findWordOffsetX;
  108. picshape.Top = picshape.Top + Stamp.findWordOffsetY;
  109. if (Stamp.stampImageVisible == false)
  110. {
  111. picshape.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
  112. }
  113. if (Stamp.stampImageFilename2 != ""&&isfirst==true)
  114. {
  115. int ra = Stamp.roteAngle;
  116. if (ra > 0)
  117. {
  118. Random rnd = new Random();
  119. ra = Stamp.randomRoteAngle == false ? ra : rnd.Next(ra);
  120. }
  121. Bitmap cc = (Bitmap)Image.FromFile(Stamp.stampImageFilename2);
  122. Bitmap bb = Rotate(cc, -ra, Stamp.roteReFix);
  123. WordDoc.Windows[1].Panes[1].Pages;
  124. int pages2 = WordDoc.ComputeStatistics(Word.WdStatistic.wdStatisticPages, ref Nothing);
  125. if (pages2 == 1)
  126. {
  127. pages2 = 0; //如果一页就不盖骑缝章
  128. }
  129. for (int pi = 1; pi <= pages2; pi++)
  130. {
  131. Word.Range pagerange = WordDoc.GoTo(Word.WdGoToItem.wdGoToPage, Word.WdGoToDirection.wdGoToAbsolute, pi.ToString());
  132. int rx = (pi - 1) * bb.Width / pages2;
  133. int ry = 0;
  134. int rw = bb.Width / pages2;
  135. int rh = bb.Height;
  136. if (Stamp.stamp2Direction == "bottom")
  137. {
  138. rx = 0;
  139. ry = (pi - 1) * bb.Height / pages2;
  140. rw = bb.Width;
  141. rh = bb.Height / pages2;
  142. }
  143. else if (Stamp.stamp2Direction == "left")
  144. {
  145. rx = (pages2 - pi) * bb.Width / pages2;
  146. ry = 0;
  147. rw = bb.Width / pages2;
  148. rh = bb.Height;
  149. }
  150. else if (Stamp.stamp2Direction == "top")
  151. {
  152. rx = 0;
  153. ry = (pages2 - pi) * bb.Height / pages2;
  154. rw = bb.Width;
  155. rh = bb.Height / pages2;
  156. }
  157. if (rw < 1 || rh < 1)
  158. {
  159. continue;
  160. }
  161. Bitmap sepbitmap1 = bb.Clone(new System.Drawing.Rectangle(rx, ry, rw, rh), System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
  162. string temppng = "d:\\" + System.Guid.NewGuid().ToString() + ".png";
  163. sepbitmap1.Save(temppng);
  164. Word.InlineShape pic2 = pagerange.InlineShapes.AddPicture(temppng, false, true);
  165. Word.Shape picshape2 = pic2.ConvertToShape();
  166. picshape2.WrapFormat.Type = Word.WdWrapType.wdWrapNone;
  167. picshape2.Width = picshape.Width / pages2;
  168. picshape2.Height = picshape.Height;
  169. if (Stamp.stamp2Direction == "bottom" || Stamp.stamp2Direction == "top")
  170. {
  171. picshape2.Width = picshape.Width;
  172. picshape2.Height = picshape.Height / pages2;
  173. }
  174. picshape2.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;
  175. picshape2.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
  176. picshape2.Left = pagewidth - picshape2.Width;
  177. picshape2.Top = Stamp.stamp2Y;
  178. if (Stamp.stamp2Direction == "bottom")
  179. {
  180. picshape2.Left = Stamp.stamp2X;
  181. picshape2.Top = pageheight - picshape2.Height;
  182. }
  183. else if (Stamp.stamp2Direction == "left")
  184. {
  185. picshape2.Left = 0;
  186. picshape2.Top = Stamp.stamp2Y;
  187. }
  188. else if (Stamp.stamp2Direction == "top")
  189. {
  190. picshape2.Left = Stamp.stamp2X;
  191. picshape2.Top = 0;
  192. }
  193. resultReport += string.Format("stamp2 {2} left: {0} top:{1} width:{3} height:{4}<br>", picshape2.Left, picshape2.Top,pi,picshape2.Width,picshape2.Height);
  194. File.Delete(temppng);
  195. }
  196. }//stamp2
  197. if (Stamp.stampImageFilename3 != ""&&isfirst==true)
  198. {
  199. int ra = Stamp.stamp3Angle;
  200. if (ra > 0)
  201. {
  202. Random rnd = new Random();
  203. ra = Stamp.randomRoteAngle == false ? ra : rnd.Next(ra);
  204. }
  205. Bitmap cc = (Bitmap)Image.FromFile(Stamp.stampImageFilename3);
  206. Bitmap bb = Rotate(cc, -ra, true);
  207. int pages2 = WordDoc.ComputeStatistics(Word.WdStatistic.wdStatisticPages, ref Nothing);
  208. resultReport += string.Format(" PageCount3:{0}<br>", pages2);
  209. for (int pi = 1; pi <= pages2; pi++)
  210. {
  211. Word.Range pagerange = WordDoc.GoTo(Word.WdGoToItem.wdGoToPage, Word.WdGoToDirection.wdGoToAbsolute, pi.ToString());
  212. int rx = (pi - 1) * bb.Width / pages2;
  213. rx = 0;
  214. int ry = 0;
  215. int rw = bb.Width;
  216. int rh = bb.Height;
  217. Bitmap sepbitmap1 = bb.Clone(new System.Drawing.Rectangle(rx, ry, rw, rh), System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
  218. string temppng = "d:\\" + System.Guid.NewGuid().ToString() + ".png";
  219. Word.InlineShape pic2 = pagerange.InlineShapes.AddPicture(temppng, false, true);
  220. Word.Shape picshape2 = pic2.ConvertToShape();
  221. picshape2.WrapFormat.Type = Word.WdWrapType.wdWrapNone;
  222. picshape2.Width = picshape.Width;
  223. picshape2.Height = picshape.Height;
  224. picshape2.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;
  225. picshape2.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
  226. picshape2.Left = Stamp.stamp3X;
  227. // picshape2.Left = Stamp.stamp2X;
  228. picshape2.Top = Stamp.stamp2Y;
  229. File.Delete(temppng);
  230. }
  231. }//stamp3
  232. isfirst = false;
  233. }// while
  234. foreach (Word.Range range in restoreRange)
  235. {
  236. range.Text = Stamp.findWord;
  237. }
  238. }//foreach
  239. WordDoc.Save();
  240. WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
  241. //关闭WordApp组件对象
  242. WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
  243. return _lastfile;
  244. }

旋转图片方法

  1. public Bitmap Rotate(Bitmap b, int angle,bool fix=false)
  2. {
  3. angle = angle % 360;
  4. //弧度转换
  5. double radian = angle * Math.PI / 180.0;
  6. double cos = Math.Cos(radian);
  7. double sin = Math.Sin(radian);
  8. //原图的宽和高
  9. int w = b.Width;
  10. int h = b.Height;
  11. int ow = w;
  12. int oh = h;
  13. int d = ((int)Math.Sqrt(Math.Pow(w - 0, 2) + Math.Pow(h- 0, 2))+1);
  14. if (fix == true)
  15. {
  16. w = d;
  17. h = d;
  18. }
  19. int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
  20. int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
  21. //目标位图
  22. Bitmap dsImage = new Bitmap(w, h);
  23. System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage);
  24. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
  25. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  26. //计算偏移量
  27. System.Drawing.Point Offset = new System.Drawing.Point((W - w) / 2, (H - h) / 2);
  28. //构造图像显示区域:让图像的中心与窗口的中心点一致
  29. System.Drawing.Rectangle rect = new System.Drawing.Rectangle(fix==false?0:(d-ow)/2, fix == false ? 0 : (d-oh)/2, ow, oh);
  30. // System.Drawing.Rectangle rect = new System.Drawing.Rectangle(Offset.X, Offset.Y, w, h);
  31. // System.Drawing.Point center = new System.Drawing.Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
  32. System.Drawing.Point center = new System.Drawing.Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
  33. g.TranslateTransform(center.X, center.Y);
  34. g.RotateTransform(360 - angle);
  35. //恢复图像在水平和垂直方向的平移
  36. g.TranslateTransform(-center.X, -center.Y);
  37. g.DrawImage(b, rect);
  38. //重至绘图的所有变换
  39. g.ResetTransform();
  40. g.Save();
  41. g.Dispose();
  42. //dsImage.Save("yuancd.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
  43. return dsImage;
  44. }

总结 

以上是实现设计的一些参考代码,在实际的使用中,可能还会遇到如下问题:

1、定位关键字的叠加效果不好,因此针对每一个模板文件均需要调整图片的x、y偏移量,以达到最佳效果

2、对于超多页面的文件(如几万页),骑缝的效果可能不佳,可以采取调整图片像素宽度,或拆分模板文件进行处理

示例代码仅作参考,欢迎大家评论指教!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/139578
推荐阅读
相关标签
  

闽ICP备14008679号