Search in sources :

Example 6 with WORD

use of com.sun.jna.platform.win32.WinDef.WORD in project jna by java-native-access.

the class MSOfficeWordDemo method testMSWord.

public static void testMSWord() throws IOException {
    File demoDocument = null;
    ComIApplication msWord = null;
    Factory factory = new Factory();
    try {
        System.out.println("Files in temp dir: " + Helper.tempDir.getAbsolutePath());
        ComWord_Application msWordObject = factory.createObject(ComWord_Application.class);
        msWord = msWordObject.queryInterface(ComIApplication.class);
        System.out.println("MSWord version: " + msWord.getVersion());
        msWord.setVisible(true);
        demoDocument = Helper.createNotExistingFile("jnatest", ".doc");
        Helper.extractClasspathFileToReal("/com/sun/jna/platform/win32/COM/util/office/resources/jnatest.doc", demoDocument);
        msWord.getDocuments().Open(demoDocument.getAbsolutePath());
        Helper.sleep(5);
        msWord.getSelection().TypeText("Hello from JNA! \n\n");
        // wait 10sec. before closing
        Helper.sleep(10);
        // save in different formats
        // pdf format is only supported in MSWord 2007 and above
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestSaveAs.doc").getAbsolutePath(), WdSaveFormat.wdFormatDocument);
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestSaveAs.pdf").getAbsolutePath(), WdSaveFormat.wdFormatPDF);
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestSaveAs.rtf").getAbsolutePath(), WdSaveFormat.wdFormatRTF);
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestSaveAs.html").getAbsolutePath(), WdSaveFormat.wdFormatHTML);
        // close and don't save the changes
        msWord.getActiveDocument().Close(false);
        // Create a new document
        msWord.getDocuments().Add();
        // msWord.openDocument(currentWorkingDir + "jnatest.doc", true);
        msWord.getSelection().TypeText("Hello from JNA! \n Please notice that JNA can control " + "MS Word via the new COM interface! \nHere we are " + "creating a new word document and we save it " + "to the 'TEMP' directory!");
        // save with no user prompt
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestNewDoc1.docx").getAbsolutePath(), WdSaveFormat.wdFormatDocumentDefault);
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestNewDoc2.docx").getAbsolutePath(), WdSaveFormat.wdFormatDocumentDefault);
        msWord.getActiveDocument().SaveAs(new File(Helper.tempDir, "jnatestNewDoc3.docx").getAbsolutePath(), WdSaveFormat.wdFormatDocumentDefault);
        // close and don't save the changes
        msWord.getActiveDocument().Close(false);
        // open 3 documents
        msWord.getDocuments().Open(new File(Helper.tempDir, "jnatestNewDoc1.docx").getAbsolutePath());
        msWord.getSelection().TypeText("Hello some changes from JNA!\n");
        msWord.getDocuments().Open(new File(Helper.tempDir, "jnatestNewDoc2.docx").getAbsolutePath());
        msWord.getSelection().TypeText("Hello some changes from JNA!\n");
        msWord.getDocuments().Open(new File(Helper.tempDir, "jnatestNewDoc3.docx").getAbsolutePath());
        msWord.getSelection().TypeText("Hello some changes from JNA!\n");
        // save the document and prompt the user
        msWord.getDocuments().Save(false, WdOriginalFormat.wdPromptUser);
    } finally {
        // Make sure the word instance is shut down
        if (msWord != null) {
            msWord.Quit();
        }
        // Release all objects acquired by the factory
        factory.disposeAll();
        if (demoDocument != null && demoDocument.exists()) {
            demoDocument.delete();
        }
    }
}
Also used : ComWord_Application(com.sun.jna.platform.win32.COM.util.office.word.ComWord_Application) Factory(com.sun.jna.platform.win32.COM.util.Factory) File(java.io.File) ComIApplication(com.sun.jna.platform.win32.COM.util.office.word.ComIApplication)

Example 7 with WORD

use of com.sun.jna.platform.win32.WinDef.WORD in project jna by java-native-access.

the class Wordautomation_KB_313193_Mod method main.

