java使用jacob實(shí)現(xiàn)word轉(zhuǎn)pdf
背景:日常開(kāi)發(fā)ERP系統(tǒng),會(huì)有一些工單或者合同之類需要填寫(xiě)打印。我們就會(huì)將其word模板來(lái)通過(guò)系統(tǒng)自動(dòng)化填寫(xiě)并轉(zhuǎn)換為PDF格式(PDF文件打印可保證文件質(zhì)量,是一種通用的格式。文件不易去修改,比較穩(wěn)定)。所以我們將通過(guò)jacob來(lái)實(shí)現(xiàn)這些功能。
準(zhǔn)備工作:
1.服務(wù)器需要安裝office2007,因?yàn)槲覀兙褪钦{(diào)用這個(gè)來(lái)實(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.假如通過(guò)以上準(zhǔn)備工作未成功轉(zhuǎn)換,就下載一個(gè)SaveAsPDFandXPS.exe組件(office2007里的)。我就是通過(guò)這個(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就是出問(wèn)題。我就是通過(guò)磨了一天的時(shí)間,看了各種日志才發(fā)現(xiàn)問(wè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("打開(kāi)文檔..." + 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[] {});
}
//如果沒(méi)有這句話,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編碼過(guò)的字節(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ì)象,來(lái)保存要填寫(xiě)的數(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();
}
}
//填寫(xiě)數(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é):通過(guò)以上代碼,就可以在模板中填寫(xiě)好數(shù)據(jù),并將其生成word文件與其pdf文件。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Spring Boot 目錄文件結(jié)構(gòu)
這篇文章主要介紹了Spring Boot 目錄文件結(jié)構(gòu)的相關(guān)資料,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07
MyBatis-Plus中提供的各種注解詳細(xì)說(shuō)明
這篇文章主要介紹了MyBatis-Plus中提供的各種注解詳細(xì)說(shuō)明,下面對(duì)MyBatis-Plus提供的注解進(jìn)行整理,本文提供了部分示例代碼以方便理解,需要的朋友可以參考下2023-11-11
關(guān)于Mybatis的@param注解及多個(gè)傳參
這篇文章主要介紹了關(guān)于Mybatis的@param注解及多個(gè)傳參,@Param的作用就是給參數(shù)命名,比如在mapper里面某方法A(int id),當(dāng)添加注解后A(@Param(“userId”) int id),也就是說(shuō)外部想要取出傳入的id值,只需要取它的參數(shù)名userId就可以了,需要的朋友可以參考下2023-05-05
java Class.getSimpleName() 詳解及用法
這篇文章主要介紹了java Class.getSimpleName() 詳解及用法的相關(guān)資料,需要的朋友可以參考下2017-02-02
解決Mybatis出現(xiàn)報(bào)錯(cuò)Error querying database.Cause: j
這篇文章主要介紹了解決Mybatis出現(xiàn)報(bào)錯(cuò)Error querying database.Cause: java.lang.IndexOutOfBoundsException: Index 9 out of,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
springboot一個(gè)自定義注解如何搞定多線程事務(wù)
文章介紹了Spring?Boot中使用`@Async`注解進(jìn)行聲明式多線程編程的方法,以及如何通過(guò)自定義注解和AOP實(shí)現(xiàn)多線程事務(wù)控制,同時(shí),還解釋了`CountDownLatch`的使用場(chǎng)景及其工作原理2024-12-12
Redis框架Jedis及Redisson對(duì)比解析
這篇文章主要介紹了Redis框架Jedis及Redisson對(duì)比解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07

