Sun, July 24, 2005
OpenOfficeOrgでPDFを生成(プログラムから)
MS-Officeのドキュメントをサーバ側でPDF化したい場合がある。 いい方法はないものかと探していたところ、OpenOfficeOrgを使うことで、 解決できることがわかった。
OpenOfficeOrgはJavaやJythonなどを使って、プログラム的に
ドキュメントを操作することができる。
もともと、OpenOfficeOrgには、PDFでドキュメントを出力する機能が付いているので、
これをプログラムから処理してやればよいことになる。
複数あるMS-ワードのドキュメントを一括処理で、まとめてPDF化したい場合など、 OpenOfficeOrgのAPIを使って、Javaプログラムから操作できるのはグッド。
ただ、処理内容は単純なのだが、記述がややこしいのが難点。
code
import java.io.File;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.view.XPrintable;
public class CreatePDF {
public static void main(String args[]) {
try {
args=new String[]{"test.sxw"};
String sConnectionString = "uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager";
/* Bootstraps a component context with the jurt base components
registered. Component context to be granted to a component for running.
Arbitrary values can be retrieved from the context. */
XComponentContext xcomponentcontext =
com.sun.star.comp.helper.Bootstrap.createInitialComponentContext( null );
/* Gets the service manager instance to be used (or null). This method has
been added for convenience, because the service manager is a often used
object. */
XMultiComponentFactory xmulticomponentfactory =
xcomponentcontext.getServiceManager();
/* Creates an instance of the component UnoUrlResolver which
supports the services specified by the factory. */
Object objectUrlResolver =
xmulticomponentfactory.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", xcomponentcontext );
// Create a new url resolver
XUnoUrlResolver xurlresolver = ( XUnoUrlResolver )
UnoRuntime.queryInterface( XUnoUrlResolver.class,
objectUrlResolver );
// Resolves an object that is specified as follow:
// uno:<connection description>;<protocol description>;<initial object name>
Object objectInitial = xurlresolver.resolve( sConnectionString );
// Create a service manager from the initial object
xmulticomponentfactory = ( XMultiComponentFactory )
UnoRuntime.queryInterface( XMultiComponentFactory.class, objectInitial );
// Query for the XPropertySet interface.
XPropertySet xpropertysetMultiComponentFactory = ( XPropertySet )
UnoRuntime.queryInterface( XPropertySet.class, xmulticomponentfactory );
// Get the default context from the office server.
Object objectDefaultContext =
xpropertysetMultiComponentFactory.getPropertyValue( "DefaultContext" );
// 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. */
XComponentLoader xcomponentloader = ( XComponentLoader )
UnoRuntime.queryInterface( XComponentLoader.class,
xmulticomponentfactory.createInstanceWithContext(
"com.sun.star.frame.Desktop", xcomponentcontext ) );
String sUrl = args[0];
if ( sUrl.indexOf("private:") != 0) {
java.io.File sourceFile = new java.io.File(args[0]);
StringBuffer sTmp = new StringBuffer("file:///");
sTmp.append(sourceFile.getCanonicalPath().replace('\\', '/'));
sUrl = sTmp.toString();
}
/*
// Load a Writer document, which will be automaticly displayed
XComponent xcomponent = xcomponentloader.loadComponentFromURL(
sUrl, "_blank", 0,
new PropertyValue[0] );
*/
PropertyValue[] loadProps = new PropertyValue[1];
loadProps[0] = new PropertyValue();
loadProps[0].Name = "Hidden";
loadProps[0].Value = new Boolean(true);
XComponent xcomponent = xcomponentloader.loadComponentFromURL(
sUrl, "_blank", 0,loadProps);
new CreatePDF().saveAsPDF(xcomponent,new File("test.pdf"));
System.exit(0);
}
catch( Exception exception ) {
System.err.println( exception );
}
}
private void saveAsPDF(XComponent xDoc,File file) throws Exception{
java.io.File sourceFile = file;
StringBuffer sTmp = new StringBuffer("file:///");
sTmp.append(sourceFile.getCanonicalPath().replace('\\', '/'));
String sUrl = sTmp.toString();
storeDocComponent(xDoc,sUrl);
xDoc.dispose();
}
private void storeDocComponent(XComponent xDoc, String storeUrl) throws java.lang.Exception {
XStorable xStorable = (XStorable)UnoRuntime.queryInterface(XStorable.class, xDoc);
PropertyValue[] storeProps = new PropertyValue[1];
storeProps[0] = new PropertyValue();
storeProps[0].Name = "FilterName";
storeProps[0].Value = "writer_pdf_Export";
// storeProps[0].Value = "MS Word 97";
// xStorable.storeAsURL(storeUrl, storeProps);
xStorable.storeToURL(storeUrl, storeProps);
}
private void printDocComponent(XComponent xDoc) throws java.lang.Exception {
XPrintable xPrintable = (XPrintable)UnoRuntime.queryInterface(XPrintable.class, xDoc);
PropertyValue[] printerDesc = new PropertyValue[1];
printerDesc[0] = new PropertyValue();
printerDesc[0].Name = "Name";
// printerDesc[0].Value = "5D PDF Creator";
printerDesc[0].Value = "Adobe PDF";
xPrintable.setPrinter(printerDesc);
PropertyValue[] printOpts = new PropertyValue[1];
printOpts[0] = new PropertyValue();
printOpts[0].Name = "Pages";
printOpts[0].Value = "1";
// printOpts[0].Value = "3-5,7";
xPrintable.print(printOpts);
}
}
※作動させるには、 [OfficePath]/program/classes/*.jar をクラスパスに含める必要がある。