图片、pdf、wrod和excel 在线预览

自定义文件服务器 图片、pdf、wrod和excel 在线预览

场景介绍

因公司项目中需要使用到文件交互,因此在网上找了一个demo做了点修改,原项目功能只有上传和下载,现要求在线预览pdf word excel 文件,所以在原来的基础上进行修改使其支持在线预览,图片和pdf 的在线预览比较简单,word excel 的预览实现方式是先将word 和excel 文件 转换成具有一定格式的html 然后输出在界面上,目前只支持.xls 和 .doc 文件预览

准备工作

1.需要用到的 jar 用于word excel的解析在这里插入图片描述
2. PoiUtil2 类 用于解析word excel 的工具类

package fileServer.util;

import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class PoiUtil2 {

    public static final String dtLong = "yyyyMMddHHmmss";
    static DateFormat df = new SimpleDateFormat(dtLong);

    /**
     * Excel 转为 HTML
     * @param fileName
     * @param outputFile
     * @throws FileNotFoundException
     * @throws IOException
     * @throws ParserConfigurationException
     * @throws TransformerConfigurationException
     * @throws TransformerException
     */
    public static void excelToHtml(String fileName, String outputFile)
            throws FileNotFoundException, IOException, ParserConfigurationException,
            TransformerConfigurationException, TransformerException {
        String htmlStr = excelPareToHtmlString(fileName);
        writeFile(htmlStr, outputFile);
    }

   
    public  static String  excelPareToHtmlString(String fileName)  throws FileNotFoundException, IOException, ParserConfigurationException,
            TransformerConfigurationException, TransformerException {
        InputStream is = new FileInputStream(fileName);

        HSSFWorkbook excelBook = new HSSFWorkbook(is);

        ExcelToHtmlConverter ethc = new ExcelToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());


        ethc.setOutputColumnHeaders(false);
        ethc.setOutputRowNumbers(false);

        ethc.processWorkbook(excelBook);

        Document htmlDocument = ethc.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();

        String htmlStr = new String(out.toByteArray(),"UTF-8");

        htmlStr = htmlStr.replace("<h2>Sheet1</h2>", "")
                .replace("<h2>Sheet2</h2>", "")
                .replace("<h2>Sheet3</h2>", "")
                .replace("<h2>Sheet4</h2>", "")
                .replace("<h2>Sheet5</h2>", "");
        return  htmlStr;
    }

    /**
     * Word 转为 HTML
     *
     * @param fileName
     * @param outputFile
     * @throws IOException
     * @throws ParserConfigurationException
     * @throws TransformerException
     */
//    public static void wordToHtml(String fileName, String outputFile) throws
//            IOException, ParserConfigurationException, TransformerException {
//        String htmlStr = wordParseToHtmlString(fileName,null,null);
//        writeFile(htmlStr, outputFile);
//    }

    public static  String wordParseToHtmlString(String fileName, String imageStoragePath,HttpServletRequest request)throws
            IOException, ParserConfigurationException, TransformerException {
        HWPFDocument wordDoc = new HWPFDocument(new FileInputStream(fileName));

        WordToHtmlConverter wthc = new WordToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());

        //这里用来处理word 中的图片 保存到服务器本地磁盘并且 返回在线可访问的地址
        wthc.setPicturesManager(new PicturesManager() {

            @Override
            public String savePicture(byte[] bytes, PictureType pt, String string, float f, float f1) {
                //文件命名与FileUpLload上传文件名称规则一致
                String extension = pt.getExtension();

                //因为服务会给上传的文件追加时间搓防止文件重复 oldName 上传之前的文件名称
                String oldName = System.currentTimeMillis() + "." + extension;
                String name = df.format(new Date()) + "-" + oldName;
                try {
                    String targetPath = imageStoragePath + name;
                    FileOutputStream out = new FileOutputStream(targetPath);
                    out.write(bytes);
                    out.close();
                    String webroot = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
                    String fileurl = webroot + "/download?name=" + name;

                    name = fileurl;
                    //返回在线可访问的地址 如 http://localhost:8000/download?name=1.jpg;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return name;
            }

        });

        wthc.processDocument(wordDoc);

        List<Picture> pics = wordDoc.getPicturesTable().getAllPictures();
        if (null != pics && pics.size() > 0) {
            for (Picture pic : pics) {
                String suggestFullFileName = pic.suggestFullFileName();
                pic.writeImageContent(new FileOutputStream(suggestFullFileName));
            }
        }

        Document htmlDocument = wthc.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);

        out.close();

        String htmlStr = new String(out.toByteArray(),"UTF-8");
        return  htmlStr;
    }

    public static void writeFile(String content, String path) {
        FileOutputStream fos = null;
        BufferedWriter bw = null;

        File file = new File(path);

        try {
            fos = new FileOutputStream(file);

            bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
            bw.write(content);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (null != bw) {
                    bw.close();
                }
                if (null != fos) {
                    fos.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            PoiUtil2.excelToHtml("C:\\Users\\-AiYuan\\Desktop\\20190508001.xls", "C:\\Users\\-AiYuan\\Desktop\\test.html");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }

//        try {
//        PoiUtil2.wordToHtml("C:\\Users\\-AiYuan\\Desktop\\安卓扫描枪对接文档 .doc","C:\\Users\\-AiYuan\\Desktop\\test2.html");
//        } catch (IOException ex) {
//            logger.error(ex);
//        } catch (ParserConfigurationException ex) {
//            logger.error(ex);
//        } catch (TransformerException ex) {
//            logger.error(ex);
//        }
    }
}

