C#直接打印word文档

摘要:
使用using.Microsoft.Office.Interop.Word;(通过添加引用com组件,找到office的word组件//////print word//////word文件路径//指定的打印机publicvoid print

    using using Microsoft.Office.Interop.Word;   
(通过添加引用-com组件,找office的word组件

 /// <summary>
        /// 打印word
        /// </summary>
        /// <param name="filepath">word文件路径</param>
        /// <param name="printername">指定的打印机</param>
        public void Printword(string filepath,string printername)
        {
            //filepath=@"d:\b.doc";
            //printername = "Microsoft XPS Document Writer";
            try
            {
                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 = filepath;
                Help help = new Help();
                help.LogMessage(filepath + "---------" + printername);
                //指定执行的动作,是打印,即print,打开是 open
                p.StartInfo.Verb = "print";

                //获取当前默认打印机

                string defaultPrinter = GetDefaultPrinter();

                //将指定的打印机设为默认打印机
                SetDefaultPrinter(printername);

                //开始打印
                p.Start();

                //等待十秒
                p.WaitForExit(10000);

                //将默认打印机还原
                SetDefaultPrinter(defaultPrinter);
            }
            catch (Exception ex)
            {
           
                help.LogMessage(filepath + "----" + printername + "-------" + ex.Message);
            }

        }
        [DllImport("Winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool SetDefaultPrinter(string printerName);

        [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
       
        private static extern bool GetDefaultPrinter(StringBuilder pszBuffer, ref int pcchBuffer);
        /// <summary>
        /// 获取默认的打印机
        /// </summary>
        /// <returns></returns>
        static string GetDefaultPrinter()
        {
            const int ERROR_FILE_NOT_FOUND = 2;

            const int ERROR_INSUFFICIENT_BUFFER = 122;

            int pcchBuffer = 0;

            if (GetDefaultPrinter(null, ref pcchBuffer))
            {
                return null;
            }

            int lastWin32Error = Marshal.GetLastWin32Error();

            if (lastWin32Error == ERROR_INSUFFICIENT_BUFFER)
            {
                StringBuilder pszBuffer = new StringBuilder(pcchBuffer);
                if (GetDefaultPrinter(pszBuffer, ref pcchBuffer))
                {
                    return pszBuffer.ToString();
                }

                lastWin32Error = Marshal.GetLastWin32Error();
            }
            if (lastWin32Error == ERROR_FILE_NOT_FOUND)
            {
                return null;
            }

            throw new Win32Exception(Marshal.GetLastWin32Error());


        }
        #region
      ///打印页面不会闪动
        public void PrintMethodOther(string filepath,string printername)
        {
            try
            {
                object wordFile = filepath;
                //@"d:\b.doc";
                object oMissing = Missing.Value;          
                //自定义object类型的布尔值
                object oTrue = true;
                object oFalse = false;
          
                object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
              
                //定义WORD Application相关
        
               Application appWord = new Application();
            
                //WORD程序不可见
                appWord.Visible = false;
                //不弹出警告框
                appWord.DisplayAlerts = WdAlertLevel.wdAlertsNone;
      
                //先保存默认的打印机
                string defaultPrinter = appWord.ActivePrinter;
            
                //打开要打印的文件
                //如果在其它函数调用中出错(doc为null),处理办法:建立临时文件夹,还要设置服务的权限属性
            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 = printername;
                //"Microsoft XPS Document Writer";
              
                //打印

                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;
            }
            catch (Exception ex)
            {
                help.LogMessage(filepath+"----"+printername+"-------"+ex.Message);
            }
        }


         //// <summary>
        ///解决 word调用打印机报错问题,创建一个临时文件夹
        /// </summary>
        /// <returns></returns>
        public bool CreateFolder()
        {
            bool ifsuccesss = false;
            try
            {
                string systempath = System.Environment.GetFolderPath(Environment.SpecialFolder.System);
                string fullpath = string.Empty;
                if (FindSystemWidth() == "32")
                {
                    fullpath = systempath + "\\config\\systemprofile\\Desktop";
                }
                else
                {
                    fullpath = systempath + "\\config\\systemprofile\\Desktop";
                }
                if (!Directory.Exists(fullpath))
                {
                    Directory.CreateDirectory(fullpath);
                }
                ifsuccesss = true;
            }
            catch (Exception ex)
            {
                ifsuccesss = false;
            }
            return ifsuccesss;

        }
        /// <summary>
        /// 获取系统的位数
        /// </summary>
        /// <returns></returns>
        public string FindSystemWidth()
        {
            ConnectionOptions oConn = new ConnectionOptions();
            System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\\\localhost", oConn);
            System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select AddressWidth from Win32_Processor");
            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
            ManagementObjectCollection oReturnCollection = oSearcher.Get();
            string addressWidth = null;

            foreach (ManagementObject oReturn in oReturnCollection)
            {
                addressWidth = oReturn["AddressWidth"].ToString();
            }

            return addressWidth;
        }
     

免责声明:文章转载自《C#直接打印word文档》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇C#读取CPU序列号、硬盘ID、网卡MAC地址,生成机器码c# 获取多个集合的组合结果下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

kindeditor在线编辑器的使用心得

1、如何声明引用? <!DOCTYPEhtml> <html> <head> <metacharset="utf-8"/> <title>kindeditor在线编辑器的使用心得</title> <!--添加kindeditor的引用--> <scr...

C# 互操作性入门系列(二):使用平台调用调用Win32 函数

本文转载自:https://www.cnblogs.com/zhili/archive/2013/01/21/PInvoke.html 本专题概要: 引言 如何使用平台调用Win32 函数——从实例开始 当调用Win32函数出错时怎么办?——获得Win32函数的错误信息 小结 一、引言 上一专题对.NET 互操作性做了一个全面的概括,其中讲到.NET平...

KindEditor 一款好用的HTML可视化编辑器(富文本编辑器)

  KindEditor使用JavaScript编写,可以无缝的于Java、.NET、PHP、ASP等程序接合。 KindEditor非常适合在CMS、商城、论坛、博客、Wiki、电子邮件等互联网应用上使用,2006年7月首次发布2.0以来,KindEditor依靠出色的用户体验和领先的技术不断扩大编辑器市场占有率,目前在国内已经成为最受欢迎的编辑器之一。...

html css项目积累汇总

1、关于ul的padding-left:40px的问题; 首先,我们来看一段代码: 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>ul的padding-left:40...

操作iframe 的方法与兼容性

首先创建两个页面 //iframe1.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body...

sass学习笔记1

less在处理CSS动画时,非常恶心,决定转向sass了。sass诞生得比less早,只是因为它是ruby写的,因此受众面够少。但我们不需要自己下编译器或使用命令行,我们可以koala这神器 首先几个注意点,sass可以用sass后缀名,也可以用scss后缀名。前者比较恶心,像python一样没有花括号,也不让写分号,散架子一样。因此推荐用scss,这个也...