Aspose.Words进行Word替换(插入图片和水印)
由于最近一直在忙着做着Word打印模板的一些工作,就整理一些Asponse.Words对Word文档进行操作的资料。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using Aspose.Words;
using Aspose.Words.Drawing;
using System.IO;
using System.Drawing; namespace ASPONSE_Words
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("开始进行操作");
DataTable dt = new DataTable();
dt.Columns.Add("title", typeof(string));
dt.Columns.Add("xm", typeof(string));
dt.Columns.Add("xb", typeof(string));
dt.Columns.Add("mz", typeof(string));
dt.Columns.Add("nl", typeof(string));
dt.Columns.Add("Photo1", typeof(string));
dt.Columns.Add("Photo2", typeof(string));
dt.Columns.Add("Photo3", typeof(string));
dt.Columns.Add("Photo4", typeof(string));
DataRow dr = dt.NewRow();
dr["title"] = "测试";
dr["xm"] = "华哥\n无敌";
dr["xb"] = "男神";
dr["mz"] = "汉族";
dr["nl"] = "";
dr["Photo1"] = "../File/1.jpg";
dr["Photo2"] = "../File/2.jpg";
dr["Photo3"] = "../File/3.jpg";
dr["Photo4"] = "../File/4.jpg";
dt.Rows.Add(dr);
var fileUrl = "../File/test11.doc";
try
{
Print(fileUrl, dt);
Console.WriteLine("替换成功");
}
catch (Exception)
{
Console.WriteLine("替换失败");
} Console.ReadKey();
} public static void Print(string fileurl, DataTable dtInfo)
{
Document doc = new Document(fileurl);
if (dtInfo != null && dtInfo.Rows.Count > )
{
var dr = dtInfo.Rows[];
foreach (DataColumn dc in dtInfo.Columns)
{
var nValue = dr[dc.ColumnName] + "";
try
{
if (dc.ColumnName.Contains("Photo"))
{
if (File.Exists(nValue))
{
Regex reg = new Regex("#" + dc.ColumnName + "#");
doc.Range.Replace(reg, new ReplaceImage2(nValue), false);
}
}
else {
if (nValue.Contains("\n"))
{
doc.Range.Replace("$" + dc.ColumnName + "$", "#" + dc.ColumnName + "#", false, false);
Regex reg = new Regex("#" + dc.ColumnName + "#");
doc.Range.Replace(reg,new ReplaceHtml(nValue),false);
}
else doc.Range.Replace("$" + dc.ColumnName + "$", nValue, false, false);
}
}
catch (Exception ex)
{
throw ex;
}
}
}
WaterMark(doc, "华哥无敌");
doc.Save("huage.doc");
} 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 = Color.Gray;//浅灰色水印
waterShape.StrokeColor = Color.Gray;
//将水印放置在页面中心
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));
}
} public class ReplaceImage1 : IReplacingCallback
{
public string imageUrl;
public string Barcode; public ReplaceImage1(string url)
{
this.imageUrl = url;
} public ReplaceAction Replacing(ReplacingArgs e)
{
//获取当前节点
var node = e.MatchNode;
//获取当前文档
Document doc = node.Document as Document;
DocumentBuilder builder = new DocumentBuilder(doc);
//将光标移动到指定节点
builder.MoveTo(node);
//插入图片
builder.InsertImage(imageUrl);
return ReplaceAction.Replace;
} } public class ReplaceImage2 : IReplacingCallback
{
public string imageUrl;
public string Barcode; public ReplaceImage2(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);
Shape shape = new Shape(doc, ShapeType.Image);
shape.ImageData.SetImage(imageUrl);
shape.Width = ;
shape.Height = ;
shape.DistanceTop = ;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.VerticalAlignment = VerticalAlignment.Center;
builder.InsertNode(shape);
}
return ReplaceAction.Replace;
} } public class ReplaceHtml : IReplacingCallback
{
public string Text ; public ReplaceHtml(string str)
{
this.Text = str;
} public ReplaceAction Replacing(ReplacingArgs e)
{
//获取当前节点
if (!string.IsNullOrEmpty(Text))
{
Node node = e.MatchNode;
Document doc = node.Document as Document;
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveTo(node);
builder.Write(Text);
}
return ReplaceAction.Replace;
} }
}
模板:

效果图:

