當下做一個項目,就是各種操作office,客戶的需求總是各種不按常理,來需求就得搞啊.對JAVA操作office這方面真是頭大,弟弟是真滴不懂不會啊。無奈只好試啊試的。網上一大堆好使的,一大堆不好使的。整了一大堆word轉PDF的方法。但是客戶要求有水印,又不想花錢。硬着頭皮試了一堆。雖說暫時還都沒采用,但是收獲也是有的。
以下都是親測可用的(很多都是借鑒了前輩的博文)一來給自己用(畢竟我記性不好), 二來是希望能對看到本博客的帥哥靚妹們有點用處,免得一用都是不好使的。
以下方法都是轉換結果比較可觀的。。。。要用哪個自己斟酌
本博客的方法也許會不斷的增加。有心自己看吧!!
----------------------------------------------------第一種方法 ------------------------------------------------
JobConverter + OpenOffice ( Windows系統下 )
JobConverter的jar包下載地址 : 點我去下載
OpenOffice的下載地址 : 點我去下載
OpenOffice 的安裝路徑自己定義。 代碼中要使用對應路徑調用啟動服務 (此處友情提示)
import java.io.File;
import java.io.IOException;
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;
// 將word格式的文件轉換為pdf格式
public static void WordToPDF(String startFile, String overFile) throws IOException {
// 源文件目錄
File inputFile = new File(startFile);
if (!inputFile.exists()) {
System.out.println("源文件不存在!");
return;
}
// 輸出文件目錄
File outputFile = new File(overFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().exists();
}
// 調用openoffice服務線程
/** 我把openOffice下載到了 C:/Program Files (x86)/下 ,下面的寫法自己修改編輯就可以**/
String command = "C:/Program Files (x86)/OpenOffice 4/program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
Process p = Runtime.getRuntime().exec(command);
// 連接openoffice服務
OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
connection.connect();
// 轉換
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(inputFile, outputFile);
// 關閉連接
connection.disconnect();
// 關閉進程
p.destroy();
}
public static void main(String[] args) {
String start = "F:\\新建文件夾\\我是word測試文件.docx";
String over = "F:\\新建文件夾\\成了.pdf";
try {
WordToPDF(start, over);
} catch (IOException e) {
e.printStackTrace();
}
}
-
-
-
-
-
----------------------------------------------------第二種方法 ------------------------------------------------
SaveAsPDFandXPS + jacob (Windows操作系統下,電腦里有office)
SaveAsPDFandXPS 下載地址 : 點我去下載
jacob 的jar包 下載地址 : 點我去下載
先安裝SaveAsPDFandXPS ,安裝成功后 , 打開jacob的jar包 ,里面的結構應該是這樣的
把jacob.jar 放到項目下 , 然后 這里注意 把 兩個后綴為dll的文件 放到 jre目錄bin的里面 必須放進去 不然會報錯(java.lang.NoClassDefFoundError) ,
實在不懂看此圖 如果是默認安裝 大概就是這個文件里面。
然后准備就緒 對應代碼
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
private static final int wdFormatPDF = 17;// PDF 格式
public static void wordToPDF(){
ActiveXComponent app = null;
Dispatch doc = null;
try {
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("Documents").toDispatch();
//轉換前的文件路徑
String startFile = "F:\\新建文件夾\\我是word版本" + ".doc";
//轉換后的文件路勁
String overFile = "F:\\新建文件夾\\我是轉換后的pdf文件" + ".pdf";
doc = Dispatch.call(docs, "Open" , startFile).toDispatch();
File tofile = new File(overFile);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc,"SaveAs", overFile, wdFormatPDF);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
Dispatch.call(doc,"Close",false);
if (app != null)
app.invoke("Quit", new Variant[] {});
}
//結束后關閉進程
ComThread.Release();
}
public static void main(String[] args) {
wordToPDF();
}
-
-
-
-
-
-----------------------------------------------第三種方法----------------------------------------------
這種方法純屬是搜刮出來的,因為測試好用。所以也弄了上來。這個里面依賴的jar包挺麻煩的。但是只要導入jar包就可以獲得立竿見影的效果,缺點可能就速度上比較上面兩種能慢一些,還有就是支持的是docx的文檔格式 。
我把所有jar包一點一點的搜集起來整合了一下。(jar包的版本也會造成問題。所以我整合了一版)
大家可以去這里下載→ 整合版jar包下載地址
這個代碼相比較上面兩種就比較容易了。導入jar包就能用。
廢話不說。貼代碼
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
import org.apache.poi.xwpf.converter.core.utils.StringUtils;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class WordToPDF {
/**
* 將word文檔, 轉換成pdf, 中間替換掉變量
* @param source 源為word文檔, 必須為docx文檔
* @param target 目標輸出
* @param params 需要替換的變量
* @throws Exception
*/
public static void wordConverterToPdf(InputStream source,
OutputStream target, Map<String, String> params) throws Exception {
wordConverterToPdf(source, target, null, params);
}
/**
* 將word文檔, 轉換成pdf, 中間替換掉變量
* @param source 源為word文檔, 必須為docx文檔
* @param target 目標輸出
* @param params 需要替換的變量
* @param options PdfOptions.create().fontEncoding( "windows-1250" ) 或者其他
* @throws Exception
*/
public static void wordConverterToPdf(InputStream source, OutputStream target,
PdfOptions options,
Map<String, String> params) throws Exception {
XWPFDocument doc = new XWPFDocument(source);
paragraphReplace(doc.getParagraphs(), params);
for (XWPFTable table : doc.getTables()) {
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
paragraphReplace(cell.getParagraphs(), params);
}
}
}
PdfConverter.getInstance().convert(doc, target, options);
}
/** 替換段落中內容 */
private static void paragraphReplace(List<XWPFParagraph> paragraphs, Map<String, String> params) {
if (MapUtils.isNotEmpty(params)) {
for (XWPFParagraph p : paragraphs){
for (XWPFRun r : p.getRuns()){
String content = r.getText(r.getTextPosition());
if(StringUtils.isNotEmpty(content) && params.containsKey(content)) {
r.setText(params.get(content), 0);
}
}
}
}
}
public static void main(String[] args) {
String filepath = "F:\\新建文件夾\\我是word.docx";
String outpath = "F:\\新建文件夾\\我是結果.pdf";
InputStream source;
OutputStream target;
try {
source = new FileInputStream(filepath);
target = new FileOutputStream(outpath);
Map<String, String> params = new HashMap<String, String>();
PdfOptions options = PdfOptions.create();
wordConverterToPdf(source, target, options, params);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
第一種效果不錯,windows . linux 都可以配置。 linux有興趣可以自己查閱 。
第二種最好,幾乎不管水印還是格式都完美的轉換。 但是只能支持windows 。
第三種最方便, 效果和第一種差不多,但是速度稍微慢了一些。
原文:https://blog.csdn.net/csdnFlyFun/article/details/79523262
