C# Word 打印

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 using Microsoft.Office.Interop.Word;
  7 using System.Runtime.InteropServices;
  8 using System.ComponentModel;
  9 using System.Management;
 10 using System.IO;
 11 using System.Reflection;
 12 
 13 namespace WordPrint_Test
 14 {
 15     public class WordPrintHelper
 16     {
 17         /// <summary>
 18         /// 打印word
 19         /// </summary>
 20         /// <param name="filepath">word文件路径</param>
 21         /// <param name="printername">指定的打印机</param>
 22         public void Printword(string filepath, string printername)
 23         {
 24             //filepath=@"d:.doc";
 25             //printername = "Microsoft XPS Document Writer";
 26             try
 27             {
 28                 System.Diagnostics.Process p = new System.Diagnostics.Process();
 29                 //不现实调用程序窗口,但是对于某些应用无效
 30                 p.StartInfo.CreateNoWindow = true;
 31                 p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
 32 
 33                 //采用操作系统自动识别的模式
 34                 p.StartInfo.UseShellExecute = true;
 35 
 36                 //要打印的文件路径
 37                 p.StartInfo.FileName = filepath;
 38                 ////Help help = new Help();
 39                 ////help.LogMessage(filepath + "---------" + printername);
 40                 //指定执行的动作,是打印,即print,打开是 open
 41                 p.StartInfo.Verb = "open"; //print
 42 
 43                 //获取当前默认打印机
 44 
 45                 string defaultPrinter = GetDefaultPrinter();
 46 
 47                 //将指定的打印机设为默认打印机
 48                 SetDefaultPrinter(printername);
 49 
 50                 //开始打印
 51                 p.Start();
 52 
 53                 //等待十秒
 54                 p.WaitForExit(10000);
 55 
 56                 //将默认打印机还原
 57                 SetDefaultPrinter(defaultPrinter);
 58             }
 59             catch (Exception ex)
 60             {
 61                 //help.LogMessage(filepath + "----" + printername + "-------" + ex.Message);
 62             }
 63 
 64         }
 65         [DllImport("Winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
 66         private static extern bool SetDefaultPrinter(string printerName);
 67 
 68         [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
 69 
 70         private static extern bool GetDefaultPrinter(StringBuilder pszBuffer, ref int pcchBuffer);
 71         /// <summary>
 72         /// 获取默认的打印机
 73         /// </summary>
 74         /// <returns></returns>
 75         static string GetDefaultPrinter()
 76         {
 77             const int ERROR_FILE_NOT_FOUND = 2;
 78 
 79             const int ERROR_INSUFFICIENT_BUFFER = 122;
 80 
 81             int pcchBuffer = 0;
 82 
 83             if (GetDefaultPrinter(null, ref pcchBuffer))
 84             {
 85                 return null;
 86             }
 87 
 88             int lastWin32Error = Marshal.GetLastWin32Error();
 89 
 90             if (lastWin32Error == ERROR_INSUFFICIENT_BUFFER)
 91             {
 92                 StringBuilder pszBuffer = new StringBuilder(pcchBuffer);
 93                 if (GetDefaultPrinter(pszBuffer, ref pcchBuffer))
 94                 {
 95                     return pszBuffer.ToString();
 96                 }
 97 
 98                 lastWin32Error = Marshal.GetLastWin32Error();
 99             }
100             if (lastWin32Error == ERROR_FILE_NOT_FOUND)
101             {
102                 return null;
103             }
104 
105             throw new Win32Exception(Marshal.GetLastWin32Error());
106 
107 
108         }
109 
110         ///打印页面不会闪动
111         public void PrintMethodOther(string filepath, string printername)
112         {
113             try
114             {
115                 object wordFile = filepath;
116                 //@"d:.doc";
117                 object oMissing = Missing.Value;
118                 //自定义object类型的布尔值
119                 object oTrue = true;
120                 object oFalse = false;
121 
122                 object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
123 
124                 //定义WORD Application相关
125 
126                 Application appWord = new Application();
127 
128                 //WORD程序不可见
129                 appWord.Visible = false;
130                 //不弹出警告框
131                 appWord.DisplayAlerts = WdAlertLevel.wdAlertsNone;
132 
133                 //先保存默认的打印机
134                 string defaultPrinter = appWord.ActivePrinter;
135 
136                 //打开要打印的文件
137                 //如果在其它函数调用中出错(doc为null),处理办法:建立临时文件夹,还要设置服务的权限属性
138                 Document doc = appWord.Documents.Open(
139                         ref wordFile,
140                         ref oMissing,
141                         ref oTrue,
142                         ref oFalse,
143                         ref oMissing,
144                         ref oMissing,
145                         ref oMissing,
146                         ref oMissing,
147                         ref oMissing,
148                         ref oMissing,
149                         ref oMissing,
150                         ref oMissing,
151                         ref oMissing,
152                         ref oMissing,
153                         ref oMissing,
154                         ref oMissing);
155 
156                 //设置指定的打印机
157                 appWord.ActivePrinter = printername;
158                 //"Microsoft XPS Document Writer";
159 
160                 //打印
161 
162                 doc.PrintOut(
163                     ref oTrue, //此处为true,表示后台打印
164                     ref oFalse,
165                     ref oMissing,
166                     ref oMissing,
167                     ref oMissing,
168                     ref oMissing,
169                     ref oMissing,
170                     ref oMissing,
171                     ref oMissing,
172                     ref oMissing,
173                     ref oMissing,
174                     ref oMissing,
175                     ref oMissing,
176                     ref oMissing,
177                     ref oMissing,
178                     ref oMissing,
179                     ref oMissing,
180                     ref oMissing
181                     );
182 
183                 //打印完关闭WORD文件
184                 doc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
185 
186                 //还原原来的默认打印机
187                 appWord.ActivePrinter = defaultPrinter;
188 
189                 //退出WORD程序
190                 appWord.Quit(ref oMissing, ref oMissing, ref oMissing);
191 
192                 doc = null;
193                 appWord = null;
194             }
195             catch (Exception ex)
196             {
197                 ////help.LogMessage(filepath + "----" + printername + "-------" + ex.Message);
198             }
199         }
200 
201 
202         //// <summary>
203         ///解决 word调用打印机报错问题,创建一个临时文件夹
204         /// </summary>
205         /// <returns></returns>
206         public bool CreateFolder()
207         {
208             bool ifsuccesss = false;
209             try
210             {
211                 string systempath = System.Environment.GetFolderPath(Environment.SpecialFolder.System);
212                 string fullpath = string.Empty;
213                 if (FindSystemWidth() == "32")
214                 {
215                     fullpath = systempath + "\config\systemprofile\Desktop";
216                 }
217                 else
218                 {
219                     fullpath = systempath + "\config\systemprofile\Desktop";
220                 }
221                 if (!Directory.Exists(fullpath))
222                 {
223                     Directory.CreateDirectory(fullpath);
224                 }
225                 ifsuccesss = true;
226             }
227             catch (Exception ex)
228             {
229                 ifsuccesss = false;
230             }
231             return ifsuccesss;
232 
233         }
234 
235         /// <summary>
236         /// 获取系统的位数
237         /// </summary>
238         /// <returns></returns>
239         public string FindSystemWidth()
240         {
241             ConnectionOptions oConn = new ConnectionOptions();
242             System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\localhost", oConn);
243             System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select AddressWidth from Win32_Processor");
244             ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
245             ManagementObjectCollection oReturnCollection = oSearcher.Get();
246             string addressWidth = null;
247 
248             foreach (ManagementObject oReturn in oReturnCollection)
249             {
250                 addressWidth = oReturn["AddressWidth"].ToString();
251             }
252 
253             return addressWidth;
254         }
255     }
256 }

原文地址:http://www.cnblogs.com/ldqwyl/archive/2011/04/13/2015476.html

原文地址:https://www.cnblogs.com/hzz521/p/5810937.html