C# 打印word文件

    #region 辅助定义

    //打印机状态
    [FlagsAttribute]
    internal enum PrinterStatus
    {
        PRINTER_STATUS_BUSY = 0x00000200,
        PRINTER_STATUS_DOOR_OPEN = 0x00400000,
        PRINTER_STATUS_ERROR = 0x00000002,
        PRINTER_STATUS_INITIALIZING = 0x00008000,
        PRINTER_STATUS_IO_ACTIVE = 0x00000100,
        PRINTER_STATUS_MANUAL_FEED = 0x00000020,
        PRINTER_STATUS_NO_TONER = 0x00040000,
        PRINTER_STATUS_NOT_AVAILABLE = 0x00001000,
        PRINTER_STATUS_OFFLINE = 0x00000080,
        PRINTER_STATUS_OUT_OF_MEMORY = 0x00200000,
        PRINTER_STATUS_OUTPUT_BIN_FULL = 0x00000800,
        PRINTER_STATUS_PAGE_PUNT = 0x00080000,
        PRINTER_STATUS_PAPER_JAM = 0x00000008,
        PRINTER_STATUS_PAPER_OUT = 0x00000010,
        PRINTER_STATUS_PAPER_PROBLEM = 0x00000040,
        PRINTER_STATUS_PAUSED = 0x00000001,
        PRINTER_STATUS_PENDING_DELETION = 0x00000004,
        PRINTER_STATUS_PRINTING = 0x00000400,
        PRINTER_STATUS_PROCESSING = 0x00004000,
        PRINTER_STATUS_TONER_LOW = 0x00020000,
        PRINTER_STATUS_USER_INTERVENTION = 0x00100000,
        PRINTER_STATUS_WAITING = 0x20000000,
        PRINTER_STATUS_WARMING_UP = 0x00010000
    };

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    internal struct structPrinterDefaults
    {
        [MarshalAs(UnmanagedType.LPTStr)]
        public String pDatatype;
        public IntPtr pDevMode;
        [MarshalAs(UnmanagedType.I4)]
        public int DesiredAccess;
    };

    //Nested Types
    [StructLayout(LayoutKind.Sequential)]
    public class DOCINFOA
    {
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDocName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pOutputFile;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDataType;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct PRINTER_INFO_2
    {
        public string pServerName;
        public string pPrinterName;
        public string pShareName;
        public string pPortName;
        public string pDriverName;
        public string pComment;
        public string pLocation;
        public IntPtr pDevMode;
        public string pSepFile;
        public string pPrintProcessor;
        public string pDatatype;
        public string pParameters;
        public IntPtr pSecurityDescriptor;
        public uint Attributes;
        public uint Priority;
        public uint DefaultPriority;
        public uint StartTime;
        public uint UntilTime;
        public uint Status;
        public uint cJobs;
        public uint AveragePPM;
    }

    #endregion

    /// <summary>
    /// 打印机状态
    /// </summary>
    public enum ePrinterState
    {
        UnknownStatus = -1,
        Ready = 0,
        Paused = 1,
        Error = 2,
        PendingDeletion = 4,
        PaperJam = 8,
        NoPaper = 0x10,
        ManualFeedPaper = 0x20,
        PaperProblem = 0x40,
        OffLine = 0x80,
        Transmitting = 0x100,
        Busy = 0x200,
        Printing = 0x400,
        OutputBinFull = 0x800,
        NotAvailable = 0x1000,
        Processing = 0x4000,
        Initializing = 0x8000,
        /// <summary>
        /// 热机中
        /// </summary>
        WarmingUp = 0x10000,
        /// <summary>
        /// 墨粉不足
        /// </summary>
        TonerLow = 0x20000,
        /// <summary>
        /// 无墨粉
        /// </summary>
        NoToner = 0x40000,
        /// <summary>
        /// 当前页无法打印
        /// </summary>
        PagePunt = 0x80000,
        /// <summary>
        /// 需要用户干预
        /// </summary>
        UserIntervention = 0x100000,
        OutOfMemory = 0x200000,
        DoorIsOpen = 0x400000,
        Waiting = 0x20000000,
    }

    /// <summary>
    /// 打印的文件类型
    /// </summary>
    public enum ePrintFileType
    {
        Invalid = -1,
        TextFile = 0,
        Word = 1,
        Excel = 2
    }

    /// <summary>
    /// 打印类
    /// 使用方法:
    /// GetPrinterList 获取所有可用打印机名称列表
    /// CheckPrinterValid 检查某个打印机是否可用.
    /// GetPrinterStatus 获取打印机状态
    /// PrintFile 使用指定打印机打印文件.
    /// PrintFileBySystem 使用指定打印机打印文件,调用操作系统默认程序打印
    /// </summary>
    public class PrinterHelper
    {
        #region 对外接口
        public static bool PrintWord(string filename)
        {
            string printerName = GetDefaultPrinter();
            if (!string.IsNullOrEmpty(printerName))
            {
                if (CheckPrinterValid(printerName))
                {
                    return PrintWord(printerName, filename);
                }
            }
            return false;
        }
        /// <summary>
        /// 获取本机安装的所有打印机
        /// </summary>
        /// <returns></returns>
        public static List<String> GetPrinterList()
        {
            List<String> ret = new List<String>();
            if (PrinterSettings.InstalledPrinters.Count < 1)
            {
                return ret;
            }

            foreach (String printername in PrinterSettings.InstalledPrinters)
            {
                ret.Add(printername);
            }
            return ret;
        }

        /// <summary>
        /// 检查打印机是否可用
        /// </summary>
        /// <param name="printername"></param>
        /// <returns></returns>
        public static Boolean CheckPrinterValid(String printername)
        {
            if (printername.Length < 1)
            {
                return false;
            }

            ePrinterState state = GetPrinterStatus(printername);
            if (state == ePrinterState.Ready || state == ePrinterState.Busy)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取打印机状态
        /// </summary>
        /// <param name="PrinterName"></param>
        /// <returns></returns>
        public static ePrinterState GetPrinterStatus(string PrinterName)
        {
            int intValue = GetPrinterStatusInt(PrinterName);
            ePrinterState ret = (ePrinterState)intValue;
            return ret;
        }

        #endregion

        #region 内部实现
        /// <summary>
        /// 打印word
        /// </summary>
        /// <param name="printername"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        private static Boolean PrintWord(String printername, String filename)
        {
            object oMissing = Missing.Value;

            //定义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;

            object oTrue = true;
            object oFalse = false;

            //打开要打印的文件
            object wordFile = filename;
            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);

            //设置指定的打印机
            appWord.ActivePrinter = printername;

            //true后台打印,false前台打印。
            //必须false,否则后台打印时,尚未打印,就调用了后续的Close,造成打印任务无法执行
            object printbackgroud = false;

            doc.PrintOut(ref printbackgroud,
                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
                );

            object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;

            //打印完关闭WORD文件
            doc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);

            //退出WORD程序
            appWord.Quit(ref doNotSaveChanges, ref oMissing, ref oMissing);

            doc = null;
            appWord = null;
            return true;
        }

        #endregion

        #region 获取设置默认打印机

        /// <summary>
        /// 设置默认打印机
        /// </summary>
        /// <param name="printerName"></param>
        /// <returns></returns>
        [DllImport("Winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
        public 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>
        public static String GetDefaultPrinter()
        {
            StringBuilder strbuilder = new StringBuilder(2048);
            Int32 buflen = strbuilder.Capacity;

            GetDefaultPrinter(strbuilder, ref buflen);
            String ret = strbuilder.ToString();
            return ret;
        }
        #endregion

        #region 系统API

        // [Methods]
        [DllImport("winspool.Drv", CallingConvention = CallingConvention.StdCall, SetLastError = true, ExactSpelling = true)]
        internal static extern bool ClosePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", CallingConvention = CallingConvention.StdCall, SetLastError = true, ExactSpelling = true)]
        internal static extern bool EndDocPrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", CallingConvention = CallingConvention.StdCall, SetLastError = true, ExactSpelling = true)]
        internal static extern bool EndPagePrinter(IntPtr hPrinter);

        [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        internal static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

        [DllImport("winspool.Drv", EntryPoint = "GetPrinterA", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        internal static extern bool GetPrinter(IntPtr hPrinter, int dwLevel, IntPtr pPrinter, int dwBuf, out int dwNeeded);

        [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        internal static extern bool StartDocPrinter(IntPtr hPrinter, int level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);


        [DllImport("winspool.Drv", CallingConvention = CallingConvention.StdCall, SetLastError = true, ExactSpelling = true)]
        internal static extern bool StartPagePrinter(IntPtr hPrinter);


        [DllImport("winspool.Drv", CallingConvention = CallingConvention.StdCall, SetLastError = true, ExactSpelling = true)]
        internal static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, int dwCount, out int dwWritten);

        /// <summary>
        /// 获取打印机状态字
        /// </summary>
        /// <param name="PrinterName"></param>
        /// <returns></returns>
        internal static int GetPrinterStatusInt(string PrinterName)
        {
            int intRet = 0;
            IntPtr hPrinter;
            //structPrinterDefaults defaults = new structPrinterDefaults();

            Boolean bl = OpenPrinter(PrinterName, out hPrinter, IntPtr.Zero);
            if (!bl)
            {
                return (int)ePrinterState.NotAvailable;
            }

            int cbNeeded = 0;
            bl = GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out cbNeeded);
            //此处不能判断bl.应该只判断 cbNeeded
            if (cbNeeded < 1)
            {
                ClosePrinter(hPrinter);
                return (int)ePrinterState.OutputBinFull;
            }

            IntPtr pAddr = Marshal.AllocHGlobal((int)cbNeeded);
            bl = GetPrinter(hPrinter, 2, pAddr, cbNeeded, out cbNeeded);
            if (!bl)
            {
                ClosePrinter(hPrinter);
                return (int)ePrinterState.NotAvailable;
            }

            PRINTER_INFO_2 Info2 = new PRINTER_INFO_2();
            Info2 = (PRINTER_INFO_2)Marshal.PtrToStructure(pAddr, typeof(PRINTER_INFO_2));
            intRet = System.Convert.ToInt32(Info2.Status);
            Marshal.FreeHGlobal(pAddr);
            ClosePrinter(hPrinter);
            return intRet;
        }

        #endregion
    }

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页