Java轉PDF線上預覽
阿新 • • 發佈:2019-01-09
專案要用到doc轉pdf的功能,一番google之後總結出了三種方法(免費方案)
方法1.poi讀取doc + itext生成pdf (實現最方便,效果最差,跨平臺)
方法2.jodconverter + openOffice (一般格式實現效果還行,複雜格式容易有錯位,跨平臺)
方法3.jacob + msOfficeWord + SaveAsPDFandXPS (完美保持原doc格式,效率最慢,只能在windows環境下進行)
方法1:使用jdoctopdf來實現,這是一個封裝好的包,可以把doc轉換成pdf,html,xml等格式,呼叫很方便地址:http://www.maxstocker.com/jdoctopdf/downloads.php
需要自己匯入poi包與itext包,需要注意的是itext要匯入itext-2.1.5版本,新版本由於包名不同,會出錯
也可以自己根據網上的其他教程根據需要自己寫方法來實現。
用jdoctopdf的實現方法如下:
public void doc2pdf(String docFileName) throws Exception{ String path = this.getSession().getServletContext().getRealPath("/")+"attachment/"; Parser p = new DocParser();// create a new parser instance FileInputStream fis = new FileInputStream(path+"/doc/"+ docFileName + ".doc");// creating InputStream for use with parser DocumentElement mydoc = p.parse(fis,true,false);// parse document from input stream DocWriter w = new PDFWriter();// create PDF writer w.writeDocument(mydoc,new FileOutputStream(path+"/pdf/"+docFileName + ".pdf"));// write document as pdf using writer w = new XHTMLWriter(); w.writeDocument(mydoc,new FileOutputStream(path+"/pdf/"+docFileName + ".html"));// write document as xhtml }
public String materialUpload(){
try {
doc2pdf("ttt");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
方法1轉化後pdf截圖:(itext轉中文需要額外配置,所以。。。一片空白,格式也錯位了)
方法2:使用jodconverter來呼叫openOffice的服務來轉換,openOffice有個各個平臺的版本,所以這種方法跟方法1一樣都是跨平臺的。
jodconverter的下載地址:http://www.artofsolving.com/opensource/jodconverter
首先要安裝openOffice,下載地址:http://www.openoffice.org/download/index.html
安裝完後要啟動openOffice的服務,具體啟動方法請自行google,
mac下的啟動方法為終端輸入
/Applications/OpenOffice.org.app/Contents/MacOS/soffice "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -nologo -headless
準備工作完成後在專案裡匯入下載下來的包,然後加個方法就OK:
public void createPdf(String docFileName) throws IOException{
String path = this.getSession().getServletContext().getRealPath("/")+"attachment/";
File inputFile = new File(path+"/doc/"+ docFileName + ".doc");
File outputFile = new File(path+"/pdf/"+docFileName + ".pdf");
// connect to an OpenOffice.org instance running on port 8100
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
connection.connect();
// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(inputFile, outputFile);
// close the connection
connection.disconnect();
}
方法3:效果最好的一種方法,但是需要window環境,而且速度是最慢的需要安裝msofficeWord以及SaveAsPDFandXPS.exe(word的一個外掛,用來把word轉化為pdf)
Office版本是2007,因為SaveAsPDFandXPS是微軟為office2007及以上版本開發的外掛
SaveAsPDFandXPS下載地址:http://www.microsoft.com/zh-cn/download/details.aspx?id=7
jacob 包下載地址:http://sourceforge.net/projects/jacob-project/
我下的是jacob-1.17-M2.zip
下載下來的jacob裡的jar包匯入到專案裡,
jacob的dll檔案放到到你的jdk/jre/bin下面(不放會報錯:java.lang.NoClassDefFoundError: Could not initialize class com.jacob.com.Dispatch)
網上還有一種是把dll放在放在以下程式碼輸出的路徑裡的任意一個路徑目錄
System.getProperty("java.library.path");
這個我沒試過,應該也是可以的然後新增方法:
static final int wdFormatPDF = 17;// PDF 格式
public void wordToPDF(String docFileName){
System.out.println("啟動Word...");
long start = System.currentTimeMillis();
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 path = this.getSession().getServletContext().getRealPath("/")+"attachment/";
String sfileName = path+"/doc/"+ docFileName + ".doc";
String toFileName = path+"/pdf/"+ docFileName + ".pdf";
doc = Dispatch.call(docs, "Open" , sfileName).toDispatch();
System.out.println("開啟文件..." + sfileName);
System.out.println("轉換文件到PDF..." + toFileName);
File tofile = new File(toFileName);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc,
"SaveAs",
toFileName, // FileName
wdFormatPDF);
long end = System.currentTimeMillis();
System.out.println("轉換完成..用時:" + (end - start) + "ms.");
} catch (Exception e) {
System.out.println("========Error:文件轉換失敗:" + e.getMessage());
} finally {
Dispatch.call(doc,"Close",false);
System.out.println("關閉文件");
if (app != null)
app.invoke("Quit", new Variant[] {});
}
//如果沒有這句話,winword.exe程序將不會關閉
ComThread.Release();
}
需要注意的是,如果沒有安裝SaveAsPDFandXPS.exe的話會提示
========Error:文件轉換失敗:Invoke of: SaveAs
Source: Microsoft Word
Description:
方法3pdf最終轉換效果(格式完全一致):