在日常工作中,我们可能常常需要打印各种文件资料,比如word文档。对于编程员,应用程序中文档的打印是一项非常重要的功能,也一直是一个非常复杂的工作。可以通过调用打印对话框(PrintDialog)来进行相关打印设置,也可以通过静默打印方式直接打印Word文档。一般如果要想选择非默认打印机或者说想显示打印设置对话框时,我们也需要对代码进行一定的设置。
; w% c" b" ~; b4 s/ y/ t实现方法:5 Y7 v, B# M5 C; W7 x
1、系统安装 Office,可以是微软的Office,也可以是wps。+ C+ a4 E1 e2 x/ I) F
2、实现方法代码 ! Y; s" [( L9 @2 N
- 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;
- }
- }
|