实现动态添加数据打印word预览
/// <summary>
/// 实现动态添加数据打印预览
/// </summary>
/// <param name="path">word模板路径</param>
/// <param name="pathprint">word打印路径</param>
public void PrintPreview(string path, string pathprint)
{
WordApplication word = null;
Document doc = null;
Document printDoc = null;
object oMissing = System.Reflection.Missing.Value;
object oMissing2 = System.Reflection.Missing.Value;
if (word == null)
{
word = new WordApplication();
}
object path1 = (object)path;
object path2 = (object)pathprint;
doc = word.Documents.OpenOld(ref path1, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
printDoc = word.Documents.OpenOld(ref path2, ref oMissing2, ref oMissing2, ref oMissing2, ref oMissing2, ref oMissing2, ref oMissing2, ref oMissing2, ref oMissing2, ref oMissing2);
printDoc.Content.Text = null;//清空word打印
doc.Content.Copy(); //复制doc里的内容,doc是每次做替换书签的文档.
object save = false;
doc.Close(ref save, ref oMissing, ref oMissing); //关闭doc.
Range range = printDoc.Content; //全中printDoc里的全部内容,printDoc是目标保存文档.
range.Collapse(ref oMissing);
range.Paste();
try
{
#region 替换书签
foreach (Bookmark BM in printDoc.Bookmarks)
{
switch (BM.Name)
{
case "姓名":
BM.Select();
BM.Range.Text = "xxxxxx";
break;
case "性别":
BM.Select();
BM.Range.Text = "男";
break;
}
}
#endregion
word.Visible = true;
printDoc.PrintPreview();
}
catch (Exception ex)
{
object save2 = false;
printDoc.Close(ref save2, ref oMissing2, ref oMissing2); //关闭doc.
MessageBox.Show(ex.Message.ToString());
}
}