在浏览器中显示图片、pdf文件或office文件

一直想做一个功能,通过文件名的后缀判断是图片文件、pdf文件还是office文件,通过接口调用直接在浏览器中显示。

在网上查找了许多例子,最后还是自己写了一个方法。

首先浏览器显示图片或pdf文件 只用设置好: response.setContentType 类型,基本上都可以实现。但是遇到office一般都是先将office文件转为pdf文件,然后再进行显示。我这里使用的是openOffice软件进行转换。

注意:电脑上必须安装openOffice软件

 

 /**
     * 在浏览器里显示文件
     */
    @RequestMapping(value = "/viewFile/{fileName}",method=RequestMethod.GET,produces = "application/json;charset=UTF-8")
    public void viewFile(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "fileName") String fileName){
        if(StringUtil.isEmpty(fileName))throw new MyException("文件名字不能为空");
        BasAttachment attachment=attachmentService.findByFileName(fileName);
        if(attachment==null) throw new MyException("文件名称错误");
        String name=attachment.getName();//文件名称
        String extensionName="";//扩展名
        String filePath=attachment.getFilePath();//文件存放路径
        if(name.contains(".")) {
            extensionName = name.substring(name.lastIndexOf(".")+1);
        }
        String path = uploadPath+filePath;//网络图片地址
        File file=null;

        String[] imageType={"jpg","jpeg","png","gif"};
        String[] officeType={"doc","docx","xls","xlsx","ppt","pptx"};
        List<String> imageTypeList= Arrays.asList(imageType);
        List<String> officeTypeList= Arrays.asList(officeType);
        response.setContentType("text/html; charset=UTF-8");
        if(extensionName.equalsIgnoreCase("pdf")){
            response.setContentType("application/pdf");
            file=new File(path);
        }else if(imageTypeList.contains(extensionName)){
            response.setContentType("image/"+extensionName);
            file=new File(path);
        }else if(officeTypeList.contains(extensionName)){
            //office文件转pdf再显示
            file = Office2PDF.openOfficeToPDF(path);
            response.reset(); // 非常重要
            response.setContentType("application/pdf");
        }else {
            throw new MyException("不支持的文件类型");
        }


        FileInputStream bis = null;
        OutputStream os = null;
        try {
            bis = new FileInputStream(file);
            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count =bis.read(buffer)) != -1){
                os.write(buffer, 0,count);
            }
            os.flush();
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os !=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis !=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

  

 

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.springframework.util.StringUtils;

/**
 * 使用该工具类电脑上必须安装openOffice软件
 * 这是一个工具类,主要是为了使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx)
 * 转化为pdf文件<br>
 */
public class Office2PDF {

    private static final Log LOG = LogFactory.getLog(Office2PDF.class);

    /**
     * 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件<br>
     *
     * @param inputFilePath
     *            源文件路径,如:"e:/test.docx"
     * @return
     */
    public static File openOfficeToPDF(String inputFilePath) {
        return office2pdf(inputFilePath);
    }

    /**
     * 根据操作系统的名称,获取OpenOffice.org 3的安装目录<br>
     * 如我的OpenOffice.org 3安装在:C:/Program Files (x86)/OpenOffice.org 3<br>
     *
     * @return OpenOffice.org 3的安装目录
     */
    public static String getOfficeHome() {
        String osName = System.getProperty("os.name");
        System.out.println("操作系统名称:" + osName);
        if (Pattern.matches("Linux.*", osName)) {
            return "/opt/openoffice.org3";
        } else if (Pattern.matches("Windows.*", osName)) {
            return "C:/Program Files (x86)/OpenOffice 4";
        } else if (Pattern.matches("Mac.*", osName)) {
            return "/Applications/OpenOffice.org.app/Contents/";
        }
        return null;
    }

    /**
     * 连接OpenOffice.org 并且启动OpenOffice.org
     *
     * @return
     */
    public static OfficeManager getOfficeManager() {
        DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
        // 设置OpenOffice.org 3的安装目录
        config.setOfficeHome(getOfficeHome());
        // 启动OpenOffice的服务
        OfficeManager officeManager = config.buildOfficeManager();
        officeManager.start();
        return officeManager;
    }

    /**
     * 转换文件
     *
     * @param inputFile
     * @param outputFilePath_end
     * @param inputFilePath
     * @param converter
     */
    public static File converterFile(File inputFile, String outputFilePath_end, String inputFilePath,
                                     OfficeDocumentConverter converter) {
        File outputFile = new File(outputFilePath_end);
        // 假如目标路径不存在,则新建该路径
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        converter.convert(inputFile, outputFile);
        System.out.println("文件:" + inputFilePath + "\n转换为\n目标文件:" + outputFile + "\n成功!");
        return outputFile;
    }

    /**
     * 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件<br>
     *
     * @param inputFilePath
     *            源文件路径,如:"e:/test.docx"
     * @return
     */
    public static File office2pdf(String inputFilePath) {
        OfficeManager officeManager = null;
        try {
            if (StringUtils.isEmpty(inputFilePath)) {
                LOG.info("输入文件地址为空,转换终止!");
                return null;
            }

            File inputFile = new File(inputFilePath);
            if (!inputFile.exists()) {
                LOG.info("输入文件不存在,转换终止!");
                return null;
            }

            // 转换后的文件路径
            String outputFilePath_end = getOutputFilePath(inputFilePath);
            //如果转换后的文件存在,直接返回文件
            File outputFile=new File(outputFilePath_end);
            if(outputFile.exists()){
                return outputFile;
            }

            // 获取OpenOffice的安装路劲
            officeManager = getOfficeManager();
            // 连接OpenOffice
            OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);

            return converterFile(inputFile, outputFilePath_end, inputFilePath, converter);
        } catch (Exception e) {
            LOG.error("转化出错!", e);
        } finally {
            // 停止openOffice
            if (officeManager != null) {
                officeManager.stop();
            }
        }
        return null;
    }

    /**
     * 获取输出文件
     *
     * @param inputFilePath
     * @return
     */
    public static String getOutputFilePath(String inputFilePath) {
        if(!inputFilePath.contains(".")){
            return inputFilePath+".pdf";
        }
        String outputFilePath = inputFilePath.replaceAll("." + getPostfix(inputFilePath), ".pdf");
        return outputFilePath;
    }

    /**
     * 获取inputFilePath的后缀名,如:"e:/test.pptx"的后缀名为:"pptx"<br>
     *
     * @param inputFilePath
     * @return
     */
    public static String getPostfix(String inputFilePath) {
        return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
    }

    public static void main(String[] args) {
        Office2PDF.openOfficeToPDF("D:/attachment/PSP-PMS-cxfservice-V1.40.8.docx");
    }

}

  

项目代码见:

https://github.com/wxb100200/wang-base.git

  

 

posted @ 2019-01-17 18:14  争鸣  阅读(384)  评论(0)    收藏  举报