1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Data;
  6. using Aspose.Words;
  7. using System.Configuration;
  8. using System.Data.SqlClient;
  9. using System.Reflection;
  10. using Aspose.Words.Drawing;
  11. using System.Text.RegularExpressions;
  12. using System.IO;
  13. using Aspose.Words.Saving;
  14. using Aspose.Words.Tables;
  15. using System.Text;
  16. using System.Drawing.Printing;
  17. using System.Collections;
  18.  
  19. namespace WebControl
  20. {
  21. public class Print
  22. {
  23. private void SaveDocument(Document doc)
  24. {
  25. //SaveOptions saveop = SaveOptions.CreateSaveOptions(filename + ".doc");
  26. //doc.Save(HttpContext.Current.Response, filename + ".doc", ContentDisposition.Attachment, saveop);
  27. if (Dotype.Equals("word"))
  28. {
  29. SaveOptions saveop = SaveOptions.CreateSaveOptions(filename + ".doc");
  30. doc.Save(HttpContext.Current.Response, filename + ".doc", ContentDisposition.Attachment, saveop);
  31. }
  32. else if (Dotype.Equals("pdf"))
  33. {
  34.  
  35. filename = filename + ".pdf";
  36. string dirpath = HttpContext.Current.Server.MapPath("~/FlexPaper/docs");
  37. if (!Directory.Exists(dirpath))
  38. {
  39. Directory.CreateDirectory(dirpath);
  40. }
  41. string strpath = dirpath + "/" + filename;
  42. if (File.Exists(strpath))
  43. {
  44. File.Delete(strpath);
  45. }
  46. doc.Save(strpath, SaveFormat.Pdf);
  47. FileInfo fileInfo = new FileInfo(strpath);
  48. HttpContext.Current.Response.Clear();
  49. HttpContext.Current.Response.ClearContent();
  50. HttpContext.Current.Response.ClearHeaders();
  51. filename = System.Web.HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);
  52. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
  53. HttpContext.Current.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
  54. HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
  55. HttpContext.Current.Response.ContentType = "application/octet-stream";
  56. //Response.ContentEncoding = System.Text.Encoding.UTF8;
  57. HttpContext.Current.Response.WriteFile(fileInfo.FullName);
  58. HttpContext.Current.Response.Flush();
  59. HttpContext.Current.Response.End();
  60. }
  61.  
  62. }
  63.  
  64. #region 打印多个模板拼接成word
  65.  
  66. public Document printDocumentAllWordMore(List<PrintData> datalist)
  67. {
  68. int p = ;
  69. Document maindoc = new Document();
  70. foreach (var page in datalist)
  71. {
  72. Document newdoc = new Document(page.wordpath);
  73. DocumentBuilder builder = new DocumentBuilder(newdoc);
  74. List<DataTable> dtinfos = page.dtinfos;
  75.  
  76. if (dtinfos != null)
  77. {
  78. for (int i = ; i < dtinfos.Count; i++)
  79. {
  80. DataTable dtinfo = dtinfos[i];
  81. if (dtinfo != null)
  82. {
  83. for (int n = ; n < dtinfo.Columns.Count; n++)
  84. {
  85. string fieldname = dtinfo.Columns[n].ColumnName.ToLower();
  86. try
  87. {
  88. string fieldvalue = dtinfo.Rows[][fieldname].ToString();
  89. newdoc.Range.Replace(WordTabChar + fieldname + WordTabChar, fieldvalue, false, false);
  90. }
  91. catch { }
  92. }
  93. }
  94. }
  95. }
  96. Dictionary<string, string> dict = page.dict;
  97. if (dict != null)
  98. {
  99. foreach (var key in dict.Keys)
  100. {
  101. try
  102. {
  103. newdoc.Range.Replace(WordTabChar + key + WordTabChar, dict[key], false, false);
  104. }
  105. catch { }
  106. }
  107. }
  108. List<PositionProChildren> listpos = new List<PositionProChildren>();
  109. List<DataTable> dtlist = page.dtlist;
  110. int section = newdoc.GetChildNodes(NodeType.Section, true).Count;
  111. int dataindex = ;
  112. for (int kk = ; kk < section; kk++)
  113. {
  114. Aspose.Words.Section dtsection = (Aspose.Words.Section)newdoc.GetChild(NodeType.Section, kk, true);
  115. int num = dtsection.Body.Tables.Count;
  116. for (int mm = ; mm < num; mm++)
  117. {
  118. Aspose.Words.Tables.Table dtdoc1 = dtsection.Body.Tables[mm];
  119.  
  120. for (int r = ; r < dtdoc1.Rows.Count; r++)
  121. {
  122. for (int c = ; c < dtdoc1.Rows[r].Cells.Count; c++)
  123. {
  124. if (dtdoc1.Rows[r].Cells[c].Range.Text.ToLower().Contains("#start#"))
  125. {
  126. PositionProChildren pos = new PositionProChildren();
  127. pos.tableindex = mm;
  128. pos.row_start = r;
  129. pos.cell_start = c;
  130. pos.row_end = r;
  131. pos.cell_end = c;
  132. listpos.Add(pos);
  133. dtdoc1.Rows[r].Cells[c].Range.Replace("#START#", "", false, false);
  134. }
  135. if (dtdoc1.Rows[r].Cells[c].Range.Text.ToLower().Contains("#end#"))
  136. {
  137. PositionProChildren pos = listpos.Last<PositionProChildren>();
  138. pos.row_end = r;
  139. pos.cell_end = c;
  140. dtdoc1.Rows[r].Cells[c].Range.Replace("#END#", "", false, false);
  141. }
  142. }
  143. }
  144. for (int i = ; i < listpos.Count; i++)
  145. {
  146. PositionProChildren pos = new PositionProChildren();
  147. if (listpos.Count > i)
  148. {
  149. pos = listpos[i];
  150. }
  151. DataTable dt = dtlist[i + dataindex];
  152.  
  153. Aspose.Words.Tables.Table dtdoc = dtsection.Body.Tables[mm];
  154. List<string> celltabs = new List<string>();
  155. for (int t = pos.cell_start; t < dtdoc.Rows[pos.row_start].Cells.Count; t++)
  156. {
  157. string colname = dtdoc.Rows[pos.row_start].Cells[t].Range.Text.Replace(WordTabChar, "").Replace("\a", "");
  158. celltabs.Add(colname);
  159. dtdoc.Rows[pos.row_start].Range.Replace(WordTabChar + colname + WordTabChar, "", false, false);
  160. }
  161. if (dt.Rows.Count > pos.rownum)
  162. {
  163. int addrow = dt.Rows.Count - pos.rownum;
  164. for (int a = ; a < addrow; a++)
  165. {
  166. Aspose.Words.Node newrow = dtdoc.Rows[pos.row_start + ].Clone(true);//确认模板有第二行
  167.  
  168. //Aspose.Words.Node newrow = dtdoc.Rows[pos.row_start].Clone(true);
  169. dtdoc.Rows.Insert(pos.row_start + , newrow);
  170. if (i < listpos.Count - )
  171. {
  172. for (int l = i + ; l < listpos.Count; l++)
  173. {
  174. PositionProChildren poscur = listpos[l - ];
  175. PositionProChildren posnext = listpos[l];
  176. if (posnext.tableindex.Equals(poscur.tableindex))
  177. {
  178. posnext.row_start += ;
  179. posnext.row_end += ;
  180. }
  181. else
  182. break;
  183. }
  184. }
  185. }
  186.  
  187. }
  188.  
  189. for (int m = ; m < dt.Rows.Count; m++)
  190. {
  191. for (int n = ; n < celltabs.Count; n++)
  192. {
  193. try
  194. {
  195. builder.MoveToSection(kk);
  196. //builder.MoveTo(newdoc.Sections[kk].Body.Tables[mm].Rows[pos.row_start + m].Cells[pos.cell_start + n].Paragraphs[0].Runs[0]);
  197. builder.MoveToCell(pos.tableindex, pos.row_start + m, pos.cell_start + n, );
  198. builder.Write(dt.Rows[m][celltabs[n].ToString()].ToString());
  199. }
  200. catch { }
  201. }
  202. }
  203.  
  204. }
  205.  
  206. //dataindex = 0;
  207. dataindex = dataindex + listpos.Count;
  208. listpos.Clear();
  209.  
  210. }
  211.  
  212. }
  213. if (!p.Equals())
  214. {
  215. newdoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
  216. maindoc.AppendDocument(newdoc, ImportFormatMode.KeepSourceFormatting);
  217. }
  218. else
  219. {
  220. maindoc = newdoc;
  221. }
  222. p++;
  223. }
  224. return maindoc;
  225. }
  226.  
  227. public void PrintMoreMb(List<List<PrintData>> datalist)
  228. {
  229. if (datalist.Count > )
  230. {
  231. Document maindoc = printDocumentAllWordMore(datalist[]);
  232. Document newdoc = new Document();
  233. for (int i = ; i < datalist.Count; i++)
  234. {
  235. newdoc = printDocumentAllWordMore(datalist[i]);
  236. newdoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
  237. maindoc.AppendDocument(newdoc, ImportFormatMode.KeepSourceFormatting);
  238. }
  239. maindoc.Protect(ProtectionType.AllowOnlyFormFields, "mima");
  240. WaterMark(maindoc, HttpContext.Current.Session["LRXSMC_SH"].ToString());
  241. //WaterMarkMore(maindoc, HttpContext.Current.Session["LRXSMC_SH"].ToString());
  242. this.SaveDocument(maindoc);
  243. }
  244.  
  245. }
  246.  
  247. //public Object apply(Shape watermark)
  248. //{
  249. // watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.MARGIN);
  250. // watermark.setRelativeVerticalPosition(RelativeVerticalPosition.MARGIN);
  251. // watermark.setWrapType(WrapType.NONE);
  252. // // 我们需要自定义距离顶部的高度
  253. // // watermark.setVerticalAlignment(VerticalAlignment.TOP);
  254. // watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
  255. // // 设置距离顶部的高度
  256. // watermark.setTop(160);
  257.  
  258. // return null;
  259. //}
  260.  
  261. /// <summary>
  262. /// 插入多个水印
  263. /// </summary>
  264. /// <param name="mdoc">Document</param>
  265. /// <param name="wmText">水印文字名</param>
  266. /// <param name="left">左边距多少</param>
  267. /// <param name="top">上边距多少</param>
  268. /// <returns></returns>
  269. public static Shape ShapeMore(Document mdoc, string wmText, double left, double top)
  270. {
  271. Shape waterShape = new Shape(mdoc, ShapeType.TextPlainText);
  272. //设置该文本的水印
  273. waterShape.TextPath.Text = wmText;
  274. waterShape.TextPath.FontFamily = "宋体";
  275. waterShape.Width = ;
  276. waterShape.Height = ;
  277. //文本将从左下角到右上角。
  278. waterShape.Rotation = ;
  279. //绘制水印颜色
  280. waterShape.Fill.Color = System.Drawing.Color.Gray;//浅灰色水印
  281. waterShape.StrokeColor = System.Drawing.Color.Gray;
  282. //将水印放置在页面中心
  283. waterShape.Left = left;
  284. waterShape.Top = top;
  285. waterShape.WrapType = WrapType.None;
  286. return waterShape;
  287. }
  288.  
  289. /// <summary>
  290. /// 插入多个水印
  291. /// </summary>
  292. /// <param name="mdoc">Document</param>
  293. /// <param name="wmText">水印文字名</param>
  294. public static void WaterMarkMore(Document mdoc, string wmText)
  295. {
  296. Paragraph watermarkPara = new Paragraph(mdoc);
  297. for (int j = ; j < ; j = j + )
  298. {
  299. for (int i = ; i < ; i = i + )
  300. {
  301. Shape waterShape = ShapeMore(mdoc, wmText, j, i);
  302. watermarkPara.AppendChild(waterShape);
  303. }
  304. }
  305.  
  306. // 在每个部分中,最多可以有三个不同的标题,因为我们想要出现在所有页面上的水印,插入到所有标题中。
  307. foreach (Section sect in mdoc.Sections)
  308. {
  309. // 每个区段可能有多达三个不同的标题,因为我们希望所有页面上都有水印,将所有的头插入。
  310. InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary);
  311. InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst);
  312. InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven);
  313. }
  314. }
  315.  
  316. /// <summary>
  317. /// 插入水印
  318. /// </summary>
  319. /// <param name="mdoc">Document</param>
  320. /// <param name="wmText">水印名称</param>
  321. public static void WaterMark(Document mdoc, string wmText)
  322. {
  323. Shape waterShape = new Shape(mdoc, ShapeType.TextPlainText);
  324. //设置该文本的水印
  325. waterShape.TextPath.Text = wmText;
  326. waterShape.TextPath.FontFamily = "宋体";
  327. waterShape.Width = ;
  328. waterShape.Height = ;
  329. //文本将从左下角到右上角。
  330. waterShape.Rotation = -;
  331. //绘制水印颜色
  332. waterShape.Fill.Color = System.Drawing.Color.Gray;//浅灰色水印
  333. waterShape.StrokeColor = System.Drawing.Color.Gray;
  334.  
  335. //waterShape.Fill.Color = System.Drawing.Color.FromName("#DFF1DF");//浅灰色水印
  336. //waterShape.StrokeColor = System.Drawing.Color.Gray;
  337.  
  338. //将水印放置在页面中心
  339. //waterShape.Left = 200;
  340. //waterShape.Top = 600;
  341. waterShape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
  342. waterShape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
  343. waterShape.WrapType = WrapType.None;
  344. waterShape.VerticalAlignment = VerticalAlignment.Center;
  345. waterShape.HorizontalAlignment = HorizontalAlignment.Center;
  346.  
  347. // 创建一个新段落并在该段中添加水印。
  348. Paragraph watermarkPara = new Paragraph(mdoc);
  349. watermarkPara.AppendChild(waterShape);
  350.  
  351. // 在每个部分中,最多可以有三个不同的标题,因为我们想要出现在所有页面上的水印,插入到所有标题中。
  352. foreach (Section sect in mdoc.Sections)
  353. {
  354. // 每个区段可能有多达三个不同的标题,因为我们希望所有页面上都有水印,将所有的头插入。
  355. InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary);
  356. InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst);
  357. InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven);
  358. }
  359. }
  360. private static void InsertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, HeaderFooterType headerType)
  361. {
  362. HeaderFooter header = sect.HeadersFooters[headerType];
  363.  
  364. if (header == null)
  365. {
  366. // 当前节中没有指定类型的头,创建它
  367. header = new HeaderFooter(sect.Document, headerType);
  368. sect.HeadersFooters.Add(header);
  369. }
  370.  
  371. // 在头部插入一个水印的克隆
  372. header.AppendChild(watermarkPara.Clone(true));
  373. }
  374.  
  375. #endregion
  376.  
  377. }
  378.  
  379. public class ReplaceText : IReplacingCallback
  380. {
  381. /// <summary>
  382. /// 替换文本格式
  383. /// </summary>
  384. public string Text { get; set; }
  385. public ReplaceText(string Text)
  386. {
  387. this.Text = Text;
  388. }
  389. public ReplaceAction Replacing(ReplacingArgs e)
  390. {
  391. //获取当前节点
  392. var node = e.MatchNode;
  393. Document doc = node.Document as Document;
  394. DocumentBuilder builder = new DocumentBuilder(doc);
  395. builder.MoveTo(node);
  396. builder.Write(Text);
  397. return ReplaceAction.Replace;
  398. }
  399. }
  400.  
  401. public class ReplaceHtml : IReplacingCallback
  402. {
  403. /// <summary>
  404. /// 替换为html格式
  405. /// </summary>
  406. public string Text { get; set; }
  407. public ReplaceHtml(string Text)
  408. {
  409. this.Text = Text;
  410. }
  411. public ReplaceAction Replacing(ReplacingArgs e)
  412. {
  413. //获取当前节点
  414. var node = e.MatchNode;
  415. Document doc = node.Document as Document;
  416. DocumentBuilder builder = new DocumentBuilder(doc);
  417. builder.MoveTo(node);
  418. builder.InsertHtml(Text);
  419. return ReplaceAction.Replace;
  420. }
  421. }
  422.  
  423. public class ReplaceImage : IReplacingCallback
  424. {
  425. /// <summary>
  426. /// 替换图片
  427. /// </summary>
  428. public string ImageUrl { get; set; }
  429. //
  430. public ReplaceImage(string url)
  431. {
  432. this.ImageUrl = url;
  433. }
  434. public ReplaceAction Replacing(ReplacingArgs e)
  435. {
  436. //获取当前节点
  437. if (!string.IsNullOrEmpty(ImageUrl))
  438. {
  439. var node = e.MatchNode;
  440. Document doc = node.Document as Document;
  441. DocumentBuilder builder = new DocumentBuilder(doc);
  442. builder.MoveTo(node);
  443. //builder.Write(Text);
  444. Shape shape = new Shape(doc, ShapeType.Image);
  445. shape.ImageData.SetImage(ImageUrl);
  446. shape.Top = ;
  447. shape.Width = ;
  448. shape.Height = ;
  449. shape.HorizontalAlignment = HorizontalAlignment.Center;
  450. CompositeNode node1 = shape.ParentNode;
  451. builder.InsertNode(shape);
  452. }
  453. return ReplaceAction.Replace;
  454. }
  455. }
  456.  
  457. public class PositionPro
  458. {
  459. public string key { get; set; }
  460. public int row_start { get; set; }
  461. public int row_end { get; set; }
  462. public int cell_start { get; set; }
  463. public int cell_end { get; set; }
  464. public int rownum
  465. {
  466. get
  467. {
  468. return row_end - row_start + ;
  469. }
  470. }
  471. }
  472.  
  473. public class PrintData
  474. {
  475. public List<DataTable> dtinfos;
  476. public Dictionary<string, string> dict;
  477. public List<DataTable> dtlist;
  478. public string wordpath;
  479. }
  480.  
  481. public class PositionProChildren
  482. {
  483. public int tableindex { get; set; }
  484. public string key { get; set; }
  485. public int row_start { get; set; }
  486. public int row_end { get; set; }
  487. public int cell_start { get; set; }
  488. public int cell_end { get; set; }
  489. public int rownum
  490. {
  491. get
  492. {
  493. return row_end - row_start + ;
  494. }
  495. }
  496. }
  497. }

