java使用jacob客户端需要安装office,服务端需要安装吗?如果需要,服务器是Linux该如何解决?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java使用jacob客户端需要安装office,服务端需要安装吗?如果需要,服务器是Linux该如何解决?相关的知识,希望对你有一定的参考价值。

您好,使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用。
1、确保使用JACOB的服务器安装Microsoft的Office文件。
2、把jacob-1.14.3-x86.dll加入到环境变量path,最简单的方式是直接把这个文件拷贝到WINDOWS\system32目录下。
3、dll文件只会被classloader加载一次,因此一般情况下把jacob.jar放入WEB-INF/lib即可;但若有多个使用jacob的应用部署在同一个服务器,如tomcat,则需要把jacob.jar放在common/lib目录下。

常见异常处理:
1、java.lang.UnsatisfiedLinkError:no jacob in java.library.path
加载不到加载的jacob-1.14.3-x86.dll文件;可设置正确的path或者直接放入到WINDOWS\system32目录下。
2、java.lang.NoClassDefFoundError: Could not initialize class com.jacob.activeX.ActiveXComponent
在classpath找不到jacob.jar;可采用的方法是把jacob.jar放在common/lib目录下。
  3、”java.lang.UnsatisfiedLinkError: C:\WINDOWS\system32\jacob-1.14.3-x86.dll: 由于应用程序配置不正确,应用程序未能启动。重新安装应用程序可能会纠正”这个问题。
参考技术A jacob只支持Windows环境下Java操作Word文档功能,一般linux下无法读取Jacob的动态链接库文件,即.dll文件,linux服务器下,要保证能正常读取.dll文件和Word,否则则无法使用jacob,只能用别的办法了。 参考技术B 使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用。
1、确保使用JACOB的服务器安装Microsoft的Office文件。
2、把jacob-1.14.3-x86.dll加入到环境变量path,最简单的方式是直接把这个文件拷贝到WINDOWS\system32目录下。
3、dll文件只会被classloader加载一次,因此一般情况下把jacob.jar放入WEB-INF/lib即可;但若有多个使用jacob的应用部署在同一个服务器,如tomcat,则需要把jacob.jar放在common/lib目录下。

常见异常处理:
1、java.lang.UnsatisfiedLinkError:no jacob in java.library.path
加载不到加载的jacob-1.14.3-x86.dll文件;可设置正确的path或者直接放入到WINDOWS\system32目录下。
2、java.lang.NoClassDefFoundError: Could not initialize class com.jacob.activeX.ActiveXComponent
在classpath找不到jacob.jar;可采用的方法是把jacob.jar放在common/lib目录下。
3、”java.lang.UnsatisfiedLinkError: C:\WINDOWS\system32\jacob-1.14.3-x86.dll: 由于应用程序配置不正确,应用程序未能启动。重新安装应用程序可能会纠正”这个问题。

java-使用Jacob实现office转换成pdf

 

 

 

