图片、pdf、wrod和excel 在线预览
自定义文件服务器 图片、pdf、wrod和excel 在线预览
- 场景介绍
- 准备工作
- 预览图片,pdf
- 预览word
- 预览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)throwsIOException, ParserConfigurationException, TransformerException {HWPFDocument wordDoc = new HWPFDocument(new FileInputStream(fileName));WordToHtmlConverter wthc = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());//这里用来处理word 中的图片 保存到服务器本地磁盘并且 返回在线可访问的地址wthc.setPicturesManager(new PicturesManager() {@Overridepublic 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 转htmlString 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();//调用 解析工具解析excelString 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();}}}}
效果图
图片、pdf、wrod和excel 在线预览相关推荐
- java零碎要点010---Java实现office文档与pdf文档的在线预览功能
最近项目有个需求要java实现office文档与pdf文档的在线预览功能,刚刚接到的时候就觉得有点难,以自己的水平难以在三四天做完.压力略大.后面查找百度资料.以及在同事与网友的帮助下,四天多把它做完 ...
- aspose实现word,excel在线预览
aspose实现word,excel在线预览 一,项目中引入aspose依赖 <dependency><groupId>com.aspose</groupId>&l ...
- java 预览word文档_Java实现office文档与pdf文档的在线预览功能
最近项目有个需求要java实现office文档与pdf文档的在线预览功能,刚刚接到的时候就觉得有点难,以自己的水平难以在三四天做完.压力略大.后面查找百度资料.以及在同事与网友的帮助下,四天多把它做完 ...
- Vue+SpringBoot实现Excel在线预览功能(PS:添加样式比较费劲)
** 问题还原: ** 在做项目时,用户需要上传Excel模板,里面有对应的各种数据.我们拿到这个Excel后,定时的根据其中的数据去查对应的实时数据并进行计算,然后将实时数据和计算后的数据保存到Ex ...
- Python excel转成html页面 excel 在线预览
Python excel转成html页面 excel 在线预览 因为这两天公司的项目要用到在浏览excel 所以就在做这个功能.一开始查了很多资料 都是各种不行,最后好不容易找到一些辅助资料 终于是今 ...
- js-xlsx vue导入excel在线预览
js-xlsx vue导入excel在线预览 导入XLSX库 官方地址Github 安装 npm install xlsx --s 引入 import XLSX from 'xlsx' HTML &l ...
- 前端-Excel在线预览
前端-Excel在线预览 最近项目中有一个 Excel 预览的需求,就调研了一下 xls/xlsx.word.ppt 文件在线预览功能的实现 . 实现 xls/xlsx.word.ppt 在线预览功能 ...
- vue移动端实现excel在线预览
上篇博客我提到了ios手机不能实现下载功能,但是可以实现预览,图片预览和pdf预览我已经在前篇博客做了讲解,但是,在工作中大家上传最多的应该是excel的文件,今天我就讲解一下excel移动端的预览实 ...
- html做在线预览pdf文件,html中在线预览pdf文件之pdf在线预览插件
html中在线预览pdf文件之pdf在线预览插件 最近遇到一个需求,要在html页面查看pdf生成的pdf文件! 翻来覆去找到两种办法 ,最后采用了jquery.media.js插件 方式一 将pdf ...
最新文章
- 中科院陆汝钤获吴文俊人工智能最高成就奖,百度王海峰获吴文俊人工智能杰出贡献奖...
- DOM中元素节点、属性节点、文本节点的理解
- UA MATH563 概率论的数学基础 鞅论初步1 条件期望
- Windows下配置单机Hadoop环境
- 一步步编写操作系统 28 cpu乱序执行
- .NET网络编程学习(二)
- QT中信号与槽的常见使用
- python基础之迭代器、生成器、装饰器
- 图片裁切批处理_Imgbot 在线图片批量处理工具 支持缩放、压缩、裁切、水印等...
- scratch编程 超有趣反应力游戏
- 前端基础CSS+html篇 2w字吐血总结
- 关于serverlet
- LTSPICE使用教程:参数变量和参数扫描
- 百度收录了大量死链网址如何处理
- 带式输送机、采样控制系统、变速器、离心成型机、齿轮减速器、三级减速器、蜗轮减速机、多向混合机、颗粒包装机、机床夹具、球阀、支撑掩护式液压支架、轮式移动机器人、液压传动、轴向柱塞泵…毕业设计 课程设计
- 关于系统中的流水帐号
- 64-bit Linux安装英伟达显卡驱动
- 计算机应用设计大赛获奖信息,北京大学第六届“计算机应用设计大赛”圆满落幕...
- mysql 查找小写字母_MySQL中查询时对字母大小写的区分
- 柔宇六周年庆2000人齐聚,揭开“柔性星球”面纱