Aspose.Words进行Word替换(插入图片和水印)的更多相关文章
- Java利用poi生成word(包含插入图片,动态表格,行合并)
转(小改): Java利用poi生成word(包含插入图片,动态表格,行合并) 2018年12月20日 09:06:51 wjw_11093010 阅读数:70 Java利用poi生成word(包含插 ...
- OpenXml入门---word里面插入图片
下面介绍如何在word里面插入图片,顺便小弟发现MSDN官网有完整的OpenXML教程,虽然是全英文的不过还是很有帮助的. Tips,原来摘抄代码里面没有模板,在copy过来发现插入word中的图片大 ...
- 在word里插入图片,并设置图片的格式
由于公司业务需要,需要在生成的word里插入图片(公司印章),仔细想了下,还是在word模板里添加一个书签,然后再该书签的位置插入图片,并设置图片的格式方便些: 代码如下: using System; ...
- 如何在Microsoft Word里面插入图片作为背景/封面?
Stay hungry, Stay foolish. 如何在Word里面插入图片作为背景?其实很简单,开门见山,我们只需要这几步即可! 1.第一步,打开要插入图片的Word 2.第二步,插入图 ...
- .net使用Aspose.Words进行Word替换操作的实现代码
DLL文件下载 示例: Aspose.Words.Document doc = new Aspose.Words.Document(TempFile); Aspose.Words.DocumentBu ...
- C#调用NPOI组件读取excel表格数据转为datatable写入word表格中并向word中插入图片/文字/书签 获得书签列表
调用word的com组件将400条数据导入word表格中耗时10分钟简直不能忍受,使用NPOI组件耗时4秒钟.但是NPOI中替换书签内容的功能不知道是不支持还是没找到. 辅助类 Excel表格数据与D ...
- C#中按模板操作Word —— 如何向Word中插入图片
一.Word对象模型的重叠性分析 本文主要介绍通过书签Bookmark向Word文档中插入图片的方法.在此之前我们先简单讨论下Word对象模型的重叠性.如果你对Word对象模型还不熟悉,请参考本专栏第 ...
- C#操作word之插入图片
假如我们导出一份简历到word文档,那势必可能要同时导出我们包含的简历,下面就来试一下如何和通过C#代码,将图片插入到word文档中. 为了简便起见,就简单一点.类似下面这样的 姓名 张三 照片 ...
- Aspose.Words操作Word.PDF,让图片和文本垂直居中,水平居中解决方案
x 环境 { "Aspose.Words": {"Version":"18.x"} } 需求与难题 生成试卷的时候,如果数学题目中有特殊符号 ...
随机推荐
- ubuntu 16.04 安装QT问题
使用 sudo sh ./**.run 有错误: 增加 文件的可运行权限: sudo chmod +x Qt.run 直接运行: ./Qt.run 可完成安装
- layui confirm
layer.confirm('是否要删除信息!', { btn: ['确定', '取消'] }, function (index, layero) { //移除元素 $("#tr" ...
- Swiper 3D flow轮播使用方法
swiper 的3d轮播效果,移动端适用 (1). 如需使用Swiper的3d切换首先加载3D flow插件(js和css). <head> <link rel="styl ...
- drf05 路由Routers
对于视图集ViewSet,我们除了可以自己手动指明请求方式与动作action之间的对应关系外,还可以使用Routers来帮助我们快速实现路由信息. REST framework提供了两个router ...
- C#调用存储过程中事务级临时表返回DataTable列乱序解决办法
string result = strSqlResult.Substring(3).Trim().Replace("\n", "").Replace(" ...
- BZOJ 1715: [Usaco2006 Dec]Wormholes 虫洞 DFS版SPFA判负环
Description John在他的农场中闲逛时发现了许多虫洞.虫洞可以看作一条十分奇特的有向边,并可以使你返回到过去的一个时刻(相对你进入虫洞之前).John的每个农场有M条小路(无向边)连接着N ...
- sql server安装出现的一点小问题
- 【剑指Offer】26、二叉搜索树与双向链表
题目描述: 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表.要求不能创建任何新的结点,只能调整树中结点指针的指向. 解题思路: 首先要理解此题目的含义,在双向链表中,每个结 ...
- [luogu4158 SCOI2009] 粉刷匠(dp)
传送门 Solution 把状态都记上暴力转移即可 Code //By Menteur_Hxy #include <queue> #include <cmath> #inclu ...
- AtCoder ABC 070D - Transit Tree Path
传送门:http://abc070.contest.atcoder.jp/tasks/abc070_d 本题是一个图论问题——树(Tree). 有一棵结点数目为n的无向树.第i条边连接结点ai与bi, ...