public static void main(String[] args) throws IOException {
    // Initialize COM Subsystem
    Ole32.INSTANCE.CoInitializeEx(Pointer.NULL, Ole32.COINIT_MULTITHREADED);
    // Initialize Factory for COM object creation
    Factory fact = new Factory();
    try {
        // oEndOfDoc is a predefined bookmark
        final String oEndOfDoc = "\\endofdoc";
        /* \endofdoc is a predefined bookmark */
        // Start word application
        ComWord_Application word = fact.createObject(ComWord_Application.class);
        ComIApplication wordApp = word.queryInterface(ComIApplication.class);
        // Make word visible/invisible (invisible is default)
        wordApp.setVisible(true);
        // Create an empty document (signiture of depends on bindings)
        ComIDocument doc = wordApp.getDocuments().Add();
        Helper.sleep(5);
        //Insert a paragraph at the beginning of the document.
        Paragraph para1 = doc.getContent().getParagraphs().Add(VARIANT_MISSING);
        para1.getRange().setText("Heading 1");
        para1.getRange().getFont().setBold(1);
        //24 pt spacing after paragraph.
        para1.getFormat().setSpaceAfter(24F);
        para1.getRange().InsertParagraphAfter();
        //Insert a paragraph at the end of the document.
        Paragraph para2 = doc.getContent().getParagraphs().Add(doc.getBookmarks().Item(oEndOfDoc).getRange());
        para2.getRange().setText("Heading 2");
        para2.getFormat().setSpaceAfter(6F);
        para2.getRange().InsertParagraphAfter();
        //Insert another paragraph.
        Paragraph para3 = doc.getContent().getParagraphs().Add(doc.getBookmarks().Item(oEndOfDoc).getRange());
        para3.getRange().setText("This is a sentence of normal text. Now here is a table:");
        para3.getRange().getFont().setBold(0);
        para3.getFormat().setSpaceAfter(24F);
        para3.getRange().InsertParagraphAfter();
        //Insert a 3 x 5 table, fill it with data, and make the first row
        //bold and italic.
        Table table = doc.getTables().Add(doc.getBookmarks().Item(oEndOfDoc).getRange(), 3, 5, VARIANT_MISSING, VARIANT_MISSING);
        table.getRange().getParagraphFormat().setSpaceAfter(6F);
        for (int r = 1; r <= 3; r++) {
            for (int c = 1; c <= 5; c++) {
                String strText = "r" + r + "c" + c;
                table.Cell(r, c).getRange().setText(strText);
            }
        }
        table.getRows().Item(1).getRange().getFont().setBold(1);
        table.getRows().Item(1).getRange().getFont().setItalic(1);
        //Add some text after the table.
        Paragraph para4 = doc.getContent().getParagraphs().Add(doc.getBookmarks().Item(oEndOfDoc).getRange());
        para4.getRange().InsertParagraphBefore();
        para4.getRange().setText("And here's another table:");
        para4.getFormat().setSpaceAfter(24F);
        para4.getRange().InsertParagraphAfter();
        //Insert a 5 x 2 table, fill it with data, and change the column widths.
        table = doc.getTables().Add(doc.getBookmarks().Item(oEndOfDoc).getRange(), 5, 2, VARIANT_MISSING, VARIANT_MISSING);
        table.getRange().getParagraphFormat().setSpaceAfter(6F);
        for (int r = 1; r <= 5; r++) {
            for (int c = 1; c <= 2; c++) {
                String strText = "r" + r + "c" + c;
                table.Cell(r, c).getRange().setText(strText);
            }
        }
        //Change width of columns 1 & 2
        table.getColumns().Item(1).setWidth(wordApp.InchesToPoints(2F));
        table.getColumns().Item(2).setWidth(wordApp.InchesToPoints(3F));
        //Keep inserting text. When you get to 7 inches from top of the
        //document, insert a hard page break.
        Range wrdRng;
        float dPos = wordApp.InchesToPoints(7F);
        doc.getBookmarks().Item(oEndOfDoc).getRange().InsertParagraphAfter();
        do {
            wrdRng = doc.getBookmarks().Item(oEndOfDoc).getRange();
            wrdRng.getParagraphFormat().setSpaceAfter(6F);
            wrdRng.InsertAfter("A line of text");
            wrdRng.InsertParagraphAfter();
        } while (dPos >= (Float) wrdRng.getInformation(WdInformation.wdVerticalPositionRelativeToPage));
        wrdRng.Collapse(WdCollapseDirection.wdCollapseEnd);
        wrdRng.InsertBreak(WdBreakType.wdPageBreak);
        wrdRng.Collapse(WdCollapseDirection.wdCollapseEnd);
        wrdRng.InsertAfter("We're now on page 2. Here's my chart:");
        wrdRng.InsertParagraphAfter();
        //Insert a chart and change the chart.
        InlineShape oShape = doc.getBookmarks().Item(oEndOfDoc).getRange().getInlineShapes().AddOLEObject("MSGraph.Chart.8", "", Boolean.FALSE, Boolean.FALSE, VARIANT_MISSING, VARIANT_MISSING, VARIANT_MISSING, VARIANT_MISSING);
        //Demonstrate use of late bound oChart and oChartApp objects to
        //manipulate the chart object with MSGraph.
        IDispatch oChart = oShape.getOLEFormat().getObject();
        IDispatch oChartApp = oChart.getProperty(IDispatch.class, "Application");
        //Change the chart type to Line
        oChart.setProperty("ChartType", XlChartType.xlLine.getValue());
        //Update the chart image and quit MSGraph.
        oChartApp.invokeMethod(Void.class, "Update");
        oChartApp.invokeMethod(Void.class, "Quit");
        //... If desired, you can proceed from here using the Microsoft Graph 
        //Object model on the oChart and oChartApp objects to make additional
        //changes to the chart.
        //Set the width of the chart.
        oShape.setWidth(wordApp.InchesToPoints(6.25f));
        oShape.setHeight(wordApp.InchesToPoints(3.57f));
        //Add text after the chart.
        wrdRng = doc.getBookmarks().Item(oEndOfDoc).getRange();
        wrdRng.InsertParagraphAfter();
        wrdRng.InsertAfter("THE END.");
        File tempFile = Helper.createNotExistingFile("KB_313193_", ".pdf");
        doc.ExportAsFixedFormat(tempFile.getAbsolutePath(), WdExportFormat.wdExportFormatPDF, Boolean.FALSE, WdExportOptimizeFor.wdExportOptimizeForOnScreen, WdExportRange.wdExportAllDocument, null, null, WdExportItem.wdExportDocumentContent, Boolean.FALSE, Boolean.TRUE, WdExportCreateBookmarks.wdExportCreateNoBookmarks, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, VARIANT_MISSING);
        System.out.println("Output written to: " + tempFile.getAbsolutePath());
        doc.Close(WdSaveOptions.wdDoNotSaveChanges, VARIANT_MISSING, VARIANT_MISSING);
        wordApp.Quit();
    } finally {
        fact.disposeAll();
        Ole32.INSTANCE.CoUninitialize();
    }
}
Also used : InlineShape(com.sun.jna.platform.win32.COM.util.office.word.InlineShape) Table(com.sun.jna.platform.win32.COM.util.office.word.Table) ComIDocument(com.sun.jna.platform.win32.COM.util.office.word.ComIDocument) Factory(com.sun.jna.platform.win32.COM.util.Factory) WdExportRange(com.sun.jna.platform.win32.COM.util.office.word.WdExportRange) Range(com.sun.jna.platform.win32.COM.util.office.word.Range) Paragraph(com.sun.jna.platform.win32.COM.util.office.word.Paragraph) ComWord_Application(com.sun.jna.platform.win32.COM.util.office.word.ComWord_Application) IDispatch(com.sun.jna.platform.win32.COM.util.IDispatch) File(java.io.File) ComIApplication(com.sun.jna.platform.win32.COM.util.office.word.ComIApplication)