ASP.NET基于Aspose.Words插入Word水印以及多个水印的更多相关文章

  1. Aspose.Words给word文档加水印

    需求:在一些重要的Word文档需要打印时,添加水印以明出处. 方案:使用Aspose组件给word文档 代码:干货如下 /// <summary> /// Inserts a waterm ...

  2. Aspose.Words操作word生成PDF文档

    Aspose.Words操作word生成PDF文档 using Aspose.Words; using System; using System.Collections.Generic; using ...

  3. WPF使用Aspose.Words导出Word文档

    一.创建Word文档模板 分析需要导出的word文档,将固定的内容和由程序生成的内容分开; 创建一个word(例如:Template.doc)文档,将固定的内容按照一定的格式写入当前文档中; 打开Te ...

  4. asp.net基于windows服务实现定时发送邮件的方法

    本文实例讲述了asp.net基于windows服务实现定时发送邮件的方法.分享给大家供大家参考,具体如下: //定义组件 private System.Timers.Timer time; publi ...

  5. c# Aspose.Words插入饼图PieChart

    private static void Main(string[] args) { Document doc = new Document(); DocumentBuilder builder = n ...

  6. 解决图片插入word文档后清晰度降低的问题

    解决图片插入word文档后清晰度降低的问题 在默认情况下,word程序会自动压缩插入word文档中的图片以减小整个word文档的.当我们需要插入word文档中的图片保持原始清晰度时,可以通过设置wor ...

  7. Java 在Excel中添加水印(单一水印、平铺水印)

    在Excel中没有直接添加水印的功能,但依旧可以通过一定方式来实现类似水印效果.本文通过Java程序代码介绍具体实现方法.可添加单一水印效果,即水印是以单个文本字样来呈现:也可添加多个平铺水印效果,即 ...

  8. php文字水印和php图片水印实现代码

    本文章向码农们介绍php文字水印和php图片水印实现代码,需要的码农可以参考一下. php 文字水印 文字水印就是在图片上加上文字,主要使用gd库的imagefttext方法,并且需要字体文件. 实现 ...

  9. Aspose.Words进行Word替换(插入图片和水印)

    由于最近一直在忙着做着Word打印模板的一些工作,就整理一些Asponse.Words对Word文档进行操作的资料. using System; using System.Collections.Ge ...

随机推荐

  1. centos7上安装rar解压软件

    (http://www.rarlab.com)官网可以查看最新的版本 wget https://www.rarlab.com/rar/rarlinux-x64-5.5.0.tar.gz 2.tar.g ...

  2. leetcode303

    public class NumArray { List<int> list = new List<int>(); public NumArray(int[] nums) { ...

  3. delphi XE8 NetHTTPRequest NetHTTPClient

    delphi xe8 推出2个新http控件,NetHTTPRequest.NetHTTPClient 可以调用ASP.Net 一般应用程序获取网页数据,用旧的控件idhttp控件也可以,推荐用新的这 ...

  4. MyBatis 查询缓存

    增删改操作对一级缓存的影响:增删改操作都会清空一级缓存,无论是否提交

  5. ajax传参里含有特殊字符的坑

    问题场景:今天在测试自己手上的页面功能时,发现一个小bug,在用ajax向后台发数据时,只要参数中出现一些特殊字符,控制台会报错http 400的问题,其实就是特殊字符服务器不能解析.好了,问题是找到 ...

  6. Spring Cloud Config配置中心的使用

    一.概述 1. 为什么使用? 1> 配置文件太多,不方便维护 2> 配置文件一般都保存这各种明文显示的密码,无法保证配置内容的安全性,也无法做到按权限分配给个人 3> 更新配置项目需 ...

  7. 在Ubuntu16.04中安装Docker CE

    apt-get install apt-transport-https ca-certificates curl software-properties-common curl -fsSL https ...

  8. java.lang.VerifyError: Inconsistent stackmap frames at branch target 81

    java项目中有如下代码: @RequestMapping(value = "/getMxList") @ResponseBody public Map<String, Ob ...

  9. 01b-1: 性能测度

  10. MongoDB 自动分片 auto sharding

    MongoDB部署实验系列文章 MongoDB做为NoSQL数据库,最近几年持续升温,越来越多的企业都开始尝试用MongoDB代替原有Database做一些事情.MongoDB也在集群,分片,复制上也 ...