65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 C# 打印 Word 文档

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.63/5 (25投票s)

2005年7月15日

CPOL
viewsIcon

174764

使用 Microsoft Word 和 C# 打印文档。

引言

我觉得有必要分享一下这个痛苦的经历。我为此挣扎了好几天,想让一个简单的功能正常工作。那就是使用 Word 打印 Word 文档(RTF 格式)到打印机。它还需要与多个版本的 Word 兼容(到目前为止,2000 和 2003)。我想分享一下我所学的一切。

如果希望在多个版本上工作,请安装最早版本的 Word 并添加对其 COM 组件的引用,然后针对这些版本进行开发。

接下来是代码...

代码

// Create an Application object
Word.ApplicationClass ac = new Word.ApplicationClass();
Word.Application app = ac.Application;

// I'm setting all of the alerts to be off as I am trying to get
// this to print in the background
app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;

// Open the document to print...
object filename = "myFile.rtf";
object missingValue = Type.Type.Missing;

// Using OpenOld so as to be compatible with other versions of Word
Word.Document document = app.Documents.OpenOld(ref filename,
ref missingValue, ref missingValue, 
ref missingValue, ref missingValue, ref missingValue, 
	ref missingValue, ref missingValue, ref missingValue, ref missingValue);

// Set the active printer
app.ActivePrinter = "My Printer Name";

object myTrue = true; // Print in background
object myFalse = false;

// Using PrintOutOld to be version independent
m_App.ActiveDocument.PrintOutOld(ref myTrue, 
ref myFalse, ref missingValue, ref missingValue, ref missingValue, 
	missingValue, ref missingValue, 
ref missingValue, ref missingValue, ref missingValue, ref myFalse, 
	ref missingValue, ref missingValue, ref m_MissingValue);

document.Close(ref missingValue, ref missingValue, ref missingValue);

// Make sure all of the documents are gone from the queue
while(m_App.BackgroundPrintingStatus > 0)
{
System.Threading.Thread.Sleep(250);
}

app.Quitref missingValue, ref missingValue, ref missingValue);

我并不声称这是完美的,但这是我能做到的最好结果。反正它在我机器上可以正常工作。

历史

  • 2005年7月15日:初始发布
© . All rights reserved.