Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Printing Word Documents in C#

0.00/5 (No votes)
15 Jul 2005 1  
Printing documents using Microsoft Word and C#

Introduction

I feel I need to share this pain. I have been struggling for days now to get something simple to work for me. That is to print out a Word document (RTF format) to a printer using Word. It also has to work with multiple versions of Word (so far 2000 and 2003). I thought I would share everything that I have learnt.

If you want this to work for multiple versions, install the earliest version of Word and Add Reference to its COM component and develop against these.

Next to the code...

The Code

// 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);

I do not claim that this is perfect, but it's as good as I can get. It works on my machine anyway.

History

  • 15th July, 2005: Initial post 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here