一、制作word模板

 1、插入文档部件,用于替换文档中固定字段

 

 

 

 

 

 插入文档部件效果

 

 

2、插入书签

 

 要先在文档中设置标签可见(文件--选项--高级--勾选显示书签),才能看到插入标签效果

 

二、获取模板

 private string _templatePath = ""; //模板路径
 private object _filePath = ""; //生成中间文档路径
 private string _savePath = ""; //保存生成文档路径
 private object _missing = System.Reflection.Missing.Value;

 File.Copy(_templatePath.ToString(), _savePath.ToString(), true); //将文件复制到结果文档中
 var doc = new Document(_savePath);
 var builder = new DocumentBuilder(doc);
 doc.Save(_savePath);//保存文档

三、替换文档中域文字

 while (builder.MoveToMergeField("companyName"))
       {
          builder.Write("文档编辑"); //替换公司名称
       }

四、跳转指定书签位置

 var bookmark = doc.Range.Bookmarks["position"];
   bookmark2.Text = "";//替换掉书签名称
builder.MoveToBookmark("position");//跳转指定书签
builder.Write("跳转到书签写了一段话");

 

五、段落设置

插入Html代码,可设置文档标题(1-6号标题均可),有一些弊端:某些Html代码不识别

 builder.InsertHtml("<h3>标题3</h3>");

 设置段落对齐方式

builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; //水平居中对齐
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left; //平居左对齐
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right; //平居右对齐

段落字号、加粗

builder.Font.Size = 12;//字体12磅
builder.Bold = true;//字体加粗
builder.Writeln("字体12磅,加粗");
 builder.Bold = false;

插入图片

builder.InsertImage(pictureUrl, RelativeHorizontalPosition.Page, 10, RelativeVerticalPosition.Margin, 5, 400, 100, WrapType.None);//pictureUrl图片路径

 插入分页

 builder.InsertBreak(BreakType.PageBreak); //插入分页

 

posted on 2019-09-25 18:21  name_小柒  阅读(2400)  评论(0编辑  收藏  举报