HippoDuck
HippoDuck

Reputation: 2194

How to use Document.PrintOut method from Microsoft.Office.Tools.Word to print the first page of a document

The documentation is here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.tools.word.document.printout?view=vsto-2017

This will print the whole document:

Word.Application ap = new Word.Application();
Word.Document document = ap.Documents.Open(@"C:\temp\file.doc");
document.PrintOut();

I thought I were on to something with this as it compiled but it didn't work:

Word.Application ap = new Word.Application();
Word.Document document = ap.Documents.Open(@"C:\temp\file.doc");
Word.WdPrintOutRange printRange = new Word.WdPrintOutRange();
document.PrintOut(false, false, printRange,false, 1, 2);

System.Runtime.InteropServices.COMException: 'Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))'

How do I use this method to print just the first page of the document?

Edit: This URL (https://learn.microsoft.com/en-us/office/vba/api/word.document.printout) shows examples in VBA on how to do similar things, such as print the first 3 pages, but it's in VB and I am not sure on the c# equivalent.

Upvotes: 0

Views: 820

Answers (3)

James Dean
James Dean

Reputation: 23

Word.WdPrintOutRange printRange = Word.WdPrintOutRange.wdPrintRangeOfPages;

document.PrintOut(false,null,printRange,null,Pages:2-6);

"The page numbers and page ranges to be printed, separated by commas. For example, "2, 6-10" prints page 2 and pages 6 through 10."

it will print out the specific page/s like you do in microsoft word.

https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.tools.word.document.printout?view=vsto-2022

please let me know if it works for you because this works on me.

Upvotes: 1

HippoDuck
HippoDuck

Reputation: 2194

I couldn't get range to work.

I managed to achieve printing just the first page with this instead (Added some margins and setup the page size too):

Word.Application ap = new Word.Application();
Word.Document document = ap.Documents.Open(randFile);

document.PageSetup.TopMargin = 50;
document.PageSetup.RightMargin = 50;
document.PageSetup.BottomMargin = 50;
document.PageSetup.LeftMargin = 50;
document.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA4;

Word.WdPrintOutRange printRange = Word.WdPrintOutRange.wdPrintCurrentPage;

document.PrintOut(false,null,printRange);
document.Close(false, false, false);

Upvotes: 0

Eldar
Eldar

Reputation: 10790

Word.WdPrintOutRange is an enum value. And wdPrintFromTo is for range selection.

Word.WdPrintOutRange printRange = Word.WdPrintOutRange.wdPrintFromTo;
document.PrintOut(false, false, printRange, null, 1, 2);

Upvotes: 1

Related Questions