首页 > 数据库 > 数据库开发技术 > C# 打印Word文档
在日常工作中,我们可能常常需要打印各种文件资料,比如word文档。对于编程员,应用程序中文档的打印是一项非常重要的功能,也一直是一个非常复杂的工作。
可以通过调用打印对话框(PrintDialog)来进行相关打印设置,也可以通过静默打印方式直接打印Word文档。
一般如果要想选择非默认打印机或者说想显示打印设置对话框时,我们也需要对代码进行一定的设置。
下面看下如何静默打印word文档
实现方法
1、系统安装 Office 可以是微软的Office 也可以是wps
2、实现方法代码
public bool PrintDoc(){try{//要打印的文件路径object wordFile = Directory.GetCurrentDirectory() + "/0.doc";object oMissing = Missing.Value;//自定义object类型的布尔值object oTrue = true;object oFalse = false;object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;//定义WORD Application相关Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();//WORD程序不可见appWord.Visible = false;//不弹出警告框appWord.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;//先保存默认的打印机string defaultPrinter = appWord.ActivePrinter;//打开要打印的文件Microsoft.Office.Interop.Word.Document doc = appWord.Documents.Open(ref wordFile,ref oMissing,ref oTrue,ref oFalse,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing);PrintDocument print = new PrintDocument();string sDefault = print.PrinterSettings.PrinterName;//默认打印机名//List<string> printList = new List<string>();//foreach (string sPrint in PrinterSettings.InstalledPrinters)//获取所有打印机名称//{// printList.Add(sPrint);//}//设置指定的打印机appWord.ActivePrinter = sDefault;//打印doc.PrintOut(ref oTrue, //此处为true,表示后台打印ref oFalse,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing);//打印完关闭WORD文件doc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);//还原原来的默认打印机appWord.ActivePrinter = defaultPrinter;//退出WORD程序appWord.Quit(ref oMissing, ref oMissing, ref oMissing);doc = null;appWord = null;return true;}catch (Exception e){// MessageBox.Show(e.ToString());return false;}}
原文作者:后端Q;如有侵权,请联系管理员删除。