ASP.NET基于Aspose.Words插入Word水印以及多个水印
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data;
- using Aspose.Words;
- using System.Configuration;
- using System.Data.SqlClient;
- using System.Reflection;
- using Aspose.Words.Drawing;
- using System.Text.RegularExpressions;
- using System.IO;
- using Aspose.Words.Saving;
- using Aspose.Words.Tables;
- using System.Text;
- using System.Drawing.Printing;
- using System.Collections;
- namespace WebControl
- {
- public class Print
- {
- private void SaveDocument(Document doc)
- {
- //SaveOptions saveop = SaveOptions.CreateSaveOptions(filename + ".doc");
- //doc.Save(HttpContext.Current.Response, filename + ".doc", ContentDisposition.Attachment, saveop);
- if (Dotype.Equals("word"))
- {
- SaveOptions saveop = SaveOptions.CreateSaveOptions(filename + ".doc");
- doc.Save(HttpContext.Current.Response, filename + ".doc", ContentDisposition.Attachment, saveop);
- }
- else if (Dotype.Equals("pdf"))
- {
- filename = filename + ".pdf";
- string dirpath = HttpContext.Current.Server.MapPath("~/FlexPaper/docs");
- if (!Directory.Exists(dirpath))
- {
- Directory.CreateDirectory(dirpath);
- }
- string strpath = dirpath + "/" + filename;
- if (File.Exists(strpath))
- {
- File.Delete(strpath);
- }
- doc.Save(strpath, SaveFormat.Pdf);
- FileInfo fileInfo = new FileInfo(strpath);
- HttpContext.Current.Response.Clear();
- HttpContext.Current.Response.ClearContent();
- HttpContext.Current.Response.ClearHeaders();
- filename = System.Web.HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);
- HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
- HttpContext.Current.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
- HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
- HttpContext.Current.Response.ContentType = "application/octet-stream";
- //Response.ContentEncoding = System.Text.Encoding.UTF8;
- HttpContext.Current.Response.WriteFile(fileInfo.FullName);
- HttpContext.Current.Response.Flush();
- HttpContext.Current.Response.End();
- }
- }
- #region 打印多个模板拼接成word
- public Document printDocumentAllWordMore(List<PrintData> datalist)
- {
- int p = ;
- Document maindoc = new Document();
- foreach (var page in datalist)
- {
- Document newdoc = new Document(page.wordpath);
- DocumentBuilder builder = new DocumentBuilder(newdoc);
- List<DataTable> dtinfos = page.dtinfos;
- if (dtinfos != null)
- {
- for (int i = ; i < dtinfos.Count; i++)
- {
- DataTable dtinfo = dtinfos[i];
- if (dtinfo != null)
- {
- for (int n = ; n < dtinfo.Columns.Count; n++)
- {
- string fieldname = dtinfo.Columns[n].ColumnName.ToLower();
- try
- {
- string fieldvalue = dtinfo.Rows[][fieldname].ToString();
- newdoc.Range.Replace(WordTabChar + fieldname + WordTabChar, fieldvalue, false, false);
- }
- catch { }
- }
- }
- }
- }
- Dictionary<string, string> dict = page.dict;
- if (dict != null)
- {
- foreach (var key in dict.Keys)
- {
- try
- {
- newdoc.Range.Replace(WordTabChar + key + WordTabChar, dict[key], false, false);
- }
- catch { }
- }
- }
- List<PositionProChildren> listpos = new List<PositionProChildren>();
- List<DataTable> dtlist = page.dtlist;
- int section = newdoc.GetChildNodes(NodeType.Section, true).Count;
- int dataindex = ;
- for (int kk = ; kk < section; kk++)
- {
- Aspose.Words.Section dtsection = (Aspose.Words.Section)newdoc.GetChild(NodeType.Section, kk, true);
- int num = dtsection.Body.Tables.Count;
- for (int mm = ; mm < num; mm++)
- {
- Aspose.Words.Tables.Table dtdoc1 = dtsection.Body.Tables[mm];
- for (int r = ; r < dtdoc1.Rows.Count; r++)
- {
- for (int c = ; c < dtdoc1.Rows[r].Cells.Count; c++)
- {
- if (dtdoc1.Rows[r].Cells[c].Range.Text.ToLower().Contains("#start#"))
- {
- PositionProChildren pos = new PositionProChildren();
- pos.tableindex = mm;
- pos.row_start = r;
- pos.cell_start = c;
- pos.row_end = r;
- pos.cell_end = c;
- listpos.Add(pos);
- dtdoc1.Rows[r].Cells[c].Range.Replace("#START#", "", false, false);
- }
- if (dtdoc1.Rows[r].Cells[c].Range.Text.ToLower().Contains("#end#"))
- {
- PositionProChildren pos = listpos.Last<PositionProChildren>();
- pos.row_end = r;
- pos.cell_end = c;
- dtdoc1.Rows[r].Cells[c].Range.Replace("#END#", "", false, false);
- }
- }
- }
- for (int i = ; i < listpos.Count; i++)
- {
- PositionProChildren pos = new PositionProChildren();
- if (listpos.Count > i)
- {
- pos = listpos[i];
- }
- DataTable dt = dtlist[i + dataindex];
- Aspose.Words.Tables.Table dtdoc = dtsection.Body.Tables[mm];
- List<string> celltabs = new List<string>();
- for (int t = pos.cell_start; t < dtdoc.Rows[pos.row_start].Cells.Count; t++)
- {
- string colname = dtdoc.Rows[pos.row_start].Cells[t].Range.Text.Replace(WordTabChar, "").Replace("\a", "");
- celltabs.Add(colname);
- dtdoc.Rows[pos.row_start].Range.Replace(WordTabChar + colname + WordTabChar, "", false, false);
- }
- if (dt.Rows.Count > pos.rownum)
- {
- int addrow = dt.Rows.Count - pos.rownum;
- for (int a = ; a < addrow; a++)
- {
- Aspose.Words.Node newrow = dtdoc.Rows[pos.row_start + ].Clone(true);//确认模板有第二行
- //Aspose.Words.Node newrow = dtdoc.Rows[pos.row_start].Clone(true);
- dtdoc.Rows.Insert(pos.row_start + , newrow);
- if (i < listpos.Count - )
- {
- for (int l = i + ; l < listpos.Count; l++)
- {
- PositionProChildren poscur = listpos[l - ];
- PositionProChildren posnext = listpos[l];
- if (posnext.tableindex.Equals(poscur.tableindex))
- {
- posnext.row_start += ;
- posnext.row_end += ;
- }
- else
- break;
- }
- }
- }
- }
- for (int m = ; m < dt.Rows.Count; m++)
- {
- for (int n = ; n < celltabs.Count; n++)
- {
- try
- {
- builder.MoveToSection(kk);
- //builder.MoveTo(newdoc.Sections[kk].Body.Tables[mm].Rows[pos.row_start + m].Cells[pos.cell_start + n].Paragraphs[0].Runs[0]);
- builder.MoveToCell(pos.tableindex, pos.row_start + m, pos.cell_start + n, );
- builder.Write(dt.Rows[m][celltabs[n].ToString()].ToString());
- }
- catch { }
- }
- }
- }
- //dataindex = 0;
- dataindex = dataindex + listpos.Count;
- listpos.Clear();
- }
- }
- if (!p.Equals())
- {
- newdoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
- maindoc.AppendDocument(newdoc, ImportFormatMode.KeepSourceFormatting);
- }
- else
- {
- maindoc = newdoc;
- }
- p++;
- }
- return maindoc;
- }
- public void PrintMoreMb(List<List<PrintData>> datalist)
- {
- if (datalist.Count > )
- {
- Document maindoc = printDocumentAllWordMore(datalist[]);
- Document newdoc = new Document();
- for (int i = ; i < datalist.Count; i++)
- {
- newdoc = printDocumentAllWordMore(datalist[i]);
- newdoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
- maindoc.AppendDocument(newdoc, ImportFormatMode.KeepSourceFormatting);
- }
- maindoc.Protect(ProtectionType.AllowOnlyFormFields, "mima");
- WaterMark(maindoc, HttpContext.Current.Session["LRXSMC_SH"].ToString());
- //WaterMarkMore(maindoc, HttpContext.Current.Session["LRXSMC_SH"].ToString());
- this.SaveDocument(maindoc);
- }
- }
- //public Object apply(Shape watermark)
- //{
- // watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.MARGIN);
- // watermark.setRelativeVerticalPosition(RelativeVerticalPosition.MARGIN);
- // watermark.setWrapType(WrapType.NONE);
- // // 我们需要自定义距离顶部的高度
- // // watermark.setVerticalAlignment(VerticalAlignment.TOP);
- // watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
- // // 设置距离顶部的高度
- // watermark.setTop(160);
- // return null;
- //}
- /// <summary>
- /// 插入多个水印
- /// </summary>
- /// <param name="mdoc">Document</param>
- /// <param name="wmText">水印文字名</param>
- /// <param name="left">左边距多少</param>
- /// <param name="top">上边距多少</param>
- /// <returns></returns>
- public static Shape ShapeMore(Document mdoc, string wmText, double left, double top)
- {
- Shape waterShape = new Shape(mdoc, ShapeType.TextPlainText);
- //设置该文本的水印
- waterShape.TextPath.Text = wmText;
- waterShape.TextPath.FontFamily = "宋体";
- waterShape.Width = ;
- waterShape.Height = ;
- //文本将从左下角到右上角。
- waterShape.Rotation = ;
- //绘制水印颜色
- waterShape.Fill.Color = System.Drawing.Color.Gray;//浅灰色水印
- waterShape.StrokeColor = System.Drawing.Color.Gray;
- //将水印放置在页面中心
- waterShape.Left = left;
- waterShape.Top = top;
- waterShape.WrapType = WrapType.None;
- return waterShape;
- }
- /// <summary>
- /// 插入多个水印
- /// </summary>
- /// <param name="mdoc">Document</param>
- /// <param name="wmText">水印文字名</param>
- public static void WaterMarkMore(Document mdoc, string wmText)
- {
- Paragraph watermarkPara = new Paragraph(mdoc);
- for (int j = ; j < ; j = j + )
- {
- for (int i = ; i < ; i = i + )
- {
- Shape waterShape = ShapeMore(mdoc, wmText, j, i);
- watermarkPara.AppendChild(waterShape);
- }
- }
- // 在每个部分中,最多可以有三个不同的标题,因为我们想要出现在所有页面上的水印,插入到所有标题中。
- foreach (Section sect in mdoc.Sections)
- {
- // 每个区段可能有多达三个不同的标题,因为我们希望所有页面上都有水印,将所有的头插入。
- InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary);
- InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst);
- InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven);
- }
- }
- /// <summary>
- /// 插入水印
- /// </summary>
- /// <param name="mdoc">Document</param>
- /// <param name="wmText">水印名称</param>
- public static void WaterMark(Document mdoc, string wmText)
- {
- Shape waterShape = new Shape(mdoc, ShapeType.TextPlainText);
- //设置该文本的水印
- waterShape.TextPath.Text = wmText;
- waterShape.TextPath.FontFamily = "宋体";
- waterShape.Width = ;
- waterShape.Height = ;
- //文本将从左下角到右上角。
- waterShape.Rotation = -;
- //绘制水印颜色
- waterShape.Fill.Color = System.Drawing.Color.Gray;//浅灰色水印
- waterShape.StrokeColor = System.Drawing.Color.Gray;
- //waterShape.Fill.Color = System.Drawing.Color.FromName("#DFF1DF");//浅灰色水印
- //waterShape.StrokeColor = System.Drawing.Color.Gray;
- //将水印放置在页面中心
- //waterShape.Left = 200;
- //waterShape.Top = 600;
- waterShape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
- waterShape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
- waterShape.WrapType = WrapType.None;
- waterShape.VerticalAlignment = VerticalAlignment.Center;
- waterShape.HorizontalAlignment = HorizontalAlignment.Center;
- // 创建一个新段落并在该段中添加水印。
- Paragraph watermarkPara = new Paragraph(mdoc);
- watermarkPara.AppendChild(waterShape);
- // 在每个部分中,最多可以有三个不同的标题,因为我们想要出现在所有页面上的水印,插入到所有标题中。
- foreach (Section sect in mdoc.Sections)
- {
- // 每个区段可能有多达三个不同的标题,因为我们希望所有页面上都有水印,将所有的头插入。
- InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary);
- InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst);
- InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven);
- }
- }
- private static void InsertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, HeaderFooterType headerType)
- {
- HeaderFooter header = sect.HeadersFooters[headerType];
- if (header == null)
- {
- // 当前节中没有指定类型的头,创建它
- header = new HeaderFooter(sect.Document, headerType);
- sect.HeadersFooters.Add(header);
- }
- // 在头部插入一个水印的克隆
- header.AppendChild(watermarkPara.Clone(true));
- }
- #endregion
- }
- public class ReplaceText : IReplacingCallback
- {
- /// <summary>
- /// 替换文本格式
- /// </summary>
- public string Text { get; set; }
- public ReplaceText(string Text)
- {
- this.Text = Text;
- }
- public ReplaceAction Replacing(ReplacingArgs e)
- {
- //获取当前节点
- var node = e.MatchNode;
- Document doc = node.Document as Document;
- DocumentBuilder builder = new DocumentBuilder(doc);
- builder.MoveTo(node);
- builder.Write(Text);
- return ReplaceAction.Replace;
- }
- }
- public class ReplaceHtml : IReplacingCallback
- {
- /// <summary>
- /// 替换为html格式
- /// </summary>
- public string Text { get; set; }
- public ReplaceHtml(string Text)
- {
- this.Text = Text;
- }
- public ReplaceAction Replacing(ReplacingArgs e)
- {
- //获取当前节点
- var node = e.MatchNode;
- Document doc = node.Document as Document;
- DocumentBuilder builder = new DocumentBuilder(doc);
- builder.MoveTo(node);
- builder.InsertHtml(Text);
- return ReplaceAction.Replace;
- }
- }
- public class ReplaceImage : IReplacingCallback
- {
- /// <summary>
- /// 替换图片
- /// </summary>
- public string ImageUrl { get; set; }
- //
- public ReplaceImage(string url)
- {
- this.ImageUrl = url;
- }
- public ReplaceAction Replacing(ReplacingArgs e)
- {
- //获取当前节点
- if (!string.IsNullOrEmpty(ImageUrl))
- {
- var node = e.MatchNode;
- Document doc = node.Document as Document;
- DocumentBuilder builder = new DocumentBuilder(doc);
- builder.MoveTo(node);
- //builder.Write(Text);
- Shape shape = new Shape(doc, ShapeType.Image);
- shape.ImageData.SetImage(ImageUrl);
- shape.Top = ;
- shape.Width = ;
- shape.Height = ;
- shape.HorizontalAlignment = HorizontalAlignment.Center;
- CompositeNode node1 = shape.ParentNode;
- builder.InsertNode(shape);
- }
- return ReplaceAction.Replace;
- }
- }
- public class PositionPro
- {
- public string key { get; set; }
- public int row_start { get; set; }
- public int row_end { get; set; }
- public int cell_start { get; set; }
- public int cell_end { get; set; }
- public int rownum
- {
- get
- {
- return row_end - row_start + ;
- }
- }
- }
- public class PrintData
- {
- public List<DataTable> dtinfos;
- public Dictionary<string, string> dict;
- public List<DataTable> dtlist;
- public string wordpath;
- }
- public class PositionProChildren
- {
- public int tableindex { get; set; }
- public string key { get; set; }
- public int row_start { get; set; }
- public int row_end { get; set; }
- public int cell_start { get; set; }
- public int cell_end { get; set; }
- public int rownum
- {
- get
- {
- return row_end - row_start + ;
- }
- }
- }
- }
ASP.NET基于Aspose.Words插入Word水印以及多个水印的更多相关文章
- Aspose.Words给word文档加水印
需求:在一些重要的Word文档需要打印时,添加水印以明出处. 方案:使用Aspose组件给word文档 代码:干货如下 /// <summary> /// Inserts a waterm ...
- Aspose.Words操作word生成PDF文档
Aspose.Words操作word生成PDF文档 using Aspose.Words; using System; using System.Collections.Generic; using ...
- WPF使用Aspose.Words导出Word文档
一.创建Word文档模板 分析需要导出的word文档,将固定的内容和由程序生成的内容分开; 创建一个word(例如:Template.doc)文档,将固定的内容按照一定的格式写入当前文档中; 打开Te ...
- asp.net基于windows服务实现定时发送邮件的方法
本文实例讲述了asp.net基于windows服务实现定时发送邮件的方法.分享给大家供大家参考,具体如下: //定义组件 private System.Timers.Timer time; publi ...
- c# Aspose.Words插入饼图PieChart
private static void Main(string[] args) { Document doc = new Document(); DocumentBuilder builder = n ...
- 解决图片插入word文档后清晰度降低的问题
解决图片插入word文档后清晰度降低的问题 在默认情况下,word程序会自动压缩插入word文档中的图片以减小整个word文档的.当我们需要插入word文档中的图片保持原始清晰度时,可以通过设置wor ...
- Java 在Excel中添加水印(单一水印、平铺水印)
在Excel中没有直接添加水印的功能,但依旧可以通过一定方式来实现类似水印效果.本文通过Java程序代码介绍具体实现方法.可添加单一水印效果,即水印是以单个文本字样来呈现:也可添加多个平铺水印效果,即 ...
- php文字水印和php图片水印实现代码
本文章向码农们介绍php文字水印和php图片水印实现代码,需要的码农可以参考一下. php 文字水印 文字水印就是在图片上加上文字,主要使用gd库的imagefttext方法,并且需要字体文件. 实现 ...
- Aspose.Words进行Word替换(插入图片和水印)
由于最近一直在忙着做着Word打印模板的一些工作,就整理一些Asponse.Words对Word文档进行操作的资料. using System; using System.Collections.Ge ...
随机推荐
- centos7上安装rar解压软件
(http://www.rarlab.com)官网可以查看最新的版本 wget https://www.rarlab.com/rar/rarlinux-x64-5.5.0.tar.gz 2.tar.g ...
- leetcode303
public class NumArray { List<int> list = new List<int>(); public NumArray(int[] nums) { ...
- delphi XE8 NetHTTPRequest NetHTTPClient
delphi xe8 推出2个新http控件,NetHTTPRequest.NetHTTPClient 可以调用ASP.Net 一般应用程序获取网页数据,用旧的控件idhttp控件也可以,推荐用新的这 ...
- MyBatis 查询缓存
增删改操作对一级缓存的影响:增删改操作都会清空一级缓存,无论是否提交
- ajax传参里含有特殊字符的坑
问题场景:今天在测试自己手上的页面功能时,发现一个小bug,在用ajax向后台发数据时,只要参数中出现一些特殊字符,控制台会报错http 400的问题,其实就是特殊字符服务器不能解析.好了,问题是找到 ...
- Spring Cloud Config配置中心的使用
一.概述 1. 为什么使用? 1> 配置文件太多,不方便维护 2> 配置文件一般都保存这各种明文显示的密码,无法保证配置内容的安全性,也无法做到按权限分配给个人 3> 更新配置项目需 ...
- 在Ubuntu16.04中安装Docker CE
apt-get install apt-transport-https ca-certificates curl software-properties-common curl -fsSL https ...
- java.lang.VerifyError: Inconsistent stackmap frames at branch target 81
java项目中有如下代码: @RequestMapping(value = "/getMxList") @ResponseBody public Map<String, Ob ...
- 01b-1: 性能测度
- MongoDB 自动分片 auto sharding
MongoDB部署实验系列文章 MongoDB做为NoSQL数据库,最近几年持续升温,越来越多的企业都开始尝试用MongoDB代替原有Database做一些事情.MongoDB也在集群,分片,复制上也 ...