C# 借助Aspose在没有Office的电脑上用Word模板生成Word文档并调用打印功能
----------------------------仅作为个人学习记录----------------------------
首先需要创建一个Word作为模板使用。
- 创建Word,并调整内容。
- 在需要插入数据的地方点击 【插入-文档部件-域-选择MergeField-输入域名-点击确定】
- 将文件保存好等待使用。
下面直接上代码,这是我封装好的一个工具类(虽说是封装好,但是目前仅作为Demo ,不建议直接拿到生产环境)
using Aspose.Words;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Demo_WordPrint
{
/// <summary>
/// 打印助手类
/// </summary>
public class PrintHelper
{
/// <summary>
/// 根据模板打印word
/// </summary>
/// <param name="TemplatePath">模板路径(相对)</param>
/// <param name="Fields">插入的字段</param>
/// <param name="Images">插入的图片</param>
public static void PrintWord_ByTemplate(string TemplatePath, Dictionary<string, object> Fields, Dictionary<string, WordImage> Images = null)
{
//获取当前程序目录
string appStartPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
string[] fieldNames = new string[Fields.Count];
object[] fieldValues = new object[Fields.Count];
//将字段的字典集合转为两个数组
int i = 0;
foreach (var item in Fields)
{
fieldNames[i] = item.Key;
fieldValues[i] = item.Value;
i++;
}
//生成文件名
string fileName = Guid.NewGuid().ToString() + ".docx";
//临时文件存储目录
var ouputPath = appStartPath + "/PrintTemp/";
//临时文件路径
string ouputFile = ouputPath + fileName;
//检查文件夹是否存在
if (!System.IO.Directory.Exists(ouputPath))
{
System.IO.Directory.CreateDirectory(ouputPath);
}
//创建对象
Document doc = new Document(appStartPath + TemplatePath);
//插入图片
if (null != Images)
{
foreach (var item in Images)
{
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToMergeField(item.Key);
builder.InsertImage(item.Value.Image, item.Value.ImageWidth, item.Value.ImageHeight);
}
}
//合并模版
doc.MailMerge.Execute(fieldNames, fieldValues);
//保存
doc.Save(ouputFile);
//打印
doc.Print();
}
}
/// <summary>
/// Word中图片替换模型
/// </summary>
public class WordImage
{
public Image Image { get; set; }
public int ImageWidth { get; set; }
public int ImageHeight { get; set; }
}
}
需要Demo的可以 Goto https://github.com/hongzhuoxx/Demo_WordPrint
Deme比较简陋,轻喷。