天天看點

利用openoffice進行各種格式轉換為PDF

參考:https://blog.csdn.net/liumiaocn/article/details/73480915

openoffice有window和linux版本,通過安裝openoffice軟體,在java裡頭進行調用它來實作各種格式的轉換,

核心代碼如下

/**
	 * 将Office文檔轉換為PDF. 運作該函數需要用到OpenOffice, OpenOffice下載下傳位址為
	 * http://www.openoffice.org
	 * <pre>
	 * 方法示例:
	 * window系統下
	 * String sourcePath = "F:\\office\\source.doc";
	 * String destFile = "F:\\pdf\\dest.pdf";
	 * Office2PDF.office2PDF(sourcePath, destFile);
	 * linux系統下
	 * String sourcePath = "/office/source.doc";
	 * String destFile = "/pdf/dest.pdf";
	 * Office2PDF.office2PDF(sourcePath, destFile);
	 * </pre>
	 * @param sourceFile
	 *            源檔案, 絕對路徑. 可以是Office2003-2007全部格式的文檔
	 *            包括.doc,.docx, .xls, .xlsx, .ppt, .pptx等
	 * @param destFile
	 *            目标檔案. 絕對路徑.
	 * @return 操作成功與否的提示資訊. 
	 * 		         如果傳回 -1,表示找不到源檔案
	 * 		         如果傳回 0 ,表示轉換失敗
	 *         如果傳回 1 ,表示操作成功
	 */
	public static int office2PDF(String sourceFile, String destFile) {
		Process pro = null;
		OpenOfficeConnection connection = null;
		try {
			File inputFile = new File(sourceFile);
			if (!inputFile.exists()) {
				return -1;// 找不到源檔案, 則傳回-1
			}
			// 如果目标路徑不存在, 則建立該路徑
			File outputFile = new File(destFile);
			if (!outputFile.getParentFile().exists()) {
				outputFile.getParentFile().mkdirs();
			}
			String OpenOffice_HOME = OPEN_OFFICE_HOME;
			if (OpenOffice_HOME == null || OpenOffice_HOME =="") {
				return -1;
			}
			
			String separator = System.getProperty("file.separator");
			if (OpenOffice_HOME.substring(OpenOffice_HOME.length()-1) != separator) {
				OpenOffice_HOME += separator;
			}
			String sofficeProgram = "/".equals(separator)?"soffice":"soffice.exe";
			// 啟動OpenOffice的服務
			String ooProgram = "program" + separator + sofficeProgram + " -headless -accept=\"socket,host=%s,port=%s;urp;\" -nofirststartwizard";
			String command = OpenOffice_HOME + String.format(ooProgram, OPEN_OFFICE_IP,OPEN_OFFICE_PORT);
			pro = Runtime.getRuntime().exec(command);
			connection = new SocketOpenOfficeConnection(OPEN_OFFICE_IP, Integer.parseInt(OPEN_OFFICE_PORT));
			connection.connect();
			//調用openoffice轉換格式類進行轉換
			DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
			converter.convert(inputFile, outputFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return -1;
		} catch (ConnectException e) {
			e.printStackTrace();
			return 0;
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		}finally {
			//關閉連接配接
			if(connection != null && connection.isConnected()) {
				connection.disconnect();
			}
			// 關閉OpenOffice服務的程序
			if(pro != null) {
				pro.destroy();
			}
		}
		return 1;
	}
           

 在window上進行轉換速度正常,字型也正常,linux下會亂碼需要拷貝字型到/usr/share/fonts下來解決亂碼問題,速度上很慢,目前還沒有找到解決方案,需要依賴的包,參考如下pom.xml的配置

利用openoffice進行各種格式轉換為PDF