1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > Java使用jacob完成office文档pdf转换

Java使用jacob完成office文档pdf转换

时间:2019-05-28 19:49:39

相关推荐

Java使用jacob完成office文档pdf转换

Java使用jacob完成office文档pdf转换

#简单介绍jacob

jacob是java使用微软工具的一个工具

下载地址

/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 .ComThread;import .Dispatch;import .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)); // 不可见打开wordapp.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏Dispatch docs = app.getProperty("Documents").toDispatch();// 获取文挡属性System.out.println("打开文档 >>> " + inputFile);// Object[]第三个参数是表示“是否只读方式打开”// 调用Documents对象中Open方法打开文档,并返回打开的文档对象Documentdoc = 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格式宏,值为17long 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();// 启动excelActiveXComponent 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方法打开文档,并返回打开的文档对象Documentppt = Dispatch.call(ppts, "Open", inputFile, true,// ReadOnlytrue,// 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方法打开文档,并返回打开的文档对象Documentexcel = 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转pdfpathSave = pathSave.replace("\\", "/");File file1 = new File(pathSave + fileType + "_wordToPDF" +".pdf");if(!file1.exists()) {util.word2PDF(localPath, pathSave + fileType + "_wordToPDF" +".pdf");} }// excelif (type.equals("xls") || type.equals("xlsx")) {pathSave = pathSave.replace("\\", "/");// excel转.htmlFile file1 = new File(pathSave + fileType + "_excelToHtml" +".html");if(!file1.exists()) {// util.excel2PDF(localPath, pathSave + fileType + "_excelToPDF" +".pdf");util.excelToHtml(localPath, pathSave + fileType+ "_excelToHtml" +".html");} }// pptif (type.equals("ppt") || type.equals("pptx")) {// word转pdfpathSave = 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转.htmlFile 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.用户那边下载了office,导致word和execl都转换不了,可能是jar包的问题,后来换成就好了

大概就这些吧 参考了/catoop/article/details/43150671

和/xhubobo/p/13347536.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。