java使用jacob實(shí)現(xiàn)word轉(zhuǎn)pdf
背景:日常開發(fā)ERP系統(tǒng),會(huì)有一些工單或者合同之類需要填寫打印。我們就會(huì)將其word模板來通過系統(tǒng)自動(dòng)化填寫并轉(zhuǎn)換為PDF格式(PDF文件打印可保證文件質(zhì)量,是一種通用的格式。文件不易去修改,比較穩(wěn)定)。所以我們將通過jacob來實(shí)現(xiàn)這些功能。
準(zhǔn)備工作:
1.服務(wù)器需要安裝office2007,因?yàn)槲覀兙褪钦{(diào)用這個(gè)來實(shí)現(xiàn)轉(zhuǎn)換。
2.需要安裝插件jacob,安裝jacob-1.14.3-x86.dll到j(luò)dk\jdk1.7.0\jre\bin(你自己電腦安裝的jdk)
3.需要使用jacob-1.14.3.jar包
maven代碼如下:
<dependency> <groupId>net.sf.jacob-project</groupId> <artifactId>jacob</artifactId> <version>1.14.3</version> </dependency>
4.假如通過以上準(zhǔn)備工作未成功轉(zhuǎn)換,就下載一個(gè)SaveAsPDFandXPS.exe組件(office2007里的)。我就是通過這個(gè)組件才完成轉(zhuǎn)換。
5.上面的在系統(tǒng)為windows7中就可以了,假如你的項(xiàng)目需要發(fā)布到服務(wù)器(服務(wù)器系統(tǒng)一般都是windows2008)。則還需要一步。在上面的基礎(chǔ)上再安裝安裝jacob-1.14.3-x64.dll到j(luò)dk\jdk1.7.0\jre\bin(你自己電腦安裝的jdk)中。很多人在win7下都能成功轉(zhuǎn)換,但在win2008就是出問題。我就是通過磨了一天的時(shí)間,看了各種日志才發(fā)現(xiàn)問題。
一、工具類(OperationIo.java),這里面可以不做任何修改,復(fù)制粘貼就可以了。
package com.repair.util.pub;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class OperationIO {
static final int wdFormatPDF = 17;// PDF 格式
/**
* WORD轉(zhuǎn)換PDF
* @param sfileName WORD文件存在位置
* @param toFileName PDF文件存放位置
*/
public static void wordToPDF(String sfileName,String toFileName){
System.out.println("啟動(dòng)Word...");
long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch doc = null;
try {
//調(diào)用office word
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("Documents").toDispatch();
doc = Dispatch.call(docs, "Open" , sfileName).toDispatch();
System.out.println("打開文檔..." + sfileName);
System.out.println("轉(zhuǎn)換文檔到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("轉(zhuǎn)換完成..用時(shí):" + (end - start) + "ms.");
} catch (Exception e) {
System.out.println("========Error:文檔轉(zhuǎn)換失敗:" + e.getMessage());
} finally {
Dispatch.call(doc,"Close",false);
System.out.println("關(guān)閉文檔");
if (app != null)
app.invoke("Quit", new Variant[] {});
}
//如果沒有這句話,winword.exe進(jìn)程將不會(huì)關(guān)閉
ComThread.Release();
}
/**
* 遞歸刪除目錄下的所有文件及子目錄下所有文件
* @param dir 將要?jiǎng)h除的文件目錄
* @return boolean Returns "true" if all deletions were successful.
* If a deletion fails, the method stops attempting to
* delete and returns "false".
*/
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目錄此時(shí)為空,可以刪除
return dir.delete();
}
/**
* 將圖片文件轉(zhuǎn)化為字節(jié)數(shù)組字符串,并對(duì)其進(jìn)行Base64編碼處理
* @param imgFilePath 圖片地址路徑
*/
public static String GetImageStr(String imgFilePath) {//
byte[] data = null;
// 讀取圖片字節(jié)數(shù)組
try {
InputStream in = new FileInputStream(imgFilePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 對(duì)字節(jié)數(shù)組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64編碼過的字節(jié)數(shù)組字符串
}
/**
* 將二進(jìn)制轉(zhuǎn)換為圖片
*
* @param base64String
*/
public static void base64StringToImage(String base64String,String imageoutpath) {
try {
BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] bytes1 = decoder.decodeBuffer(base64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 = ImageIO.read(bais);
File w2 = new File(imageoutpath);// 可以是jpg,png,gif格式
ImageIO.write(bi1, "jpg", w2);// 不管輸出什么格式圖片,此處不需改動(dòng)
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、業(yè)務(wù)類(PrintWordToPdf.java) ,這里
package com.hjm.Test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import com.engineering.pojos.pub.gcRecordArchive;
import com.repair.util.pub.OperationIO;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class PrintWordToPdf {
public static void main(String[] args) {
//創(chuàng)建一個(gè)Configuration的實(shí)例
Configuration configuration = new Configuration();
//設(shè)置編碼
configuration.setDefaultEncoding("utf-8");
//創(chuàng)建Map對(duì)象,來保存要填寫的數(shù)據(jù)
Map<String, Object> paraMap = new HashMap<String, Object>();
//下面這些是我測(cè)試的一些數(shù)據(jù)
paraMap.put("ReceivingParty", "中國(guó)民航");
paraMap.put("PackingListNo", 10087);
paraMap.put("ConNo", 10088);
try {
//調(diào)用模板的文件夾,new File("D:\\測(cè)試")是一個(gè)絕對(duì)路徑,你可以自己設(shè)置為服務(wù)器路徑。
configuration.setDirectoryForTemplateLoading(new File("D:\\測(cè)試"));
} catch (IOException e) {
e.printStackTrace();
}
Template t = null;
try {
//獲取模板文件
t = configuration.getTemplate("FMO-08 Packing List.ftl"); // 獲取模板文件
} catch (IOException e) {
e.printStackTrace();
}
//生成一個(gè)文件保存的文件夾
File file =new File("D:\\最終");
//判斷文件夾是否存在,存在刪除并重創(chuàng)
if (!file .exists() && !file .isDirectory())
{
file.mkdir();
} else
{
boolean b = OperationIO.deleteDir(file);
if(b){
file.mkdir();
}
}
//填寫數(shù)據(jù)后生成的word文件。
String outfilepath = "D:/最終\\結(jié)果"+".doc";
File outFile = new File(outfilepath); // 導(dǎo)出文件
Writer out = null;
try {
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFile),"utf-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(paraMap,out); // 將填充數(shù)據(jù)填入模板文件并輸出到目標(biāo)文件
out.flush();
out.close();
//轉(zhuǎn)換PDF的文件
OperationIO.wordToPDF(outfilepath,"D:/最終\\結(jié)果"+".pdf");
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
總結(jié):通過以上代碼,就可以在模板中填寫好數(shù)據(jù),并將其生成word文件與其pdf文件。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringSecurity實(shí)現(xiàn)前后端分離的示例詳解
Spring Security默認(rèn)提供賬號(hào)密碼認(rèn)證方式,具體實(shí)現(xiàn)是在UsernamePasswordAuthenticationFilter 中,這篇文章主要介紹了SpringSecurity實(shí)現(xiàn)前后端分離的示例詳解,需要的朋友可以參考下2023-03-03
Java Set接口及常用實(shí)現(xiàn)類總結(jié)
Collection的另一個(gè)子接口就是Set,他并沒有我們List常用,并且自身也沒有一些額外的方法,全是繼承自Collection中的,因此我們還是簡(jiǎn)單總結(jié)一下,包括他的常用實(shí)現(xiàn)類HashSet、LinkedHashSet、TreeSet的總結(jié)2023-01-01
Spring Boot實(shí)現(xiàn)異步請(qǐng)求(Servlet 3.0)
在spring 3.2 及以后版本中增加了對(duì)請(qǐng)求的異步處理,這篇文章主要介紹了Spring Boot實(shí)現(xiàn)異步請(qǐng)求(Servlet 3.0),感興趣的小伙伴們可以參考一下。2017-04-04
SpringBoot?實(shí)現(xiàn)微信推送模板的示例代碼
這篇文章主要介紹了SpringBoot?實(shí)現(xiàn)微信推送模板,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-12-12
springboot項(xiàng)目打包成jar包的圖文教程
有時(shí)候我們會(huì)用IDEA來開發(fā)一些小工具,需要打成可運(yùn)行的JAR包,這篇文章主要給大家介紹了關(guān)于springboot項(xiàng)目打包成jar包的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06
SpringBoot MDC全鏈路調(diào)用日志跟蹤實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了SpringBoot MDC全鏈路調(diào)用日志跟蹤實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
Java實(shí)現(xiàn)五子棋游戲單機(jī)版(1.0)
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)五子棋游戲單機(jī)版,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
Mybatis錯(cuò)誤引起的程序啟動(dòng)卡死問題及解決
這篇文章主要介紹了Mybatis錯(cuò)誤引起的程序啟動(dòng)卡死問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02

