Search code examples
comjna

Printing a MS Word document using JNA


I'm using the MSOfficeDemo/MSWord classes as a starter.

How can I print a document that is open in Word?

In a new method in the MSWord.java class I've tried:

this.invokeNoReply("Print", this.getDocuments());
this.invokeNoReply("PrintOut", this.getDocuments());
this.invokeNoReply("FilePrint", this.getDocuments());

I get an Unknown Name (hr=-2147352570) error for each of the above calls.

I've been searching for a week now and haven't found a solution.


Solution

  • Rather than guessing, you need to match your method signature to the documentation.

    You need to actually print the active document (this.getActiveDocument()) rather than the collection of documents. Then refer to the Document methods to see which method (and arguments) to use, in this case PrintOut is the correct method.

    What you pass for the parameters, you need to look at the various method signatures in ComLateBindingObject and pick the one that best matches your needs (you can pass one or two arguments, more than that you need an array.

    This code should work... haven't tested it (don't have MSWord on my Windows VM) but combined with the links above it should get you in the right direction:

    this.invokeNoReply("PrintOut", getActiveDocument());
    

    If that doesn't work, try:

    this.invokeNoReply("PrintOut", getActiveDocument().getIDispatch());
    

    If you actually need to pass any of the parameters, you'll create a VARIANT for them and start filling in 1 or more of the parameters (or an array of them).