jacob是java使用微软工具的一个工具
下载地址
http://sourceforge.net/projects/jacob-project/files/
解压后获得3个文件
jacob.jar
jacob-1.17-x64.dll
jacob-1.17-x86.dll
把dll动态库放入jdk的bin目录下,jar添加到项目
话不多说直接上代码 这块代码主要是工具方法,用来进行转换的
package office2pdf;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import com.aspose.cad.Color;
import com.aspose.cad.Image;
import com.aspose.cad.imageoptions.CadRasterizationOptions;
import com.aspose.cad.imageoptions.PdfOptions;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class OfficeUtil {
/*转PDF格式值*/
private static final int wdFormatPDF = 17;
private static final int xlFormatPDF = 0;
private static final int ppFormatPDF = 32;
private static final int msoTrue = -1;
private static final int msofalse = 0;
/*转HTML格式值*/
private static final int wdFormatHTML = 8;
private static final int ppFormatHTML = 12;
private static final int xlFormatHTML = 44;
/*转TXT格式值*/
private static final int wdFormatTXT = 2;
/***
*
* Word转PDF
* @author HHJ
* @param inputFile
* @param pdfFile
* @return
*/
/**
* Word文档转换
*
* @param inputFile
* @param pdfFile
* @author SHANHY
*/
public boolean word2PDF(String inputFile, String pdfFile) {
ComThread.InitSTA();
long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch doc = null;
try {
app = new ActiveXComponent("Word.Application");// 创建一个word对象
app.setProperty("Visible", new Variant(false)); // 不可见打开word
app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
Dispatch docs = app.getProperty("Documents").toDispatch();// 获取文挡属性
System.out.println("打开文档 >>> " + inputFile);
// Object[]第三个参数是表示“是否只读方式打开”
// 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
doc = Dispatch.call(docs, "Open", inputFile, false, true).toDispatch();
// 调用Document对象的SaveAs方法,将文档保存为pdf格式
System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");
Dispatch.call(doc, "SaveAs", pdfFile, wdFormatPDF);//word保存为pdf格式宏,值为17
// Dispatch.call(doc, "ExportAsFixedFormat", pdfFile, wdFormatPDF); // word保存为pdf格式宏,值为17
long end = System.currentTimeMillis();
System.out.println("用时:" + (end - start) + "ms.");
return true;
} catch (Exception e) {
e.printStackTrace();
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();
ComThread.quitMainSTA();
return false;
}
/**
* EXCEL转HTML
* @author HHJ
* @param xlsfile
* EXCEL文件全路径
* @param htmlfile
* 转换后HTML存放路径
*/
public void excelToHtml(String xlsfile, String htmlfile) {
// 关闭excel进程
ComThread.InitSTA();
// 启动excel
ActiveXComponent app = new ActiveXComponent("Excel.Application");
try {
// 设置excel不可见
app.setProperty("Visible", new Variant(false));
Dispatch excels = app.getProperty("Workbooks").toDispatch();
// 打开excel文件
Dispatch excel = Dispatch.invoke(
excels,
"Open",
Dispatch.Method,
new Object[] { xlsfile, new Variant(false),
new Variant(true) }, new int[1]).toDispatch();
// 作为html格式保存到临时文件
Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {
htmlfile, new Variant(xlFormatHTML) }, new int[1]);
Variant f = new Variant(false);
Dispatch.call(excel, "Close", f);
} catch (Exception e) {
e.printStackTrace();
} finally{
ComThread.Release();
try {
Runtime.getRuntime().exec("taskkill /f /t /im excel.exe");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* PPT文档转换
*
* @param inputFile
* @param pdfFile
* @author HHJ
*/
public boolean ppt2PDF(String inputFile, String pdfFile) {
ComThread.InitSTA();
pdfFile = pdfFile.replace('/', '\\');
long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch ppt = null;
try {
app = new ActiveXComponent("PowerPoint.Application");// 创建一个PPT对象
// app.setProperty("Visible", new Variant(false)); // 不可见打开(PPT转换不运行隐藏,所以这里要注释掉)
// app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
Dispatch ppts = app.getProperty("Presentations").toDispatch();// 获取文挡属性
System.out.println("打开文档 >>> " + inputFile);
// 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
ppt = Dispatch.call(ppts, "Open", inputFile,
true,// ReadOnly
true,// Untitled指定文件是否有标题
false// WithWindow指定文件是否可见
).toDispatch();
System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");
Dispatch.call(ppt, "SaveAs", pdfFile, ppFormatPDF);
long end = System.currentTimeMillis();
System.out.println("用时:" + (end - start) + "ms.");
return true;
} catch (Exception e) {
e.printStackTrace();
System.out.println("========Error:文档转换失败:" + e.getMessage());
} finally {
Dispatch.call(ppt, "Close");
System.out.println("关闭文档");
if (app != null)
app.invoke("Quit", new Variant[] {});
}
ComThread.Release();
ComThread.quitMainSTA();
return false;
}
/**
* dwg转pdf
*
* @param xlsfile
* dwg文件全路径
* @param htmlfile
* 转换后pdf存放路径
*/
public void dwgToPdf(String inputFile, String pdfFile) {
File file = new File(inputFile);
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
Image objImage = Image.load(fileInputStream);
CadRasterizationOptions rasterizationOptions = new CadRasterizationOptions();
rasterizationOptions.setBackgroundColor(Color.getWhite());
rasterizationOptions.setAutomaticLayoutsScaling(true);
rasterizationOptions.setNoScaling(false);
rasterizationOptions.setDrawType(1);
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.setVectorRasterizationOptions(rasterizationOptions);
objImage.save(pdfFile, pdfOptions);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* EXCEL转pdf
* @author HHJ
* @param xlsfile
* EXCEL文件全路径
* @param htmlfile
* 转换后HTML存放路径
*/
public boolean excel2PDF(String inputFile, String pdfFile) {
ComThread.InitSTA();
long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch excel = null;
try {
app = new ActiveXComponent("Excel.Application");// 创建一个PPT对象
app.setProperty("Visible", new Variant(false)); // 不可见打开
// app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
Dispatch excels = app.getProperty("Workbooks").toDispatch();// 获取文挡属性
System.out.println("打开文档 >>> " + inputFile);
// 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
excel = Dispatch.call(excels, "Open", inputFile, false, true).toDispatch();
// 调用Document对象方法,将文档保存为pdf格式
System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");
// Excel 不能调用SaveAs方法
Dispatch.call(excel, "ExportAsFixedFormat", xlFormatPDF, pdfFile);
long end = System.currentTimeMillis();
System.out.println("用时:" + (end - start) + "ms.");
return true;
} catch (Exception e) {
e.printStackTrace();
System.out.println("========Error:文档转换失败:" + e.getMessage());
} finally {
Dispatch.call(excel, "Close", false);
System.out.println("关闭文档");
if (app != null)
app.invoke("Quit", new Variant[] {});
}
ComThread.Release();
ComThread.quitMainSTA();
return false;
}
}
上面代码包含了word转pdf,execl转html(execl转pdf这个东西不好用,上面也有),ppt转pdf,和dwg转pdf(这个主要是项目上需要,是使用了其他的jar----aspose.jar,如果有需要自行下载)
下面这个是测试类
package office2pdf;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
public class PdfTest {
public static void main(String[] args) {
int result = 0;
File file = null;
String path = null;
String pathSave = null;
JFileChooser fileChooser = new JFileChooser();
FileSystemView fsv = FileSystemView.getFileSystemView(); //注意了,这里重要的一句
fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
fileChooser.setDialogTitle("请选择要转换的文件...");
fileChooser.setApproveButtonText("确定");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
result = fileChooser.showOpenDialog(fileChooser);
if (JFileChooser.APPROVE_OPTION == result) {
path=fileChooser.getSelectedFile().getPath();
}
JFileChooser fileChooser1 = new JFileChooser();
FileSystemView fsv1 = FileSystemView.getFileSystemView(); //注意了,这里重要的一句
fileChooser1.setCurrentDirectory(fsv1.getHomeDirectory());
fileChooser1.setDialogTitle("请选择要保存的文件夹...");
fileChooser1.setApproveButtonText("确定");
fileChooser1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
result = fileChooser1.showOpenDialog(fileChooser1);
if (JFileChooser.APPROVE_OPTION == result) {
pathSave=fileChooser1.getSelectedFile().getPath();
}
String a=startTrans(path,pathSave);
System.out.println(a);
}
//url获取
private static String startTrans(String localPath, String pathSave) {
OfficeUtil util=new OfficeUtil();
File file = new File(localPath);
String fileName=file.getName();
String type = fileName.substring(fileName.lastIndexOf(".") + 1,
fileName.length()).toLowerCase();
String fileType = fileName.substring(0, fileName.lastIndexOf("."));
pathSave=pathSave+"/";
if (type.equals("doc") || type.equals("docx")||type.equals("txt")) {
// word转pdf
pathSave = pathSave.replace("\\", "/");
File file1 = new File(pathSave + fileType + "_wordToPDF" +".pdf");
if(!file1.exists()) {
util.word2PDF(localPath, pathSave + fileType + "_wordToPDF" +".pdf");
}
}
// excel
if (type.equals("xls") || type.equals("xlsx")) {
pathSave = pathSave.replace("\\", "/");
// excel转.html
File file1 = new File(pathSave + fileType + "_excelToHtml" +".html");
if(!file1.exists()) {
// util.excel2PDF(localPath, pathSave + fileType + "_excelToPDF" +".pdf");
util.excelToHtml(localPath, pathSave + fileType+ "_excelToHtml" +".html");
}
}
// ppt
if (type.equals("ppt") || type.equals("pptx")) {
// word转pdf
pathSave = pathSave.replace("\\", "/");
File file1 = new File(pathSave + fileType + "_pptToPDF" +".pdf");
if(!file1.exists()) {
util.ppt2PDF(localPath, pathSave + fileType + "_pptToPDF" +".pdf");
}
}
if(type.equals("dwg")) {
pathSave = pathSave.replace("\\", "/");
// excel转.html
File file1 = new File(pathSave + fileType + "_dwgToPdf" +".pdf");
if(!file1.exists()) {
util.dwgToPdf(localPath, pathSave + fileType+ "_dwgToPdf" +".pdf");
}
}
return "转换成功";
}
}
这个调用了JFileChooser来简单实现的图形化显示
这张图片选择要转换的文件 支持前面代码里面的所有格式进行pdf转换
这个是选择保存的文件夹
之后是去保存文件夹去找转换文件打开即可,这里就不截图说明了
这个功能在项目上开发的时候遇到了很多问题以下是一些总结
1.转换报错,对于word和execl的转换还是挺正常的 ,但ppt|转换总报错
Description: Presentation.SaveAs : PowerPoint 无法将 ^0 保存到 ^1。
后来百度加了pdfFile = pdfFile.replace(’/’, ‘\’); 这个转换之后就好了
2.用户那边下载了office2007,导致word和execl都转换不了,可能是jar包的问题,后来换成2016就好了
大概就这些吧 参考了https://blog.csdn.net/catoop/article/details/43150671
和https://www.cnblogs.com/xhubobo/p/13347536.html