Example 8 with WORD

use of com.sun.jna.platform.win32.WinDef.WORD in project jna by java-native-access.

the class ProxyObject method oleMethod.

/*
	 * @see com.sun.jna.platform.win32.COM.COMBindingBaseObject#oleMethod
	 */
protected HRESULT oleMethod(final int nType, final VARIANT.ByReference pvResult, final IDispatch pDisp, final DISPID dispId, VARIANT[] pArgs) throws COMException {
    assert COMUtils.comIsInitialized() : "COM not initialized";
    if (pDisp == null)
        throw new COMException("pDisp (IDispatch) parameter is null!");
    // variable declaration
    int _argsLen = 0;
    VARIANT[] _args = null;
    final DISPPARAMS.ByReference dp = new DISPPARAMS.ByReference();
    final EXCEPINFO.ByReference pExcepInfo = new EXCEPINFO.ByReference();
    final IntByReference puArgErr = new IntByReference();
    // make parameter reverse ordering as expected by COM runtime
    if ((pArgs != null) && (pArgs.length > 0)) {
        _argsLen = pArgs.length;
        _args = new VARIANT[_argsLen];
        int revCount = _argsLen;
        for (int i = 0; i < _argsLen; i++) {
            _args[i] = pArgs[--revCount];
        }
    }
    // Handle special-case for property-puts!
    if (nType == OleAuto.DISPATCH_PROPERTYPUT) {
        dp.setRgdispidNamedArgs(new DISPID[] { OaIdl.DISPID_PROPERTYPUT });
    }
    // Apply "fix" according to
    // https://www.delphitools.info/2013/04/30/gaining-visual-basic-ole-super-powers/
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms221486(v=vs.85).aspx
    //
    // Summary: there are methods in the word typelibrary that require both
    // PROPERTYGET _and_ METHOD to be set. With only one of these set the call
    // fails.
    //
    // The article from delphitools argues, that automation compatible libraries
    // need to be compatible with VisualBasic which does not distingish methods
    // and property getters and will set both flags always.
    //
    // The MSDN article advises this behaviour: "[...] Some languages cannot 
    // distinguish between retrieving a property and calling a method. In this 
    //case, you should set the flags DISPATCH_PROPERTYGET and DISPATCH_METHOD.
    // [...]"))
    //
    // This was found when trying to bind InchesToPoints from the _Application 
    // dispatch interface of the MS Word 15 type library
    //
    // The signature according the ITypeLib Viewer (OLE/COM Object Viewer):
    // [id(0x00000172), helpcontext(0x09700172)]
    // single InchesToPoints([in] single Inches);
    final int finalNType;
    if (nType == OleAuto.DISPATCH_METHOD || nType == OleAuto.DISPATCH_PROPERTYGET) {
        finalNType = OleAuto.DISPATCH_METHOD | OleAuto.DISPATCH_PROPERTYGET;
    } else {
        finalNType = nType;
    }
    // Build DISPPARAMS
    if (_argsLen > 0) {
        dp.setArgs(_args);
        // write 'DISPPARAMS' structure to memory
        dp.write();
    }
    HRESULT hr = pDisp.Invoke(dispId, new REFIID(Guid.IID_NULL), factory.getLCID(), new WinDef.WORD(finalNType), dp, pvResult, pExcepInfo, puArgErr);
    COMUtils.checkRC(hr, pExcepInfo, puArgErr);
    return hr;
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) COMException(com.sun.jna.platform.win32.COM.COMException) HRESULT(com.sun.jna.platform.win32.WinNT.HRESULT) EXCEPINFO(com.sun.jna.platform.win32.OaIdl.EXCEPINFO) REFIID(com.sun.jna.platform.win32.Guid.REFIID) VARIANT(com.sun.jna.platform.win32.Variant.VARIANT) DWORDByReference(com.sun.jna.platform.win32.WinDef.DWORDByReference) DISPIDByReference(com.sun.jna.platform.win32.OaIdl.DISPIDByReference) PointerByReference(com.sun.jna.ptr.PointerByReference) IntByReference(com.sun.jna.ptr.IntByReference) ConnectionPoint(com.sun.jna.platform.win32.COM.ConnectionPoint) WinDef(com.sun.jna.platform.win32.WinDef) DISPPARAMS(com.sun.jna.platform.win32.OleAuto.DISPPARAMS)

