/xiachufeng/archive//07/31/1789136.html
打印,是做开发的人的经久不变的话题。
今天,用实例代码,说明.NET是如何打印WORD、EXCEL等OFFICE文件,以及PDF文件的。
采用指定的打印机打印OFFICE文件
此方法又分为 “显示相应的程序窗口” 和 “不显示相应的程序窗口”两种方式。
(1)显示WORD、EXCEL等程序窗口
采用操作系统自身的自动识别模式的打印,此方法实际适用于N多种文件,并不限于WORD,EXCEL,PDF之类的,但是这种方法,有一个缺陷,就是:对于某些类型的文档,如WORD,EXCEL,PDF等,打印时,会有相应的程序窗口一闪而过。
实现代码如下:
System.Diagnostics.Process p = new System.Diagnostics.Process();//不现实调用程序窗口,但是对于某些应用无效p.StartInfo.CreateNoWindow = true;p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;//采用操作系统自动识别的模式p.StartInfo.UseShellExecute = true;//要打印的文件路径,可以是WORD,EXCEL,PDF,TXT等等p.StartInfo.FileName = @"d:\a.doc";//指定执行的动作,是打印,即print,打开是 openp.StartInfo.Verb = "print";//开始p.Start();
此种方法,代码简单,性能好,可靠稳定。此种方式,如果要指定打印机,则只能利用设置默认打印机的方式来实现。
C#设置系统默认打印机的实现方法,见 “C#获取和设置系统的默认打印机” 一文
添加了指定打印机功能的代码如下:
System.Diagnostics.Process p = new System.Diagnostics.Process();//不现实调用程序窗口,但是对于某些应用无效p.StartInfo.CreateNoWindow = true;p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;//采用操作系统自动识别的模式p.StartInfo.UseShellExecute = true;//要打印的文件路径p.StartInfo.FileName = @"d:\a.doc";//指定执行的动作,是打印,即print,打开是 openp.StartInfo.Verb = "print";//获取当前默认打印机//string defaultPrinter = GetDefaultPrinter();//将指定的打印机设为默认打印机SetDefaultPrinter("指定的打印机");//开始打印p.Start();//等待十秒p.WaitForExit(10000);//将默认打印机还原SetDefaultPrinter(defaultPrinter);
(2)不显示WORD、EXCEL等程序窗口
此种方式,使用.NET调用COM的方式来实现,利用COM对象本身的特性来设置可见性和打印机
使用此方法前,需要先添加Office的COM引用,这里略过。
//要打印的文件路径object wordFile = @"d:\a.doc";object oMissing = Missing.Value;//自定义object类型的布尔值object oTrue = true;object oFalse = false;object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;//定义WORD Application相关Word.Application appWord = new Word.Application();//WORD程序不可见appWord.Visible = false;//不弹出警告框appWord.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; //先保存默认的打印机string defaultPrinter = appWord.ActivePrinter;//打开要打印的文件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);//设置指定的打印机appWord.ActivePrinter = "指定打印机的名字";//打印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;
此方法,于COM交互,性能有些损失,要注意COM对象的释放,以及异常控制,此处忽略。