package openoffice;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
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 WordToPdf {
public static int DEFAULT_PORT = 8100;
public static String DEFAULT_HOST = "127.0.0.1";
/**
* 执行前,请启动openoffice服务
* 进入$OO_HOME\program下
* 执行soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
* @param xlsfile
* @param targetfile
* @throws Exception
*/
public static void SaveAs(String xlsfile, String targetfile)
throws Exception {
File xlsf = new File(xlsfile);
File targetF = new File(targetfile);
// 获得文件格式
DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
DocumentFormat pdfFormat = formatReg.getFormatByFileExtension("pdf");
DocumentFormat docFormat = formatReg.getFormatByFileExtension("doc");
// stream 流的形式
InputStream inputStream = new FileInputStream(xlsf);
OutputStream outputStream = new FileOutputStream(targetF);
/**
*
*/
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
System.out.println(connection);
try {
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
System.out.println("inputStream------" + inputStream);
System.out.println("outputStream------" + outputStream);
converter.convert(inputStream, docFormat, outputStream, pdfFormat);
} catch (ConnectException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
connection = null;
}
}
}
public static void main(String[] args){
System.out.println("begin...");
// String path1 = "D:/temp/111.doc";
// String path2 = "D:/temp/111.pdf";
try {
SaveAs(path1, path2);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ok!!!");
}
}
Linux启动OpenOffice服务:
一、启动office转换为pdf服务器【openoffice server 】
1、进入openoffice安装目录
cd opeonofiice的安装路径/program
2、启动端口监听
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard &
3、查看启动是否成功,存在8100端口即启动成功
netstat -an
如下所示:
[root@localhost program]# netstat -an|more
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address Stat
e
tcp 0 0 127.0.0.1:2208 0.0.0.0:* LIST
EN
tcp 0 0 127.0.0.1:8100 0.0.0.0:* LIST
EN
Linux暂停OpenOffice服务:
进入命令行 ps -a
找到进openoffice进程ID
然后输入 kill [进程ID]
jodconverter API:
http://jodconverter.sourceforge.net/api/