After tossing for a long time, I finally decided to use a third-party one and found jacob, which is not bad, hereby record it.
1. Copy jacob's dll file to C:\Windows\System32.
2. Open the service DCom Server Process Launcher (DcomLaunch) in the Task Manager.
3. Copy jacob.jar to the /libs directory of the project.
It is worth noting that I am on Windows Server 2008, the dll file cannot be found, and an error is reported: Exception in thread "main" java.lang.UnsatisfiedLinkError: no jacob-1.17-x86 in java.library.path
But on win system, it's fine.
So at this time, you need to copy the dll files to your jdk/bin directory, jdk/jre/bin directory, and jre/bin directory. Then there is no problem.
code show as below:
public class TestDoc { public static void main(String[] args) { String path="D:\\yanqiong.doc"; System.out.println("Start printing"); ComThread.InitSTA(); ActiveXComponent word=new ActiveXComponent("Word.Application"); Dispatch doc=null; Dispatch.put(word, "Visible", new Variant(false)); Dispatch docs=word.getProperty("Documents").toDispatch(); doc=Dispatch.call(docs, "Open", path).toDispatch(); try { Dispatch.call(doc, "PrintOut");//打印 } catch (Exception e) { e.printStackTrace (); System.out.println("Print failed"); }finally{ try { if(doc!=null){ Dispatch.call(doc, "Close",new Variant(0)); } } catch (Exception e2) { e2.printStackTrace(); } // release resources ComThread.Release(); } } }