第一步 :添加Nuget引用 FreeSpire.Doc
第二部:添加如下代码
using Spire.Doc;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApp1
{
///
/// Word文档抽象类
///
public abstract class WordProtocol
{
#region 属性
///
/// 协议模板路径
///
public string ProtocolPath { get; set; }
///
/// 协议保存文件名
///
public string SaveFileName { get; set; }
///
/// Word文档对象
///
public Document Doc { get; set; }
///
/// 模板字符
///
public List TemplateStrings { get; set; }
#endregion
///
/// 协议内容替换准备
///
public virtual void Ready()
{
if (File.Exists(ProtocolPath) == false)
{
return;
}
Doc = new Document();
Doc.LoadFromFile(ProtocolPath);
}
///
/// 协议内容替换中(业务抽象方法)
///
public abstract void BizReplace();
///
/// 协议替换完成
///
public virtual void Finish()
{
//不允许任何更改(只读),设置解除限制编辑的密码
Doc.Protect(ProtectionType.AllowOnlyReading, "123");
Doc.SaveToFile(SaveFileName, FileFormat.Doc);
Doc.Close();
}
///
/// 模板方法
///
public void Run()
{
Ready();
BizReplace();
Finish();
}
}
}
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;
using System.Drawing;
namespace ConsoleApp1
{
public class PaymentNoticeProtocol : WordProtocol
{
///
/// 图片路径
///
public string ImagePath { get; set; }
public PaymentNoticeProtocol(string imagePath)
{
this.ImagePath = imagePath;
}
///
/// 替换内容业务
///
public override void BizReplace()
{
foreach (string item in TemplateStrings)
{
//设置查找的文本
string newStr = "";
switch (item.Trim())
{
case "[打印年]":
newStr = string.Format("{0}", DateTime.Now.ToString("yyyy"));
break;
case "[打印月]":
newStr = string.Format("{0}", DateTime.Now.ToString("MM"));
break;
case "[打印日]":
newStr = string.Format("{0}", DateTime.Now.ToString("dd"));
break;
}
TextSelection selection = Doc.FindString(item.Trim(), false, true);
TextRange range = selection.GetAsOneRange();
//替换的文本
range.Text = newStr;
}
AddPicture();
}
private void AddPicture()
{
//从文档的第一个段落添加
Paragraph para = Doc.Sections[0].Paragraphs[0];
var image = Image.FromFile(ImagePath);
DocPicture picture = para.AppendPicture(image);
//设置图片大小
picture.Width = 100f;
picture.Height =50f;
para.AppendHyperlink("www.baidu.com", picture, HyperlinkType.WebLink);
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string basePath = AppDomain.CurrentDomain.BaseDirectory;
string path = basePath + "Template\\交费通知单.doc";
WordProtocol protocol = new PaymentNoticeProtocol(basePath + "Images\\bd_logo1.png")
{
ProtocolPath = path,
SaveFileName = "demo.doc",
TemplateStrings=new List { "[打印年]", "[打印月]", "[打印日]" }
};
protocol.Run();
OpenPreviewFile(AppDomain.CurrentDomain.BaseDirectory+protocol.SaveFileName);
}
///
/// 默认打开替换后的文件
///
///
private static void OpenPreviewFile(string path)
{
if (File.Exists(path) == false)
{
return;
}
Process.Start(path);
}
}
}
第三步: 添加一个word模板和一个图片
第四步:效果图:
参考资料:
Spire.Doc英文官网及帮助文档
Spire.Doc 中文帮助文档
源代码地址