java OpenOffice Pdf2Swf FlexPaper 使用總結

package theone.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ConnectException;
import java.util.Locale;
import java.util.ResourceBundle;
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 OpenOfficeUtil {

 private static String OpenOfficeBasePath = "D:\\Program Files\\OpenOffice.org 3";

 private static final String cmd_service = "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";

 static {
  ResourceBundle rb = ResourceBundle.getBundle("OpenOfficeUtil",
    Locale.getDefault());
  OpenOfficeBasePath = rb.getString("path");
  System.out.println(OpenOfficeBasePath);
 }

 /**
  * 將Office文檔轉換爲PDF. 運行該函數需要用到OpenOffice, OpenOffice下載地址爲
  * http://www.openoffice.org/
  * 
  * <pre>
  * 方法示例: 
  * String sourcePath = "F:\\office\\source.doc"; 
  * String destFile = "F:\\pdf\\dest.pdf"; 
  * Converter.office2PDF(sourcePath, destFile);
  * </pre>
  * 
  * @param sourceFile
  *            源文件, 絕對路徑. 可以是Office2003-2007全部格式的文檔, Office2010的沒測試. 包括.doc,
  *            .docx, .xls, .xlsx, .ppt, .pptx等. 示例: F:\\office\\source.doc
  * @param destFile
  *            目標文件. 絕對路徑. 示例: F:\\pdf\\dest.pdf
  * @return 操作成功與否的提示信息. 如果返回 -1, 表示找不到源文件, 或url.properties配置錯誤; 如果返回 0,
  *         則表示操作成功; 返回1, 則表示轉換失敗
  * @throws Exception
  */
 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();
   }
   String OpenOffice_HOME = OpenOfficeBasePath;// 這裏是OpenOffice的安裝目錄,
   // 如果從文件中讀取的URL地址最後一個字符不是 '\',則添加'\'
   if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\') {
    OpenOffice_HOME += "\\";
   }
   // 啓動OpenOffice的服務
   String command = OpenOffice_HOME + cmd_service;
   Process pro = Runtime.getRuntime().exec(command);
   System.out.println(command);
   // 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();
   // 關閉OpenOffice服務的進程
   pro.destroy();
   return 0;
  } catch (FileNotFoundException e) {
   e.printStackTrace();
   return -1;
  } catch (ConnectException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return 1;
 }

}


 

 

package theone.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

public class Pdf2SwfUtil {

	private static String pdf2swfPath = "D:\\Program Files\\SWFTools\\pdf2swf.exe";
	private static String cmd="{0} -o \"{1}\\{2}\" {3} -s flashversion=9 \"{4}\"";
	private static String fontCode="<SPAN style=\"COLOR: #ff0000\">-s languagedir={0}-chinese-simplified</SPAN>";
	static{
		ResourceBundle rb = ResourceBundle.getBundle("Pdf2SwfUtil",
				Locale.getDefault());
		pdf2swfPath = rb.getString("path");
	}
	private static String getCmdStr(String sourcePath, String destPath,
			String fileName){
		return MessageFormat.format(cmd, pdf2swfPath,destPath,fileName,"",sourcePath);
	}
	
	public static int convertPDF2SWF(String sourcePath, String destPath,
			String fileName) throws IOException {
		// 目標路徑不存在則建立目標路徑
		File dest = new File(destPath);
		if (!dest.exists())
			dest.mkdirs();

		// 源文件不存在則返回
		File source = new File(sourcePath);
		if (!source.exists())
			return 0;

		// 調用pdf2swf命令進行轉換
		String command = getCmdStr(sourcePath,destPath,fileName);
		System.out.println(command);

		Process pro = Runtime.getRuntime().exec(command);

		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(pro.getInputStream()));
		while (bufferedReader.readLine() != null)
			;

		try {
			pro.waitFor();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		return pro.exitValue();

	}
}

 

 

Java利用OpenOffice將word等office文檔轉換成PDF  

2012-12-10 19:02:34|  分類:JAVA |  標籤:openoffice  |字號 訂閱

Java利用OpenOffice將word等office文檔轉換成PDF


 OpenOffice.org 是一套跨平臺的辦公室軟件套件,能在 Windows、Linux、MacOS X (X11)、和 Solaris 等操作系統上執行。它與各個主要的辦公室軟件套件兼容。OpenOffice.org 是自由軟件,任何人都可以免費下載、使用、及推廣它。


