打印Word文件

服务端调用打印机打印Word文件

简介

工作时需要直接操作 OA系统 调用打印机打印 Word 文件。

引用库介绍

需要电脑安装 Microsoft Office 并引用COM组件 Microsoft.Office.Interop.Word 才可以调用打印机。

代码及调用

打印Word

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using Word = Microsoft.Office.Interop.Word;

/// <summary>
/// 打印Word
/// </summary>
/// <param name="filePath">需要打印的文件</param>
/// <param name="PrintName">打印机名称</param>
private static void PrintWord(string filePath, string PrintName)
{
try
{
//要打印的文件路径
Object wordFile = filePath;
object oMissing = Missing.Value;
//自定义object类型的布尔值
object oTrue = true;
object oFalse = false;
object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;

//Word.Application appWord = null;
//定义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 = PrintName;

//打印
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)
{
//代码行数
string line = ex.StackTrace.ToString();
//返回错误发生的方法定义
string errorfunction = ex.TargetSite.ToString();
int code = ex.HResult;
}
}

调用方法

1
2
//打印Word
PrintWord(dialog.FileName, "审批打印机");