java使用openOffice 实现word转pdf

1、首先需要安装openOffice

2、下载jodconverter-2.2.2.jar

package com.toutiao_efficiency.modules.documet_file.service;

import java.io.File;
import java.util.Date;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

public class office2PDF {

	public static void main(String[] args) {

		Date startDate = new Date();
		String sourceFile = "E:\\oppo接口.docx";
		String destFile = "E:\\oppo接口123.pdf";
		try {
			System.out.println(office2PDF(sourceFile, destFile));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Date endDate = new Date();
		System.out.println("the cost time is " + (endDate.getTime() - startDate.getTime()));

	}

	public static int office2PDF(String sourceFile, String destFile) throws Exception {
		try {
			File inputFile = new File(sourceFile);
			if (!inputFile.exists()) {
				return -1;// 找不到源文件, 则返回-1
			}

			// 如果目标路径不存在, 则新建该路径
			File outputFile = new File(destFile);
			if (!outputFile.getParentFile().exists()) {
				outputFile.getParentFile().mkdirs();
			}

			// connect to an OpenOffice.org instance running on port 8100
			OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
			connection.connect();

			// convert
			DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
			converter.convert(inputFile, outputFile);

			// close the connection
			connection.disconnect();

			return 0;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return 1;
	}

}

 

你可能感兴趣的:(java)