Example 9 with WORD

use of com.sun.jna.platform.win32.WinDef.WORD in project jna by java-native-access.

the class TypeInfoUtil method Invoke.

/**
     * Invoke.
     * 
     * @param pvInstance
     *            the pv instance
     * @param memid
     *            the memid
     * @param wFlags
     *            the w flags
     * @param pDispParams
     *            the disp params
     * @return the invoke
     */
public Invoke Invoke(PVOID pvInstance, MEMBERID memid, WORD wFlags, DISPPARAMS.ByReference pDispParams) {
    VARIANT.ByReference pVarResult = new VARIANT.ByReference();
    EXCEPINFO.ByReference pExcepInfo = new EXCEPINFO.ByReference();
    UINTByReference puArgErr = new UINTByReference();
    HRESULT hr = this.typeInfo.Invoke(pvInstance, memid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
    COMUtils.checkRC(hr);
    return new Invoke(pVarResult, pExcepInfo, puArgErr.getValue().intValue());
}
Also used : UINTByReference(com.sun.jna.platform.win32.WinDef.UINTByReference) HRESULT(com.sun.jna.platform.win32.WinNT.HRESULT) EXCEPINFO(com.sun.jna.platform.win32.OaIdl.EXCEPINFO) HREFTYPEByReference(com.sun.jna.platform.win32.OaIdl.HREFTYPEByReference) UINTByReference(com.sun.jna.platform.win32.WinDef.UINTByReference) DWORDByReference(com.sun.jna.platform.win32.WinDef.DWORDByReference) BSTRByReference(com.sun.jna.platform.win32.WTypes.BSTRByReference) PointerByReference(com.sun.jna.ptr.PointerByReference) WORDByReference(com.sun.jna.platform.win32.WinDef.WORDByReference) IntByReference(com.sun.jna.ptr.IntByReference) VARIANT(com.sun.jna.platform.win32.Variant.VARIANT)

Example 10 with WORD

use of com.sun.jna.platform.win32.WinDef.WORD in project jna by java-native-access.

the class COMTest method testTYPEATTR.

public void testTYPEATTR() {
    int pSize = Native.POINTER_SIZE;
    TYPEATTR typeAttr = new TYPEATTR();
    typeAttr.guid = GUID.fromString("{50A7E9B0-70EF-11D1-B75A-00A0C90564FE}");
    typeAttr.lcid = Kernel32.INSTANCE.GetSystemDefaultLCID();
    typeAttr.dwReserved = new DWORD(1);
    typeAttr.memidConstructor = new MEMBERID(2);
    typeAttr.memidDestructor = new MEMBERID(3);
    typeAttr.lpstrSchema = new LPOLESTR("Hello World");
    typeAttr.cbSizeInstance = new ULONG(4);
    typeAttr.typekind = new TYPEKIND(5);
    typeAttr.cFuncs = new WORD(6);
    typeAttr.cVars = new WORD(7);
    typeAttr.cImplTypes = new WORD(8);
    typeAttr.cbSizeVft = new WORD(9);
    typeAttr.cbAlignment = new WORD(10);
    typeAttr.wMajorVerNum = new WORD(11);
    typeAttr.wMinorVerNum = new WORD(12);
    typeAttr.tdescAlias = new TYPEDESC();
    typeAttr.idldescType = new IDLDESC();
    typeAttr.write();
    typeAttr.read();
//System.out.println(typeAttr.toString());
//System.out.println("TYPEATTR size: " + typeAttr.size());
}
Also used : ULONG(com.sun.jna.platform.win32.WinDef.ULONG) DWORD(com.sun.jna.platform.win32.WinDef.DWORD) WORD(com.sun.jna.platform.win32.WinDef.WORD) MEMBERID(com.sun.jna.platform.win32.OaIdl.MEMBERID) TYPEDESC(com.sun.jna.platform.win32.OaIdl.TYPEDESC) TYPEATTR(com.sun.jna.platform.win32.OaIdl.TYPEATTR) LPOLESTR(com.sun.jna.platform.win32.WTypes.LPOLESTR) DWORD(com.sun.jna.platform.win32.WinDef.DWORD) IDLDESC(com.sun.jna.platform.win32.OaIdl.IDLDESC) TYPEKIND(com.sun.jna.platform.win32.OaIdl.TYPEKIND)

Aggregations

VARIANT (com.sun.jna.platform.win32.Variant.VARIANT)5 HRESULT (com.sun.jna.platform.win32.WinNT.HRESULT)4 IntByReference (com.sun.jna.ptr.IntByReference)4 PointerByReference (com.sun.jna.ptr.PointerByReference)4 COMException (com.sun.jna.platform.win32.COM.COMException)3 REFIID (com.sun.jna.platform.win32.Guid.REFIID)3 EXCEPINFO (com.sun.jna.platform.win32.OaIdl.EXCEPINFO)3 WinDef (com.sun.jna.platform.win32.WinDef)3 WORD (com.sun.jna.platform.win32.WinDef.WORD)3 File (java.io.File)3 Factory (com.sun.jna.platform.win32.COM.util.Factory)2 ComIApplication (com.sun.jna.platform.win32.COM.util.office.word.ComIApplication)2 ComWord_Application (com.sun.jna.platform.win32.COM.util.office.word.ComWord_Application)2 DISPID (com.sun.jna.platform.win32.OaIdl.DISPID)2 DISPIDByReference (com.sun.jna.platform.win32.OaIdl.DISPIDByReference)2 DISPPARAMS (com.sun.jna.platform.win32.OleAuto.DISPPARAMS)2 Variant (com.sun.jna.platform.win32.Variant)2 DWORD (com.sun.jna.platform.win32.WinDef.DWORD)2 DWORDByReference (com.sun.jna.platform.win32.WinDef.DWORDByReference)2 WString (com.sun.jna.WString)1