Here you go. This is a VERY early example that I cobbled together to convert
Word documents into pdf files but you would not need to change anything as
OpenOffice works out what to do from the file's extension. Feel free to play
with the code but, as I said, I would simply download and use JODConverter
and would never have written this if I have known about that utility back
then.
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.frame.XDesktop;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.XComponentContext;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.lang.XComponent;
import com.sun.star.text.XTextDocument;
import com.sun.star.beans.PropertyValue;
import com.sun.star.frame.XStorable;
import com.sun.star.util.XCloseable;
/**
* This class has a single purpose - to convert files between the Microsoft
* Word and Portable Document Formats. There is a single, public, static
method
* that is called to perform the conversion process in this manner;
*
* ConvertWordToPDF.convertToPDF(String wordFilename, String pdfFilename);
*
* The parameters should both contain the full path to and name of a file in
the
* 'typical' format, i.e. 'C:\\folder\\filename.ext'. Whilst the input file
will
* be checked and validated - to see if it actually exists - the output file
* will not be. As a result, if that file already exists, it will simply be
* over-written.
*
* @author MarkB
* @version 1.00 26th December 2008
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN
* NO EVENT SHALL THE author OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
public class ConvertWordToPDF {
public static final void converToPDF(String wordFilename, String
pdfFilename)
throws NullPointerException,
IllegalArgumentException,
FileNotFoundException
{
// Validate parameters
if(wordFilename == null) {
throw new NullPointerException("A null value was passed to the "
+
"wordFilename parameter of the ConvertWordToPDF." +
"convertToPDF() method.");
}
if(pdfFilename == null) {
throw new NullPointerException("A null value was passed to the "
+
"pdfFilename parameter of the ConvertWordToPDF." +
"convertToPDF() method.");
}
if(wordFilename.isEmpty()) {
throw new IllegalArgumentException("An empty String was passed
to " +
"the wordFilename parameter of the ConvertWordToPDF." +
"convertToPDF() method.");
}
if(pdfFilename.isEmpty()) {
throw new IllegalArgumentException("An empty String was passed
to " +
"the pdfFilename parameter of the ConvertWordToPDF." +
"convertToPDF() method.");
}
ConvertWordToPDF.validateFilename(wordFilename);
// Convert from filename to URLs
String wordFileURL = ConvertWordToPDF.toURL(wordFilename);
String pdfFileURL = ConvertWordToPDF.toURL(pdfFilename);
// If both convert successfully...
if(wordFileURL != null && pdfFileURL != null) {
XDesktop desktop = null;
XMultiComponentFactory componentFactory = null;
XComponentContext componentContext = null;
XComponentLoader compLoader = null;
XComponent wordComponent = null;
XTextDocument wordDocument = null;
XStorable storeable = null;
XCloseable closeable = null;
PropertyValue[] propertyValues = null;
// Connect to OpenOffice and convert the document.
try {
System.out.println("Connecting to OpenOffice.....");
componentContext =
com.sun.star.comp.helper.Bootstrap.bootstrap();
componentFactory = componentContext.getServiceManager();
if(componentFactory != null) {
System.out.println("Getting Desktop object.....");
Object oDesktop =
componentFactory.createInstanceWithContext(
"com.sun.star.frame.Desktop", componentContext);
desktop = (XDesktop) UnoRuntime.queryInterface(
XDesktop.class, oDesktop);
System.out.println("Getting component loader.....");
compLoader = (XComponentLoader)
UnoRuntime.queryInterface(
XComponentLoader.class, desktop);
// The user will not see OpenOffice as the value of the
// Hidden attribute is true. Simply change this to false
// if you wish to observe the process.
propertyValues = new PropertyValue[1];
propertyValues[0] = new PropertyValue();
propertyValues[0].Name = "Hidden";
propertyValues[0].Value = new Boolean(true);
System.out.println("Loading Word
component/document.....");
wordComponent = compLoader.loadComponentFromURL(
wordFileURL, "_blank", 0, propertyValues);
wordDocument = (XTextDocument)
UnoRuntime.queryInterface(
XTextDocument.class, wordComponent);
propertyValues = new PropertyValue[2];
propertyValues[0] = new PropertyValue();
propertyValues[0].Name = "Overwrite";
propertyValues[0].Value = new Boolean(true);
// Note that only the FilterName attribute is actually
set
// here. It is possible to exercise quite fine control
over
// the conversion process by passing an additional array
// of attributes under the FilterData name. Currently,
thise
// option is not supported but it could be added if
required.
propertyValues[1] = new PropertyValue();
propertyValues[1].Name = "FilterName";
propertyValues[1].Value = "writer_pdf_Export";
System.out.println("Converting and storing PDF.....");
storeable = (XStorable) UnoRuntime.queryInterface(
XStorable.class, wordDocument);
storeable.storeToURL(pdfFileURL, propertyValues);
System.out.println("Closing.....");
closeable = (XCloseable) UnoRuntime.queryInterface(
XCloseable.class, wordDocument);
closeable.close(false);
propertyValues = null;
wordDocument = null;
wordComponent = null;
compLoader = null;
desktop = null;
componentFactory = null;
componentContext = null;
System.exit(0);
}
else {
System.out.println("Cannot create desktop.....");
System.exit(1);
}
}
catch(Exception ex) {
System.out.println("Connecting to OpenOffice to perform " +
"conversion and an exception has been thrown.");
System.out.println("Type: " + ex.getClass().getName());
System.out.println("Message: " + ex.getMessage());
System.out.println("Stacktrace follows.....");
ex.printStackTrace(System.out);
System.exit(1);
}
}
else {
StringBuffer buffer = new StringBuffer(wordFileURL == null ?
"The wordFilename " : "The pdfFilename ");
buffer.append("parameter was passed a value that could not be
converted into a valid URL.");
System.out.println(buffer.toString());
System.exit(1);
}
}
/**
* Check that a file actually exists.
*
* @param fileName a String object encapsulating the name of the file.
*
* @throws java.io.FileNotFoundException thrown if the file cannot be
found.
*/
private static final void validateFilename(String fileName) throws
FileNotFoundException {
File file = new File(fileName);
if(!file.exists()) {
throw new FileNotFoundException("The file " +
fileName +
" does not exist.");
}
}
/**
* Convert a filename from the 'typical' Windows format of something
like
* 'C:\\folder\\filename.ext' to a URL format like this;
* 'file:///C:/folder/filename.ext'. The method will return a valid URL
* if it is able to perform the conversion and a null value otherwise.
*
* @param filename a String object encapsulating the path to and name of
the
* file.
*
* @return An instance of the java.lang.String class encapsulating the
* URL. As the conversion process makes use of the file system. it
is
* possible that an IOException could be thrown. If this occurs
then
* a null value will be returned.
*/
private static final String toURL(String filename) {
try {
StringBuffer buffer = new StringBuffer("file:///");
buffer.append(new
File(filename).getCanonicalPath().replace('\\', '/'));
return(buffer.toString());
}
catch(IOException ioEx) {
return(null);
}
}
}
I have a far better example but it is quite complex - featuring over-ridden
methods to do various additional things - and I felt it would confuse not
assist.
Yours
Mark B
--
View this message in context:
http://apache-poi.1045710.n5.nabble.com/convert-poi-generated-excel-to-pdf-tp3362053p3362502.html
Sent from the POI - User mailing list archive at Nabble.com.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]