首先,运行-cmd,输入cd c:\Program Files\OpenOffice.org 3\program,回车
在输入soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard,回车
(在运行下面的程序,cmd.exe程序不要关闭,转换完之后再)
需要的包在下面附件中
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.List;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
public class Main {
public static void main(String[] args) {
String host = "127.0.0.1";
int port = 8100;
String folder = "E:\\1\\";//将此目录下的所有doc、docx文件转成pdf
List<File> inputList = new ArrayList<File>();
File tempFile = new File(folder);
List<String> pathList = new ArrayList<String>();
if (tempFile.exists()) {
if (tempFile.isFile()) {
pathList.add(tempFile.getPath());
} else {
List<File> dirList = new ArrayList<File>();
dirList.add(tempFile);
while (!dirList.isEmpty()) {
for (String dir : dirList.get(0).list()) {
if (new File(String.format("%s\\%s", dirList.get(0)
.getPath(), dir)).isDirectory()) {//isDirectory()测试此抽象路径名表示的文件是否是一个目录。
dirList.add(new File(String.format("%s\\%s",
dirList.get(0).getPath(), dir)));
} else {
pathList.add(String.format("%s\\%s", dirList.get(0)
.getPath(), dir));
}
}
dirList.remove(dirList.get(0));
}
}
}
for (String path : pathList) {
if (path.lastIndexOf(".doc") >= ".doc".length()) {
File inputFile = new File(path);//要转化的文件
String outputName = inputFile.getName().substring(0,
inputFile.getName().lastIndexOf("."));
File outputFile = new File(String.format("%s\\%s.pdf",
inputFile.getParent(), outputName));//转化后的pdf文件
if (!outputFile.exists()) {
try {
outputFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
boolean _result = false;
OpenOfficeConnection ooConn;
// default host is localhost
if (host == null || host.equals("")) {
ooConn = new SocketOpenOfficeConnection(port);
} else {
ooConn = new SocketOpenOfficeConnection(host, port);
}
try {
ooConn.connect();
DocumentFormat outputFormat = new DocumentFormat(
"Portable Document Format", "application/pdf", "pdf");
DocumentConverter docConverter = new OpenOfficeDocumentConverter(
ooConn);
docConverter.convert(inputFile, outputFile);
_result = true;
} catch (ConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (ooConn != null) {
ooConn.disconnect();
}
}
System.out.println(String.format("%s is Converted!", inputFile
.getPath()));
}
}
}
}