OpenOffice org 的 API 以 UNO (UniversalNetwork Object) 寫成,所以本身是電腦語言中立的。現在來說,OpenOffice org主要是以 C++ 撰寫的,但也能以 Java(TM) 來撰寫。

1. 需要用的軟件

    OpenOffice 下載地址http://www.openoffice.org/

    JodConverter 下載地址http://sourceforge.net/projects/jodconverter/files/JODConverter/也可以直接從附件裏面下載

 

 

2.啓動OpenOffice的服務

    我到網上查如何利用OpenOffice進行轉碼的時候,都是需要先用cmd啓動一個soffice服務,啓動的命令是:soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;"。

    但是實際上,對於我的項目,進行轉碼只是偶爾進行,然而當OpenOffice的轉碼服務啓動以後,該進程(進程名稱是soffice.exe)會一直存在,並且大約佔100M的內存,感覺非常浪費。於是我就想了一個辦法,可以將執行該服務的命令直接在JAVA代碼裏面調用,然後當轉碼完成的時候,直接幹掉這個進程。在後面的JAVA代碼裏面會有解釋。

    所以,實際上,這第2步可以直接跳過

 

 

3.將JodConverter相關的jar包添加到項目中

    將JodConverter解壓縮以後,把lib下面的jar包全部添加到項目中

 

 

4. 下面就是重點嘍,詳見Java代碼解析

 

附件裏面有現成的可以用的項目示例,直接導入eclipse就可以運行

 

Java代碼 
  1. /** 
  2.      * 將Office文檔轉換爲PDF. 運行該函數需要用到OpenOffice, OpenOffice下載地址爲 
  3.      * http://www.openoffice.org/ 
  4.      *  
  5.      * <pre> 
  6.      * 方法示例: 
  7.      * String sourcePath = "F:\\office\\source.doc"; 
  8.      * String destFile = "F:\\pdf\\dest.pdf"; 
  9.      * Converter.office2PDF(sourcePath, destFile); 
  10.      * </pre> 
  11.      *  
  12.      * @param sourceFile 
  13.      *            源文件, 絕對路徑. 可以是Office2003-2007全部格式的文檔, Office2010的沒測試. 包括.doc, 
  14.      *            .docx, .xls, .xlsx, .ppt, .pptx等. 示例: F:\\office\\source.doc 
  15.      * @param destFile 
  16.      *            目標文件. 絕對路徑. 示例: F:\\pdf\\dest.pdf 
  17.      * @return 操作成功與否的提示信息. 如果返回 -1, 表示找不到源文件, 或url.properties配置錯誤; 如果返回 0, 
  18.      *         則表示操作成功; 返回1, 則表示轉換失敗 
  19.      */  
  20.     public static int office2PDF(String sourceFile, String destFile) {  
  21.         try {  
  22.             File inputFile = new File(sourceFile);  
  23.             if (!inputFile.exists()) {  
  24.                 return -1;// 找不到源文件, 則返回-1  
  25.             }  
  26.   
  27.             // 如果目標路徑不存在, 則新建該路徑  
  28.             File outputFile = new File(destFile);  
  29.             if (!outputFile.getParentFile().exists()) {  
  30.                 outputFile.getParentFile().mkdirs();  
  31.             }  
  32.   
  33.             String OpenOffice_HOME = "D:\\Program Files\\OpenOffice.org 3";//這裏是OpenOffice的安裝目錄, 在我的項目中,爲了便於拓展接口,沒有直接寫成這個樣子,但是這樣是絕對沒問題的  
  34.             // 如果從文件中讀取的URL地址最後一個字符不是 '\',則添加'\'  
  35.             if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\') {  
  36.                 OpenOffice_HOME += "\\";  
  37.             }  
  38.             // 啓動OpenOffice的服務  
  39.             String command = OpenOffice_HOME  
  40.                     + "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";  
  41.             Process pro = Runtime.getRuntime().exec(command);  
  42.             // connect to an OpenOffice.org instance running on port 8100  
  43.             OpenOfficeConnection connection = new SocketOpenOfficeConnection(  
  44.                     "127.0.0.1"8100);  
  45.             connection.connect();  
  46.   
  47.             // convert  
  48.             DocumentConverter converter = new OpenOfficeDocumentConverter(  
  49.                     connection);  
  50.             converter.convert(inputFile, outputFile);  
  51.   
  52.             // close the connection  
  53.             connection.disconnect();  
  54.             // 關閉OpenOffice服務的進程  
  55.             pro.destroy();  
  56.   
  57.             return 0;  
  58.         } catch (FileNotFoundException e) {  
  59.             e.printStackTrace();  
  60.             return -1;  
  61.         } catch (ConnectException e) {  
  62.             e.printStackTrace();  
  63.         } catch (IOException e) {  
  64.             e.printStackTrace();  
  65.         }  
  66.   
  67.         return 1;  
  68.     }

 

 

 


