從Loader對(duì)象可以加載一篇文檔:
private static Object loadDocument(XComponentLoader loader, String inputFilePath) throws Exception { // Preparing properties for loading the document PropertyValue[] propertyValues = new PropertyValue[1]; propertyValues[0] = new PropertyValue(); propertyValues[0].Name = "Hidden"; propertyValues[0].Value = new Boolean(true); // Composing the URL by replacing all backslashs File inputFile = new File(inputFilePath); String inputUrl = "file:///" + inputFile.getAbsolutePath().replace('\\', '/'); return loader.loadComponentFromURL(inputUrl, "_blank", 0, propertyValues); }
接著自然就是文檔轉(zhuǎn)換了:
private static void convertDocument(Object doc, String outputFilePath, String convertType) throws Exception { // Preparing properties for converting the document PropertyValue[] propertyValues = new PropertyValue[2]; // Setting the flag for overwriting propertyValues[0] = new PropertyValue(); propertyValues[0].Name = "Overwrite"; propertyValues[0].Value = new Boolean(true); // Setting the filter name propertyValues[1] = new PropertyValue(); propertyValues[1].Name = "FilterName"; propertyValues[1].Value = convertType; // Composing the URL by replacing all backslashs File outputFile = new File(outputFilePath); String outputUrl = "file:///" + outputFile.getAbsolutePath().replace('\\', '/'); // Getting an object that will offer a simple way to store // a document to a URL. XStorable storable = UnoRuntime.queryInterface(XStorable.class, doc); // Storing and converting the document storable.storeAsURL(outputUrl, propertyValues); }
最后還要關(guān)閉文檔:
private static void closeDocument(Object doc) throws Exception { // Closing the converted document. Use XCloseable.clsoe if the // interface is supported, otherwise use XComponent.dispose XCloseable closeable = UnoRuntime.queryInterface(XCloseable.class, doc); if (closeable != null) { closeable.close(false); } else { XComponent component = UnoRuntime.queryInterface(XComponent.class, doc); component.dispose(); } }
最后便是將上面四個(gè)步驟串聯(lián)起來(lái):
public static void main(String args[]) { String inputFilePath = "D:\\convert\\input.txt"; String outputFilePath = "D:\\convert\\output.doc"; // the given type to convert to String convertType = "swriter: MS Word 97"; try { XComponentContext context = createContext(); System.out.println("connected to a running office ..."); XComponentLoader compLoader = createLoader(context); System.out.println("loader created ..."); Object doc = loadDocument(compLoader, inputFilePath); System.out.println("document loaded ..."); convertDocument(doc, outputFilePath, convertType); System.out.println("document converted ..."); closeDocument(doc); System.out.println("document closed ..."); System.exit(0); } catch (Exception e) { e.printStackTrace(System.err); System.exit(1); } }
出處:老趙點(diǎn)滴
責(zé)任編輯:bluehearts
上一頁(yè) 使用OpenOffice.org將各類文檔轉(zhuǎn)為PDF [1] 下一頁(yè) 使用OpenOffice.org將各類文檔轉(zhuǎn)為PDF [3]
◎進(jìn)入論壇網(wǎng)絡(luò)編程版塊參加討論
|