10

I'm trying to print a word doc from my C# code. I used the 12.0.0.0 Word Interop and what i'm trying to do is to get a Print Dialogue pop up before the document prints. I'm not 100% sure of the syntax of all of this as I can't get my code to work :( Any ideas?

Thanks in advance!

Berkay Turancı
  • 3,373
  • 4
  • 32
  • 45
yeahumok
  • 2,940
  • 19
  • 52
  • 63

2 Answers2

11

It should be something along the lines of:

object nullobj = Missing.Value;
doc = wordApp.Documents.Open(ref file,
                             ref nullobj, ref nullobj, ref nullobj,
                             ref nullobj, ref nullobj, ref nullobj,
                             ref nullobj, ref nullobj, ref nullobj,
                             ref nullobj, ref nullobj, ref nullobj,
                             ref nullobj, ref nullobj, ref nullobj);

doc.Activate();
doc.Visible = true;
int dialogResult = wordApp.Dialogs[Microsoft.Office.Interop.Word.WdWordDialog.wdDialogFilePrint].Show(ref nullobj);

if (dialogResult == 1)
{
    doc.PrintOut(ref nullobj, ref nullobj, ref nullobj, ref nullobj, 
                 ref nullobj, ref nullobj, ref nullobj, ref nullobj, 
                 ref nullobj, ref nullobj, ref nullobj, ref nullobj, 
                 ref nullobj, ref nullobj, ref nullobj, ref nullobj, 
                 ref nullobj, ref nullobj);
}
Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
McAden
  • 13,714
  • 5
  • 37
  • 63
  • for some reason this is not working...can you show me all your syntax? Even a simple print won't work for me!!! – yeahumok May 18 '09 at 15:59
  • Are you saying it won't print, or that the dialog won't show up? – McAden May 18 '09 at 16:30
  • 1
    I've found that the "if (dialogResult == 1)" block is not needed. The Show() method will display the dialog, and if the user clicks Print, it will print. – kad81 Jan 25 '13 at 00:14
4

The accepted answer didn't work for me, so I found another way. This will print a document at c:\temp.docx in the background, keeping Word hidden from view.

It uses Microsoft.Office.Interop.Word.

Word.Application wordApp = new Word.Application();
wordApp.Visible = false;

PrintDialog pDialog = new PrintDialog();
if (pDialog.ShowDialog() == DialogResult.OK)
{
  Word.Document doc = wordApp.Documents.Add(@"c:\temp.docx");
  wordApp.ActivePrinter = pDialog.PrinterSettings.PrinterName;
  wordApp.ActiveDocument.PrintOut(); //this will also work: doc.PrintOut();
  doc.Close(SaveChanges: false);
  doc = null;
}

// <EDIT to include Jason's suggestion>
((Word._Application)wordApp).Quit(SaveChanges: false); 
// </EDIT>

// Original: wordApp.Quit(SaveChanges: false);
wordApp = null;
Trev
  • 1,358
  • 3
  • 16
  • 28
  • 1
    The compiler with throw ambiguity warnings from this code. To eliminate them, use phoog's answer here: http://stackoverflow.com/questions/8303969/how-to-eliminate-warning-about-ambiguity – Jason Rae Apr 09 '13 at 18:08