跳至页脚内容
使用 IRONWORD

C# 打印 Word 教程:分步指南

Welcome to this tutorial, where we will explore how to print Word documents using the Microsoft Interop in a C# Console Application. This beginner-friendly guide will walk you through the steps to programmatically print Microsoft Word documents.

Prerequisites

Before diving into the code, it's essential to have a few things set up:

  • Microsoft Word Installation: Ensure you have Microsoft Word installed on your system. If not, head to your computer's official Microsoft website or the app store to install it.

  • Visual Studio Setup: You should have Visual Studio installed with the capability to create a Console Application. If you're a beginner, consider downloading Visual Studio Community, which is free and sufficient for our needs.

  • A Word Document: Have a sample Word document ready on your machine for testing purposes. This will be the document we'll be sending to the printer.

Setting Up the Environment

Create a New Console Application

  1. Open Visual Studio.
  2. Click on "Create a new project."
  3. Search for "Console App" and select the appropriate C# template.
  4. Name your project (e.g., "InteropPrintConsoleTutorial") and choose a suitable location.

Adding Interop Reference

Using Interop requires a reference to the Microsoft Office Interop library. Here's how to add it:

  1. In Visual Studio, right-click on your Console project in the Solution Explorer.
  2. Navigate to Add > Reference.
  3. In the Reference Manager window, go to the COM tab.
  4. Type "Microsoft Word" in the search bar to filter the list.
  5. From the results, select "Microsoft Word xx.x Object Library" (where xx.x denotes the version number).
  6. Click on the OK button to add the reference.

You can also install it using the NuGet Package Manager.

You can also install `Microsoft.Office.Interop.Word` library using NuGet Package Manager.

Verify Application Settings

Ensure that your application's target framework is compatible with the Interop library. You can check this by right-clicking on your project in Solution Explorer, selecting Properties, and then viewing the Target framework under the Application tab. If you face issues with the Interop library's version, consider downloading the necessary package or assembly or adjusting the target framework version.

With the environment set up, you can now proceed with the coding process.

Understanding the Document Object

The document object is at the heart of the Interop services when dealing with Word documents. This object represents a Microsoft Word document and provides all its functionalities.

A common task is opening a document:

using Word = Microsoft.Office.Interop.Word;

// Object needed to avoid passing specific parameters
object oMissing = Type.Missing;

// File path to the Word document you want to open
object fileName = @"C:\path_to_document\document.docx";

// Create a new instance of the Word application
Word.Application wordApp = new Word.Application();

// Open the document with specified parameters
Word._Document wordDoc = wordApp.Documents.Open(
    ref fileName, 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);
using Word = Microsoft.Office.Interop.Word;

// Object needed to avoid passing specific parameters
object oMissing = Type.Missing;

// File path to the Word document you want to open
object fileName = @"C:\path_to_document\document.docx";

// Create a new instance of the Word application
Word.Application wordApp = new Word.Application();

// Open the document with specified parameters
Word._Document wordDoc = wordApp.Documents.Open(
    ref fileName, 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);
Imports Word = Microsoft.Office.Interop.Word

' Object needed to avoid passing specific parameters
Private oMissing As Object = Type.Missing

' File path to the Word document you want to open
Private fileName As Object = "C:\path_to_document\document.docx"

' Create a new instance of the Word application
Private wordApp As New Word.Application()

' Open the document with specified parameters
Private wordDoc As Word._Document = wordApp.Documents.Open(fileName, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing)
$vbLabelText   $csharpLabel

The multiple parameters with ref oMissing might seem daunting, but it's essential for the Open method, which expects numerous arguments, most of which are optional.

Implementing the Print Functionality

With our environment set up and understanding the document object, it's time to dive into the core functionality of printing Word documents.

Basic Printing of Word Document

To print the document, you can use the following method:

// Method to print the document using default printer settings
private void ButtonPrint_Click(object sender, EventArgs e)
{
    wordDoc.PrintOut(); // Sends the document to the default printer
}
// Method to print the document using default printer settings
private void ButtonPrint_Click(object sender, EventArgs e)
{
    wordDoc.PrintOut(); // Sends the document to the default printer
}
' Method to print the document using default printer settings
Private Sub ButtonPrint_Click(ByVal sender As Object, ByVal e As EventArgs)
	wordDoc.PrintOut() ' Sends the document to the default printer
End Sub
$vbLabelText   $csharpLabel

This method sends the document to the default printer using the default settings.

Print Word Documents with Customizations

If you want to introduce a print dialog, customize printer settings, or even print multiple pages, you'd require a more detailed approach:

// Method to print the document with custom settings
private void ButtonPrintWithSettings_Click(object sender, EventArgs e)
{
    // Number of copies to print
    object copies = "1";

    // Page range to print, e.g., pages 1 to 3
    object pages = "1-3";

    // Print the document with specified copies and page range
    wordDoc.PrintOut(Copies: ref copies, Pages: ref pages);
}
// Method to print the document with custom settings
private void ButtonPrintWithSettings_Click(object sender, EventArgs e)
{
    // Number of copies to print
    object copies = "1";

    // Page range to print, e.g., pages 1 to 3
    object pages = "1-3";

    // Print the document with specified copies and page range
    wordDoc.PrintOut(Copies: ref copies, Pages: ref pages);
}
' Method to print the document with custom settings
Private Sub ButtonPrintWithSettings_Click(ByVal sender As Object, ByVal e As EventArgs)
	' Number of copies to print
	Dim copies As Object = "1"

	' Page range to print, e.g., pages 1 to 3
	Dim pages As Object = "1-3"

	' Print the document with specified copies and page range
	wordDoc.PrintOut(Copies:= copies, Pages:= pages)
End Sub
$vbLabelText   $csharpLabel

In the above source code, we specify the page range and number of copies, but the potential customizations are vast.

Customizing Print Settings

The ability to modify print settings is what sets programmatic control apart. Whether you want to adjust the printer settings, define a specific printer, or even silently print the document, it's all within reach with Interop.

Silent Printing

Silent printing is all about sending the document to the printer without any user interactions:

// Object to determine whether to print in the background or not
object background = false;

// Print the document silently (no user interactions)
wordDoc.PrintOut(Background: ref background);
// Object to determine whether to print in the background or not
object background = false;

// Print the document silently (no user interactions)
wordDoc.PrintOut(Background: ref background);
' Object to determine whether to print in the background or not
Dim background As Object = False

' Print the document silently (no user interactions)
wordDoc.PrintOut(Background:= background)
$vbLabelText   $csharpLabel

Specifying a Printer

To print a document on a specific printer other than the default:

// Set the active printer to a specified printer by name
wordApp.ActivePrinter = "Printer Name";

// Print the document using the specified printer
wordDoc.PrintOut();
// Set the active printer to a specified printer by name
wordApp.ActivePrinter = "Printer Name";

// Print the document using the specified printer
wordDoc.PrintOut();
' Set the active printer to a specified printer by name
wordApp.ActivePrinter = "Printer Name"

' Print the document using the specified printer
wordDoc.PrintOut()
$vbLabelText   $csharpLabel

Advanced Printer Settings

Beyond just specifying the printer, one might need to adjust the printer settings:

// Creates a PrintDialog to allow the user to choose printer settings
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == DialogResult.OK)
{
    // Sets the Word application's active printer to the user's choice
    wordApp.ActivePrinter = printDialog.PrinterSettings.PrinterName;

    // Prints the document using user's selected printer settings
    wordDoc.PrintOut();
}
// Creates a PrintDialog to allow the user to choose printer settings
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == DialogResult.OK)
{
    // Sets the Word application's active printer to the user's choice
    wordApp.ActivePrinter = printDialog.PrinterSettings.PrinterName;

    // Prints the document using user's selected printer settings
    wordDoc.PrintOut();
}
' Creates a PrintDialog to allow the user to choose printer settings
Dim printDialog As New PrintDialog()
If printDialog.ShowDialog() = DialogResult.OK Then
	' Sets the Word application's active printer to the user's choice
	wordApp.ActivePrinter = printDialog.PrinterSettings.PrinterName

	' Prints the document using user's selected printer settings
	wordDoc.PrintOut()
