package com.example; // Classes for bootstrapping connection to OpenOffice.org import com.sun.star.connection.ConnectionSetupException; import com.sun.star.connection.NoConnectException; import com.sun.star.io.IOException; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.IndexOutOfBoundsException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.uno.Exception; import com.sun.star.bridge.XUnoUrlResolver; // Classes for accessing interfaces of the OpenOffice.org API import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XComponent; import com.sun.star.uno.XComponentContext; import com.sun.star.uno.UnoRuntime; // Classes for loading and storing documents import com.sun.star.frame.XComponentLoader; // Classes for property access import com.sun.star.beans.PropertyValue; import com.sun.star.beans.XPropertySet; // Classes used for manipulation of text documents import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.XIndexAccess; import com.sun.star.container.XNameAccess; // MailMerge Classes // Database access Classes import com.sun.star.frame.XStorable; import com.sun.star.table.XCell; import com.sun.star.text.XText; import com.sun.star.text.XTextTable; import com.sun.star.text.XTextTableCursor; import com.sun.star.text.XTextTablesSupplier; import com.sun.star.uno.Any; import java.net.MalformedURLException; import java.util.Hashtable; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; public class OfficeUNOClientApp { // The default connection string used to connect to running OpenOffice.org public static final String DEFAULT_CONNECTION_STRING = "uno:socket,host=localhost,port=8100;urp,Negotiate=1,ForceSynchronous=1;StarOffice.ServiceManager"; private XComponentContext xComponentContext; private XComponentLoader xCLoader; public OfficeUNOClientApp(String inputFilename) { setupConnection(); // create new document based on template PropertyValue[] loadProps = null; loadProps = new PropertyValue[2]; loadProps[0] = new PropertyValue(); loadProps[0].Name = "AsTemplate"; loadProps[0].Value = new Boolean(true); loadProps[1] = new PropertyValue(); loadProps[1].Name = "Hidden"; // for open document and do not show user interface use "true" loadProps[1].Value = new Boolean(true); XComponent document = null; try { document = xCLoader.loadComponentFromURL(createUNOFileURL(inputFilename), "_blank", 0, loadProps); } catch (IOException ex) { Logger.getLogger(OfficeUNOClientApp.class.getName()).log(Level.SEVERE, null, ex); System.exit(3); } catch (IllegalArgumentException ex) { Logger.getLogger(OfficeUNOClientApp.class.getName()).log(Level.SEVERE, null, ex); System.exit(3); } // first query the XTextTablesSupplier interface from our document XTextTablesSupplier xTablesSupplier = (XTextTablesSupplier) UnoRuntime.queryInterface( XTextTablesSupplier.class, document); if (null == xTablesSupplier) { System.err.println("Tables are not supported in this format (?), sorry"); System.exit(3); } // get the tables collection XNameAccess xNamedTables = xTablesSupplier.getTextTables(); // now query the XIndexAccess from the tables collection XIndexAccess xIndexedTables = (XIndexAccess) UnoRuntime.queryInterface( XIndexAccess.class, xNamedTables); // get the tables for (int i = 0; i < xIndexedTables.getCount(); i++) { // iterate tables XTextTable table = null; try { table = (XTextTable) ((Any) xIndexedTables.getByIndex(i)).getObject(); } catch (IndexOutOfBoundsException ex) { Logger.getLogger(OfficeUNOClientApp.class.getName()).log(Level.SEVERE, null, ex); System.exit(14); } catch (WrappedTargetException ex) { Logger.getLogger(OfficeUNOClientApp.class.getName()).log(Level.SEVERE, null, ex); System.exit(14); } Hashtable> somerows = new Hashtable>(); Hashtable row = new Hashtable(); row.put("A1", "test1"); row.put("B1", "test2"); row.put("C1", "test3"); row.put("D1", "test4"); somerows.put(0, row); int rowsAddedOffset = 0; int currentRow; for (Map.Entry> entry : somerows.entrySet()) { Hashtable templateRow = entry.getValue(); currentRow = entry.getKey(); int rowsToAdd = 10; int rowsAdded = 0; if (templateRow.size() > 0) { do { table.getRows().insertByIndex(currentRow + rowsAddedOffset, 1); /* UNCOMMENT IT AND CHECK WHAT HAPPENS // @ http://www.openoffice.org/issues/show_bug.cgi?id=108148 try { Thread.sleep(1000); } catch (InterruptedException ex) { System.exit(1); }//*/ for (Map.Entry entry2 : templateRow.entrySet()) { String cellString = entry2.getValue(); String cellName = entry2.getKey(); XTextTableCursor cursor = table.createCursorByCellName(cellName); cursor.goDown((short) rowsAdded, false); XCell newCell = table.getCellByName(cursor.getRangeName()); XText newCellText = (XText) UnoRuntime.queryInterface(XText.class, newCell); newCellText.setString(cellString); } ++ rowsAddedOffset; ++ rowsAdded; } while(rowsAdded < rowsToAdd); } // usuń wiersz "źródłowy" table.getRows().removeByIndex(currentRow + rowsAddedOffset, 1); -- rowsAddedOffset; } } SaveDocument(document, "/tmp/test.pdf"); System.exit(0); } public static void main(String args[]) { if (args.length == 1) { // connect to open office OfficeUNOClientApp mm = new OfficeUNOClientApp(args[0]); } else { System.err.println("Please provide file name to read!"); System.exit(2); } } /** * Creating a correct File URL that OpenOffice can handle. This is * necessary to be platform independent. * * @param filelocation * @return */ public String createUNOFileURL(String filelocation) { java.io.File newfile = new java.io.File(filelocation); java.net.URL before = null; try { before = newfile.toURL(); } catch (MalformedURLException e) { System.out.println(e); } // Create a URL, which can be used by UNO String myUNOFileURL = com.sun.star.uri.ExternalUriReferenceTranslator .create(xComponentContext).translateToInternal(before.toExternalForm()); if (myUNOFileURL.length() == 0 && filelocation.length() > 0) { System.out.println("File URL conversion faild. Filelocation " + "contains illegal characters: " + filelocation); } return myUNOFileURL; } public void SaveDocument(XComponent document, String fileName) { // save document XStorable xStorable = (XStorable) UnoRuntime.queryInterface( XStorable.class, document); // Set properties for conversions PropertyValue[] conversionProperties = new PropertyValue[2]; conversionProperties[0] = new PropertyValue(); conversionProperties[0].Name = "Overwrite"; conversionProperties[0].Value = new Boolean(true); conversionProperties[1] = new PropertyValue(); conversionProperties[1].Name = "FilterName"; conversionProperties[1].Value = "writer_pdf_Export"; try { xStorable.storeToURL(createUNOFileURL(fileName), conversionProperties); } catch (IOException ex) { System.exit(5); } } // Refer to DevelopersGuide.pdf, p30-33, "2.3.4 First Connection". public void setupConnection() { XComponentContext localContext = null; try { localContext = com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null); } catch (java.lang.Exception ex) { System.err.println("Can't create initial component context"); //Logger.getLogger(OfficeUNOClientApp.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } // initial serviceManager XMultiComponentFactory xLocalServiceManager = localContext.getServiceManager(); // create a URL resolver Object urlResolver = null; try { urlResolver = xLocalServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext); } catch (Exception ex) { System.err.println("Can't create instance with context"); //Logger.getLogger(OfficeUNOClientApp.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } // query for the XUnoUrlResolver interface XUnoUrlResolver xUrlResolver = (XUnoUrlResolver) UnoRuntime.queryInterface(XUnoUrlResolver.class, urlResolver); // Import the object Object rInitialObject = null; try { rInitialObject = xUrlResolver.resolve(DEFAULT_CONNECTION_STRING); } catch (NoConnectException ex) { System.err.println("Can't connect to OOo service! Double check connection string: '" + DEFAULT_CONNECTION_STRING + "'"); //Logger.getLogger(OfficeUNOClientApp.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } catch (ConnectionSetupException ex) { System.err.println("Can't connect to OOo service! Double check connection string: '" + DEFAULT_CONNECTION_STRING + "'"); //Logger.getLogger(OfficeUNOClientApp.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } catch (IllegalArgumentException ex) { System.err.println("Wrong connection string, double check it!"); //Logger.getLogger(OfficeUNOClientApp.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } // XComponentContext if (null != rInitialObject) { // Create a service manager from the initial object XMultiComponentFactory xMCF = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class, rInitialObject); // Query for the XPropertySet interface. XPropertySet xpropertysetMultiComponentFactory = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xMCF); // Get the default context from the office server. Object objectDefaultContext = null; try { objectDefaultContext = xpropertysetMultiComponentFactory.getPropertyValue("DefaultContext"); } catch (UnknownPropertyException ex) { Logger.getLogger(OfficeUNOClientApp.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } catch (WrappedTargetException ex) { Logger.getLogger(OfficeUNOClientApp.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } // Query for the interface XComponentContext. xComponentContext = (XComponentContext) UnoRuntime.queryInterface( XComponentContext.class, objectDefaultContext); /* A desktop environment contains tasks with one or more frames in which components can be loaded. Desktop is the environment for components which can instanciate within frames. */ try { xCLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, xMCF.createInstanceWithContext( "com.sun.star.frame.Desktop", xComponentContext)); } catch (Exception exception) { Logger.getLogger(OfficeUNOClientApp.class.getName()).log(Level.SEVERE, null, exception); System.exit(1); } } else { System.err.println("given initial-object name unknown at server side"); System.exit(1); } } }