參考資料(解決flexpapaer一直處於加載狀態的 轉載)

     本文章只研究演示Flexpaper在WEB頁面上的使用,我們要下載一個Flash版本的FlexPaper,這裏我選擇了FlexPaper_1.5.0_flash。

下載地址:http://code.google.com/p/flexpaper/downloads/list

下載、解壓後,可以看到包含如下文件: 

        如何使用flexpaper加載swf文件 - 友友 - 油子家園

主要文件、文件夾說明:

Examples  存放Flexpaper使用例子

Js        存放Flexpaper調用的JS文件

Php       存放PHP使用的文檔、JS、庫、SWF文件

Index.html 例子主頁

FlexpaperViewer Flexpaper的核心文件,用於瀏覽PDF

Paper.swf  官方的默認宣傳文件

playerProductInstall.swf  如果客戶端瀏覽器的flashplayer版本過低,他是不會嵌入你的swf,而是嵌入這個playerProductInstall.swf到頁面上下載flashplayer的安裝文件。

 

下面是第一個Flexpaper例子

一個最簡單的例子,我們主要用到FlexpaperViewer.swf、JS文件夾中的flexpaper_flash.js

創建HTML頁面test.html,代碼如下:

<HTML>

 <HEAD>

  <TITLE>ajava.org Flexpaper例子</TITLE>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

 </HEAD>

<BODY>

<script type="text/javascript" src="js/flexpaper_flash.js"></script>

 

<div style="position:absolute;left:10px;top:10px;">

            <p id="viewerPlaceHolder" style="width:660px;height:553px;display:block">Document loading..</p>

            <script type="text/javascript">                

                var fp = new FlexPaperViewer(  

                         'FlexPaperViewer',

                         'viewerPlaceHolder', { config : {

                         SwfFile : escape('FusionCharts.swf'),

                         Scale : 0.6,

                         ZoomTransition : 'easeOut',

                         ZoomTime : 0.5,

                         ZoomInterval : 0.2,

                         FitPageOnLoad : true,

                         FitWidthOnLoad : false,

                         FullScreenAsMaxWindow : false,

                         ProgressiveLoading : false,

                         MinZoomSize : 0.2,

                         MaxZoomSize : 5,

                         SearchMatchAll : false,

                         InitViewMode : 'Portrait',

                         PrintPaperAsBitmap : false,

                         ViewModeToolsVisible : true,

                         ZoomToolsVisible : true,

                         NavToolsVisible : true,

                         CursorToolsVisible : true,

                         SearchToolsVisible : true,                        

                         localeChain: 'en_US' 

                         }});  

            </script>

</div>

</BODY>

</HTML>

 

把第三章部分生產的FusionCharts.swf複製到FlexPaper根目錄下,我這裏是 F:\FlexPaper1.5.0flash,這一步是必須的,如果不是test.html怎樣讀取到FusionCharts.swf呢?

測試:

打開瀏覽器,輸入test.html的本地地址,就可以看到FlexPaper的瀏覽效果。這裏我分別在前言中的3種測試環境,結果都沒問題,效果如下圖:

如何使用flexpaper加載swf文件 - 友友 - 油子家園

如果你用FF瀏覽器,出現提示“SecurityError: Error #2148: SWF 文件 file:/// F:/FlexPaper1.5.0flash /FlexPaperViewer.swf 不能訪問本地資源FusionCharts.swf。只有僅限於文件系統的 SWF 文件和可信的本地 SWF 文件可以訪問本地資源。”,或者IE一直都處於加載狀態,這種情況,是由於Flexpaper還沒獲得Adobe Flash的信任,這時你可以請訪問 http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065,選擇始終允許,把FlexPaper1.5.0flash文件夾添加到信任列表中。

 

如何使用flexpaper加載swf文件 - 友友 - 油子家園

 (個人微信號)  (技術公衆號)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章