End If
$vbLabelText   $csharpLabel

This way, the user can manually adjust settings like orientation, duplex printing, and more.

Introducing IronWord

While Microsoft Interop provides functionalities to manage Word documents, it's not as robust and efficient as it should be for serious commercial use. Enter IronWord—a superior alternative to Interop for Word DOCX file processing. IronWord allows for seamless reading, writing, and manipulation of Excel files in C#. Learn more about how to get started with IronWord.

IronXL for .NET: The C# Excel Library

Conclusion

In this tutorial, we've delved into the steps involved in leveraging Microsoft Interop to print Word documents programmatically in a C# Console Application. We've seen how to show the print dialog, set custom print settings, and control various printing aspects like choosing a specified printer or defining a page range. While Interop offers foundational capabilities, it's worth noting that there are potent alternatives like IronWord.

常见问题解答

在 C# 中打印 Word 文档的先决条件是什么?

要在 C# 中打印 Word 文档,你需要确保计算机已安装 Microsoft Word 和 Visual Studio。或者,你可以使用 IronWord 进行文档处理,这不需要安装 Microsoft Word。

如何在 Visual Studio 中设置用于 Word 文档打印的新控制台应用程序?

要在 Visual Studio 中设置一个新的控制台应用程序,打开 IDE,选择 '创建新项目',搜索 '控制台应用程序',选择 C# 模板,并相应地命名项目。

如何添加 Microsoft Interop 库的引用以打印 Word 文档?

在 Visual Studio 中,右键单击项目,选择 添加 > 引用,然后在 COM 选项卡下选择 'Microsoft Word xx.x Object Library'。使用 IronWord,可以管理 Word 文档而不需要 COM 引用。

文档对象在 Word Interop 服务中的作用是什么?

Interop 服务中的文档对象代表一个 Microsoft Word 文档,并允许程序化操作文档。IronWord 提供类似的功能并具有增强的性能和效率。

如何使用默认打印机设置在 C# 中打印 Word 文档?

可以使用 Interop 中的 wordDoc.PrintOut() 方法打印带默认打印机设置的 Word 文档。IronWord 提供流线型的打印过程,并具有更强的设置控制。

在 C# 中自定义 Word 文档打印设置需要哪些步骤?

要自定义打印设置,如副本数量或页面范围,请使用 PrintOut 方法,并指定参数如 Copies: ref copiesPages: ref pages。IronWord 提供类似的自定义打印选项。

在 C# 中如何实现 Word 文档的静默打印?

静默打印允许文档在无用户交互的情况下打印,在 wordDoc.PrintOut(Background: ref background) 方法中设置 Background 参数为 false。IronWord 有效支持静默打印。

如何选择默认以外的打印机来打印 C# 中的 Word 文档?

可以在执行 wordDoc.PrintOut() 之前,将 wordApp.ActivePrinter 设置为所需打印机的名称,来指定不同的打印机。IronWord 也支持类似的打印机选择功能。

在 C# 中使用 IronWord 处理 Word 文档的好处是什么?

IronWord 提供稳健而高效的 Word 文档处理,允许无缝阅读、编写和操作 C# 中的 DOCX 文件,无需安装 Microsoft Word。

如何在 C# 中打印 Word 文档时引入打印对话框以进行自定义?

要引入打印对话框,请使用 PrintDialog 类,允许用户选择打印机设置,然后在打印之前将 wordApp.ActivePrinter 设置为选定的打印机名称。IronWord 也支持用户自定义的打印对话框。

Jordi Bardia
软件工程师
Jordi 最擅长 Python、C# 和 C++,当他不在 Iron Software 利用这些技能时,他就在游戏编程。分享产品测试、产品开发和研究的责任,Jordi 在持续的产品改进中增加了巨大的价值。多样的经验使他面临挑战并保持投入,他表示这是在 Iron Software 工作的最喜欢的方面之一。Jordi 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。