欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java在线游览Office

程序员文章站 2022-06-13 11:46:13
...

在线游览Office文件采用的方式是,在线转换为PDF之后进行,因为自己是后端开发,所以只介绍后端的知识;

有两种实现方法:

windows下:
windows下直接调用的是office插件转化效果肯定比OpenOffice好,所以如果条件允许,近可能的用此方案。
此方案用的是Jacob:
1 安装Office。
解压后如图所示:

Java在线游览Office

将其中的jacob-1.18-x64.dll(注意对应自己的电脑或服务器版本)放入:“C:\Windows\System32”目录下。
3代码实现:
导入jacob.jar 包
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;

public class pdf1 {
    
    private static final int wdFormatPDF = 17;
    private static final int xlsFormatPDF = 0;
    private static final int pptFormatPDF = 32;
    private static final int msoTrue = -1;
    private static final int msofalse = 0;

    
    public static boolean convert2PDF(String inputFile, String pdfFile) {
        String suffix = getFileSufix(inputFile);
        File file = new File(inputFile);
        if (!file.exists()) {
            System.out.println("文件不存在!");
            return false;
        }
        if (suffix.equals("pdf")) {
            System.out.println("PDF not need to convert!");
            return false;
        }
        if (suffix.equals("doc") || suffix.equals("docx")) {
            return word2PDF(inputFile, pdfFile);
        } else if (suffix.equals("ppt") || suffix.equals("pptx")) {
            return ppt2PDF(inputFile, pdfFile);
        } else if (suffix.equals("xls") || suffix.equals("xlsx")) {
            return excel2PDF(inputFile, pdfFile);
        } else {
            System.out.println("文件格式不支持转换!");
            return false;
        }
    }

    private static String getFileSufix(String fileName) {
        int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(splitIndex + 1);
    }