技术图片
package net.nblh.utils;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.icepdf.core.pobjects.Document;
import org.icepdf.core.util.GraphicsRenderingHints;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComFailException;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class Word2PdfUtil {

    private static final int ppSaveAsPDF = 32;

    static final int wdDoNotSaveChanges = 0;// 不保存待定的更改
    static final int wdFormatPDF = 17;// word转PDF 格式

    /**
     * 文档转pdf转png
     * @param source 源文件
     */
    public static int execuConvert(String source) {
        
        String ext = source.substring(source.lastIndexOf("."));
        String tar = source.replace(ext, ".pdf");
        File file = new File(tar);
        
        if (file.exists()) {
            //pdf文件已转换,直接转png
            return pdf2pngByFile(tar);
        }

        // 示例
//        String source = "D:\2017\庭审案件材料一.doc";
//        String target = "D:\2018\庭审案件材料一.pdf";

        if (!checkAvailable(source,tar)) {
            return 0;
        }

//        String t = setPdfType(source, target);
        
        String suffixStr = getSuffix(source);
        if (".doc".equals(suffixStr) || ".docx".equals(suffixStr)) {
            return word2pdf(source, tar);
        } else if(".pptx".equals(suffixStr) || ".ppt".equals(suffixStr)){
             return ppt2pdf(source, tar);
        } else if(".xls".equals(suffixStr) || ".xlsx".equals(suffixStr)){
            return xls2Pdf(source, tar);
        } else {
            System.out.println("无法转换此文件格式");
        }
        return 0;

    }

    public static int word2pdf(String source, String target) {
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", false);

            Dispatch docs = app.getProperty("Documents").toDispatch();

            doc = Dispatch.call(docs, "Open", source, false, true).toDispatch();
            File tofile = new File(target);
            File dirPath = new File(getPath(target));
            if (tofile.exists()) {
                tofile.delete();
            } else if (!dirPath.exists()) {
                dirPath.mkdirs();
            }

            Dispatch.call(doc, "SaveAs", target, wdFormatPDF);
//            Dispatch.call(doc, "SAs", target, wdFormatPDF);

            Dispatch.call(doc, "Close", false);
            doc = null;

            app.invoke("Quit", wdDoNotSaveChanges);
            app = null;
            System.out.println("pdf_ok");
            
            return pdf2pngByFile(target);
        } catch (Exception e) {
            return 0;
        } finally {
            if (null != doc) {
                Dispatch.call(doc, "Close", false);
            }
            if (app != null) {
                app.invoke("Quit", wdDoNotSaveChanges);
            }
        }
    }

    /**
     * 检查文件格式,只转换doc ,docx,ppt格式 fileName 文件名
     * 
     * @return
     */
    private static boolean checkFormat(String fileName) {
        if (null == fileName || "".equals(fileName)) {
            return false;
        }

        if (!(fileName.substring(fileName.lastIndexOf(File.separator)).contains("."))) {
            System.out.println("没有指明要转换的文件");
            return false;
        }

        String format = fileName.substring(fileName.lastIndexOf("."));
        if (".doc".equals(format) || ".docx".equals(format) || ".ppt".equals(format) || ".pptx".equals(format)
                || ".xls".equals(format) || ".xlsx".equals(format) || ".dot".equals(format) || ".dotx".equals(format)
                || ".pot".equals(format) || ".potx".equals(format) || ".xlt".equals(format) || "xltx".equals(format)) {

            return true;
        }
        System.out.println("文件格式不合符,无法转换");
        return false;
    }
    
    /**
     * 检查路径是否正确
     * @return
     */
    public static boolean checkAvailable(String source,String target){
        if (isEmpty(source.trim())) {
            System.out.println("源文件路径不存在");
            return false;
        }
        
        if(!source.contains(File.separator) || !source.contains(".")){
            System.out.println("请输入正确的源文件路径,以及源文件名");
            return false;
        }
        
        if(".".equals(getSuffix(source).trim())){
            System.out.println("请输入正确的源文件名");
            return false;
        }
        
        if(isEmpty(target)){
            System.out.println("目标文件路径不存在");
            return false;
        }
        
        if(!target.contains(File.separator) || !target.contains(".")){
            System.out.println("请输入正确的目标文件路径,以及目标文件名");
            return false;
        }
        
        if(!".pdf".equals(getSuffix(target))){
            System.out.println("请正确输入要生成的pdf文件名");
            return false;
        }
        
        return true;
    }

    /**
     * 截取文件全路径,不包括文件名 F:/snd/down/ceshi/
     */
    private static String getPath(String fileName) {
        if (null != fileName || !"".equals(fileName)) {
            return fileName.substring(0, fileName.lastIndexOf(File.separator));
        }
        return "";
    }

    /**
     * 如果目标文件后缀名不是pdf,则强行改为pdf
     */
    private static String setPdfType(String source, String target) {
        // 目标路径包含文件名称
        if (target.substring(target.lastIndexOf(File.separator)).contains(".")) {
            String ext = target.substring(target.lastIndexOf("."));
            String fileName = target.replace(ext, ".pdf");
            return fileName;
        } else {
            // 没有文件名称,只有路径
            return target + getFileName(source) + ".pdf";
        }
    }

    /**
     * 截取文件名 不包含后缀名
     * 
     * @return
     */
    private static String getFileName(String fileName) {
        if (!isEmpty(fileName)) {
            return fileName.substring(fileName.lastIndexOf(File.separator), fileName.lastIndexOf("."));
        }
        return "";
    }
    
    /**
     * 获得后缀名
     * @param fileName
     * @return
     */
    private static String getSuffix(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }

    private static boolean isEmpty(String str) {
        if (null == str || "".equals(str)) {
            return true;
        }
        return false;
    }

    //ppt 转 pdf
    public static int ppt2pdf(String srcFilePath, String pdfFilePath) {
        ActiveXComponent app = null;
        Dispatch ppt = null;
        try {
            
            ComThread.InitSTA();
            app = new ActiveXComponent("PowerPoint.Application");
            Dispatch ppts = app.getProperty("Presentations").toDispatch();

            // 因POWER.EXE的发布规则为同步,所以设置为同步发布
            ppt = Dispatch.call(ppts, "Open", srcFilePath, true, // ReadOnly
                    true, // Untitled指定文件是否有标题
                    false// WithWindow指定文件是否可见
            ).toDispatch();
            
            File dirPath = new File(getPath(pdfFilePath));
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }

            Dispatch.call(ppt, "SaveAs", pdfFilePath, ppSaveAsPDF); // ppSaveAsPDF为特定值32
            System.out.println("pdf转换完成!");
            
            return pdf2pngByFile(pdfFilePath); // set flag true;
        } catch (ComFailException e) {
            System.out.println(e.toString());
            return 0;
        } catch (Exception e) {
            System.out.println(e.toString());
            return 0;
        } finally {
            if (ppt != null) {
                Dispatch.call(ppt, "Close");
            }
            if (app != null) {
                app.invoke("Quit");
            }
            ComThread.Release();
        }
    }

    // EXCEL转PDF
    public static int xls2Pdf(String inFilePath, String outFilePath) {
        ActiveXComponent ax = null;
        Dispatch excels = null;
        Dispatch excel = null;
        try {
            
            ax = new ActiveXComponent("Excel.Application");
            ComThread.InitSTA();
            ax.setProperty("Visible", new Variant(false));
            ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            excels = ax.getProperty("Workbooks").toDispatch();
            
            File dirPath = new File(getPath(outFilePath));
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }

            excel = Dispatch
                    .invoke(excels, "Open", Dispatch.Method,
                            new Object[] { inFilePath, new Variant(false), new Variant(false) }, new int[9])
                    .toDispatch();

            // 转换格式
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[] { new Variant(0), // PDF格式=0
                    outFilePath, new Variant(0) }, new int[1]);// 0=标准
                                                                // (生成的PDF图片不会变模糊)
                                                                // 1=最小文件
                                                                // (生成的PDF图片糊的一塌糊涂)

            Dispatch.call(excel, "Close", new Variant(false));

            if (ax != null) {
                ax.invoke("Quit", new Variant[] {});
                ax = null;
            }
            System.out.println("pdf转换完成!");
            
            return pdf2pngByFile(outFilePath);
        } catch (Exception es) {
            System.out.println(es.toString());
            return 0;
        } finally {
            ComThread.Release();
        }
    }
    
    /**
     * 本地pdf文件转png 
     */
    public static int pdf2pngByFile(String target){
        String filePath = target;
        Document document = new Document();
//        System.out.println("开始转png");
        try {
            document.setFile(filePath);
            float scale = 1.5f;// 缩放比例(大图)
            // float scale = 0.2f;// 缩放比例(小图)
            float rotation = 0f;// 旋转角度
            int pageSize = document.getNumberOfPages();
            for (int i = 0; i < document.getNumberOfPages(); i++) {
                BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN,
                        org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
                RenderedImage rendImage = image;
//                try {
//                    File file = new File("D:/fileUpload/ftpDownload/icepdf_a" + i + ".png");
//                    // 这里png作用是:格式是jpg但有png清晰度
//                    ImageIO.write(rendImage, "png", file);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
                try {
//                    WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
//                    ServletContext servletContext = webApplicationContext.getServletContext();
//                    File contextPath = new File(servletContext.getRealPath("/")); // 项目根目录
//                    File uploadPath = new File(
//                            contextPath.getParentFile().getAbsoluteFile() + File.separator + "uploadFiles"); // 上传图片存放目录
                    File uploadPath = new File(target);
                    String fileName = getPathWithName(target);
                    File file1 = new File(fileName);
                    if (!file1.exists()) {
                        file1.mkdirs();
                    }
//                    System.out.println("地址=" + uploadPath.getAbsolutePath() + "/icepdf_a" + i + ".png" + "
");
                    File file = new File(fileName + "\" + i + ".png");
                    // 这里png作用是:格式是jpg但有png清晰度
                    ImageIO.write(rendImage, "png", file);
                    
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image.flush();
            }
            document.dispose();
            System.out.println("png_ok");
            System.out.println("pageSize="+pageSize);
            return pageSize;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return 0;
    }
    
    /**
     * 截取文件全路径,包括文件名,去掉后缀 F:/snd/down/ceshi/aaa
     */
    public static String getPathWithName(String fileName) {
        if (null != fileName || !"".equals(fileName)) {
            return fileName.substring(0, fileName.lastIndexOf("."));
        }
        return "";
    }

}
View Code

 

以上是关于java使用jacob客户端需要安装office,服务端需要安装吗?如果需要,服务器是Linux该如何解决?的主要内容,如果未能解决你的问题,请参考以下文章

java-使用Jacob实现office转换成pdf

[JAVA]使用jacob进行服务端word转html pdf

java web 开发之 office(exceldoc等)文件转pdf

office 文档转pdf

JAVA 使用Jacob.jar和Jacob.dll将excel转换成html,出现“DDE SERVER WINDOW:EXCEL.EXE”错误!求解答!

java excel怎么读取到html