C# Print Word (Developer Tutorial)

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:

object oMissing = Type.Missing;
object fileName = @"C:\path_to_document\document.docx";
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);
object oMissing = Type.Missing;
object fileName = @"C:\path_to_document\document.docx";
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);
Dim oMissing As Object = Type.Missing
Dim fileName As Object = "C:\path_to_document\document.docx"
Dim wordDoc As Word._Document = wordApp.Documents.Open(fileName, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing)
VB   C#

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:

private void ButtonPrint_Click(object sender, EventArgs e)
{
    wordDoc.PrintOut();
}
private void ButtonPrint_Click(object sender, EventArgs e)
{
    wordDoc.PrintOut();
}
Private Sub ButtonPrint_Click(ByVal sender As Object, ByVal e As EventArgs)
	wordDoc.PrintOut()
End Sub
VB   C#

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

3.2 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:

private void ButtonPrintWithSettings_Click(object sender, EventArgs e)
{
    object copies = "1";
    object pages = "1-3"; // To print multiple pages, e.g., 1 to 3.

    wordDoc.PrintOut(Copies: ref copies, Pages: ref pages);
}
private void ButtonPrintWithSettings_Click(object sender, EventArgs e)
{
    object copies = "1";
    object pages = "1-3"; // To print multiple pages, e.g., 1 to 3.

    wordDoc.PrintOut(Copies: ref copies, Pages: ref pages);
}
Private Sub ButtonPrintWithSettings_Click(ByVal sender As Object, ByVal e As EventArgs)
	Dim copies As Object = "1"
	Dim pages As Object = "1-3" ' To print multiple pages, e.g., 1 to 3.

	wordDoc.PrintOut(Copies:= copies, Pages:= pages)
End Sub
VB   C#

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 background = false;
wordDoc.PrintOut(Background: ref background);
object background = false;
wordDoc.PrintOut(Background: ref background);
Dim background As Object = False
wordDoc.PrintOut(Background:= background)
VB   C#

Specifying a Printer

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

wordApp.ActivePrinter = "Printer Name";
wordDoc.PrintOut();
wordApp.ActivePrinter = "Printer Name";
wordDoc.PrintOut();
wordApp.ActivePrinter = "Printer Name"
wordDoc.PrintOut()
VB   C#

Advanced Printer Settings

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

PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == DialogResult.OK)
{
    wordApp.ActivePrinter = printDialog.PrinterSettings.PrinterName;
    wordDoc.PrintOut();
}
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == DialogResult.OK)
{
    wordApp.ActivePrinter = printDialog.PrinterSettings.PrinterName;
    wordDoc.PrintOut();
}
Dim printDialog As New PrintDialog()
If printDialog.ShowDialog() = DialogResult.OK Then
	wordApp.ActivePrinter = printDialog.PrinterSettings.PrinterName
	wordDoc.PrintOut()
End If
VB   C#

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

Introducing IronXL

While Microsoft Interop provides functionalities to manage Word documents, working with Excel files requires a more robust solution. Enter IronXL—a superior alternative to Interop for Excel operations. IronXL allows for seamless reading, writing, and manipulation of Excel files in C#. It offers enhanced performance, is easy to integrate, and is more efficient in handling large datasets. Learn more about IronXL's capabilities and its edge over Interop in this tutorial.

IronXL for .NET: The C# Excel Library

Excel Print Setup

using IronXL;
using IronXL.Printing;

WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set the print header and footer of the worksheet
workSheet.Header.Center = "My document";
workSheet.Footer.Center = "Page &P of &N";

// Set the header margin
workSheet.PrintSetup.HeaderMargin = 2.33;

// Set the size of the paper
// Paper size enum represents different sizes of paper
workSheet.PrintSetup.PaperSize = PaperSize.B4;

// Set the print orientation of the worksheet
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Portrait;

// Set black and white printing
workSheet.PrintSetup.NoColor = true;

// Save the excel file as XLS, XLSX
workBook.SaveAs("PrintSetup.xlsx");
using IronXL;
using IronXL.Printing;

WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set the print header and footer of the worksheet
workSheet.Header.Center = "My document";
workSheet.Footer.Center = "Page &P of &N";

// Set the header margin
workSheet.PrintSetup.HeaderMargin = 2.33;

// Set the size of the paper
// Paper size enum represents different sizes of paper
workSheet.PrintSetup.PaperSize = PaperSize.B4;

// Set the print orientation of the worksheet
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Portrait;

// Set black and white printing
workSheet.PrintSetup.NoColor = true;

// Save the excel file as XLS, XLSX
workBook.SaveAs("PrintSetup.xlsx");
Imports IronXL
Imports IronXL.Printing

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Set the print header and footer of the worksheet
workSheet.Header.Center = "My document"
workSheet.Footer.Center = "Page &P of &N"

' Set the header margin
workSheet.PrintSetup.HeaderMargin = 2.33

' Set the size of the paper
' Paper size enum represents different sizes of paper
workSheet.PrintSetup.PaperSize = PaperSize.B4

' Set the print orientation of the worksheet
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Portrait

' Set black and white printing
workSheet.PrintSetup.NoColor = True

' Save the excel file as XLS, XLSX
workBook.SaveAs("PrintSetup.xlsx")
VB   C#

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 IronXL, especially when dealing with Excel operations.

IronXL streamlines Excel file operations and stands out in performance and scalability. If you're keen on giving it a spin, IronXL offers a free trial. For those ready to invest in its vast features, licenses commence at $749. Whether you're sticking with Interop or considering a shift to IronXL, the future of document manipulation in C# looks promising.