    private static boolean word2PDF(String inputFile, String pdfFile) {
        try {
            ActiveXComponent app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", false);
            Dispatch docs = app.getProperty("Documents").toDispatch();
            Dispatch doc = Dispatch.call(docs, "Open", inputFile, false, true)
                    .toDispatch();
            File tofile = new File(pdfFile);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(doc, "ExportAsFixedFormat", pdfFile, wdFormatPDF 
                    );
            Dispatch.call(doc, "Close", false);
            app.invoke("Quit", 0);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private static boolean excel2PDF(String inputFile, String pdfFile) {
        try {
            ActiveXComponent app = new ActiveXComponent("Excel.Application");
            app.setProperty("Visible", false);
            Dispatch excels = app.getProperty("Workbooks").toDispatch();
            Dispatch excel = Dispatch.call(excels, "Open", inputFile, false,
                    true).toDispatch();
            File tofile = new File(pdfFile);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(excel, "ExportAsFixedFormat", xlsFormatPDF, pdfFile);
            Dispatch.call(excel, "Close", false);
            app.invoke("Quit");
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    private static boolean ppt2PDF(String inputFile, String pdfFile) {
        try {
            ActiveXComponent app = new ActiveXComponent(
                    "PowerPoint.Application");
            Dispatch ppts = app.getProperty("Presentations").toDispatch();
            Dispatch ppt = Dispatch.call(ppts, "Open", inputFile, true,// ReadOnly
                    true,// Untitled指定文件是否有标题
                    false// WithWindow指定文件是否可见
                    ).toDispatch();
            File tofile = new File(pdfFile);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(ppt, "SaveAs", pdfFile, pptFormatPDF);
            Dispatch.call(ppt, "Close");
            app.invoke("Quit");
            return true;
        } catch (Exception e) {
            return false;
        }
    }
  
    
    public static void main(String[] args) {
        pdf1.convert2PDF("c:\\Users\\Y\\Desktop\\15.docx", "c:\\Users\\Y\\Desktop\\1234.pdf")
//第一个地址为原文件所在地址,第二个地址为转换成PDF文件后应该存放的地址。        
    }}
全平台(Linux,windows,Mac):
用OpenOffice实现(以Linux为例):
1在Linux上安装OpenOffice。
2给Linux安装适应的字体。(防止转换中文时出现乱码)
将windows下:C:\Windows\Fonts的所有文件复制进:Linux中:/usr/share/fonts中。
更新缓存
执行命令:fc-cache
kill掉openoffice进程
ps -ef | grep openoffice

启动后台运行openoffice
[aaa@qq.com openoffice4]# soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard &
开始进行java实现:
1 准备导入包。

Java在线游览Office

其中jodconverter的几个包maven中可能没有。

剩下的基本maven中都有

没有的包发在网盘了,大家可以下载:https://pan.baidu.com/s/1LTHLy3fOUJeMG58p6b64SQ

2 代码实现

package com.Util;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.regex.Pattern;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

/**
 * @author hwl_sz
 * @desc 需要OpenOffice第三插件的支持 ,支持window\linux\mac等系统
 */
public class OfficePDF {
    public static final String[] OFFICE_POSTFIXS = {"doc", "docx", "xls",
            "xlsx", "ppt", "pptx"};

    /**
     * 根据操作系统的名称,获取OpenOffice的安装目录
     * 如我的安装目录:D:/OpenOffice4
     */
    private static String getOfficeHome() {
        String osName = System.getProperty("os.name");
        if (Pattern.matches("Linux.*", osName)) {
            return "/opt/openoffice4";
        } else if (Pattern.matches("Windows.*", osName)) {
            return "D:/OpenOffice4";
        } else if (Pattern.matches("Mac.*", osName)) {
            return "/Application/OpenOffice.org.app/Contents";
        }
        return null;
    }

    /**
     * 转换文件
     *
     * @param inputFilePath  转换的office源文件路径
     * @param outputFilePath 输出目标文件路径
     */
    private static void converterFile(String inputFilePath, String outputFilePath) {
        File inputFile = new File(inputFilePath);
        File outputFile = new File(outputFilePath);
        // 假如目标路径不存在,则新建该路径
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }

        DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
        // 获取OpenOffice 的安装目录
        String officeHome = getOfficeHome();
        config.setOfficeHome(officeHome);
        // 启动OpenOffice的服务
        OfficeManager officeManager = config.buildOfficeManager();
        officeManager.start();

        OfficeDocumentConverter converter = new OfficeDocumentConverter(
                officeManager);

        converter.convert(inputFile, outputFile);
        System.out.println("文件:" + inputFilePath + "\n转换为\n目标文件:" + outputFile
                + "\n成功!");

        officeManager.stop();
    }

    /**
     * 将(.doc|.docx|.xls|.xlsx|.ppt|.pptx)等office文件 转化为pdf文件
     *
     * @param inputFilePath  待转换的源文件路径
     * @param outputFilePath 输出的目录文件路径,如果未指定(null),则按在源文件当前目录生成同名的pdf文件
     * @return 处理结果
     */
    public static boolean openOffice2Pdf(String inputFilePath, String outputFilePath) {
        boolean flag = false;
        File inputFile = new File(inputFilePath);
        ArrayList<String> office_Formats = new ArrayList<String>();
        Collections.addAll(office_Formats, OFFICE_POSTFIXS);
        if ((null != inputFilePath) && (inputFile.exists())) {
            // 判断目标文件路径是否为空
            if (office_Formats.contains(getPostfix(inputFilePath))) {
                if (null == outputFilePath) {
                    // 转换后的文件路径
                    String outputFilePath_new = inputFilePath.toLowerCase().replaceAll("."
                            + getPostfix(inputFilePath), ".pdf");
                    converterFile(inputFilePath, outputFilePath_new);
                    flag = true;
                } else {
                    converterFile(inputFilePath, outputFilePath);
                    flag = true;
                }
            }
        }
        return flag;
    }


    /**
     * 获取文件的后缀名
     */
    private static String getPostfix(String inputFilePath) {
        String[] p = inputFilePath.split("\\.");
        if (p.length > 0) {
            return p[p.length - 1];
        } else {
            return null;
        }
    }

    /**
     * @param args
     */
  public static void main(String[] args) {
    OfficePDF.openOffice2Pdf("c:/Users/Y/Desktop/11.ppt", "c:/Users/Y/Desktop/11.pdf");
//第一个地址为原文件所在地址,第二个地址为转换成PDF文件后应该存放的地址。
}
}