预览图片,pdf

	   protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            	// 省略通请求地址  //localhost:8000/download?name=1.jpg;  获取文件代码  
            	//假装这个file 是通过地址
            	File file = new File("C:\\Users\\-AiYuan\\Desktop\\1.jpg");
            	 previewFile(response, file, oldName);
            }
  //预览文件 图片和dpf 都可以用此方法预览
    void previewFile(HttpServletResponse response, File file, String oldName) {
    	//指定浏览器内部打开
        response.setHeader("Content-Disposition", "inline; filename=\"" + oldName + "\"");
        writeFile(response, file);
    }
// 写入文件
void writeFile(HttpServletResponse response, File file) {
        ServletOutputStream os = null;
        FileInputStream is = null;
        BufferedOutputStream bos = null;
        try {
            os = response.getOutputStream();
            is = new FileInputStream(file);
            bos = new BufferedOutputStream(os);

            byte[] len = new byte[1024];
            int read = 0;
            while ((read = is.read(len)) != -1) {
                bos.write(len, 0, read);
            }
            bos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

预览word

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            	// 省略通请求地址  //localhost:8000/download?name=1.jpg;  获取文件代码  
            	//假装这个file 是通过地址
            	File file = new File("C:\\Users\\-AiYuan\\Desktop\\1.jpg");
            	//imageStoragePath  word 中图片要存储的路径 
            	previewOfficeDoc(request, response, file.getAbsolutePath(), imageStoragePath);
            }
            
	 //预览word .doc 文件
    void previewOfficeDoc(HttpServletRequest request, HttpServletResponse response,String fileAbsolutePath, String buildPath) {
        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
            //调用工具类的 word 转html
            String wordParseToHtmlString = PoiUtil2.wordParseToHtmlString(fileAbsolutePath, buildPath, request);
            os.write(wordParseToHtmlString.getBytes("UTF-8"));
            os.flush();
        } catch (IOException | ParserConfigurationException | TransformerException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

预览excel

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            	// 省略通请求地址  //localhost:8000/download?name=1.jpg;  获取文件代码  
            	//假装这个file 是通过地址
            	File file = new File("C:\\Users\\-AiYuan\\Desktop\\1.jpg");
            	 previewOfficeXls(response,  file.getAbsolutePath());
            }
            
	   //预览excel .xls 文件
    void previewOfficeXls(HttpServletResponse response, String fileAbsolutePath) {
        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
            //调用 解析工具解析excel
            String wordParseToHtmlString = PoiUtil2.excelPareToHtmlString(fileAbsolutePath);
            os.write(wordParseToHtmlString.getBytes("UTF-8"));
            os.flush();
        } catch (IOException | ParserConfigurationException | TransformerException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

效果图

excel

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值