pdf,excel转word所需jar包  网盘链接  提取码:4gmw

目录

1.在resources下新建license.xml

2.文件转换工具类

3.文件下载

4.批量下载

5.在线打开文件



1.在resources下新建license.xml

Tips:这个文件好像是去除水印需要的东西,word转pdf不需要,excel转pdf时需要用到(可能这个jar版本有点低)

<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Excel for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

2.文件转换工具类

因为浏览器不支持打开word文档以及excel文件,也不能单独给服务器装个其他插件来在线打开,所以就决定先转换成pdf然后再用浏览器打开(doc,docx,wps,xls,xlsx这些我都替小伙伴们试过啦,木的问题,其他类型的大家可以再研究研究)

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;@Slf4j
public class FileUtils {/*** Word 转换  Pdf* @param fileFullPath  旧文件全路径   /home/2022-07/保密协议.docx*/public static String doc2pdf(String fileFullPath) {try {//    ----->   /home/2022-07/String path = fileFullPath.substring(0, fileFullPath.lastIndexOf("/")+1);//    ----->保密协议String fileName=fileFullPath.substring(fileFullPath.lastIndexOf("/")+1,fileFullPath.lastIndexOf("."));String outFIleFullPath=path+fileName+".pdf";File file = new File(outFIleFullPath); // 新建一个pdf文档FileOutputStream os = new FileOutputStream(file);/** 这里需要指定Linux服务器上从本地windows上传的字体库,否则生成乱码*  【/usr/share/fonts/windowsFonts/】位于Linux服务器上的windows字体,作为word转pdf用*///FontSettings.getDefaultInstance().setFontsFolder("/usr/share/fonts/windowsFonts/", true);Document doc = new Document(fileFullPath);doc.save(os,SaveFormat.PDF);// 全面支持DOC, DOCX,wpsos.close();return  outFIleFullPath;} catch (Exception e) {e.printStackTrace();log.info("pdf转换异常");return null;}}/*** excel 转换  Pdf* @param fileFullPath  旧文件全路径   /home/2022-07/保密协议.xlsx*/public static String excel2pdf(String fileFullPath) {if (!getLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生return null;}try {String path = fileFullPath.substring(0, fileFullPath.lastIndexOf("/")+1);String fileName=fileFullPath.substring(fileFullPath.lastIndexOf("/")+1,fileFullPath.lastIndexOf("."));String outFIleFullPath=path+fileName+".pdf";File pdfFile = new File(outFIleFullPath); // 输出路径FileInputStream excelstream = new FileInputStream(fileFullPath);Workbook wb = new Workbook(excelstream);// excel路径,这里是先把数据放进缓存表里,然后把缓存表转化成PDFFileOutputStream fileOS = new FileOutputStream(pdfFile);PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();pdfSaveOptions.setOnePagePerSheet(true);//参数true把内容放在一张PDF页面上;wb.save(fileOS, pdfSaveOptions);fileOS.close();return  outFIleFullPath;} catch (Exception e) {e.printStackTrace();log.info("excel转换异常");return null;}}public static boolean getLicense() {boolean result = false;try {InputStream is =FileUtils.class.getClassLoader().getResourceAsStream("license.xml"); //// license.xml这个文件你放在静态文件资源目录下就行了License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}public static void main(String[] args) {FileUtils.doc2pdf("D:\\home\\2022-07\\保密协议.wps");}
}

3.文件下载

Tips:下载的是本地文件,后续用了文件存储服务器后可能会改,还有个小问题,下载文件时    响应头    Content-Disposition   文件名称中文乱码

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** 文件下载** @param filePath* @param response*/public void downloadFile(String filePath, HttpServletResponse response, HttpServletRequest request) {InputStream fis = null;OutputStream out = null;try {// path是指欲下载的文件的路径。File file = new File(filePath);// 取得文件名。String filename = file.getName();// 以流的形式下载文件。fis = new BufferedInputStream(new FileInputStream(filePath));byte[] buffer = new byte[fis.available()];fis.read(buffer);// 清空responseresponse.reset();String userAgent = request.getHeader("User-Agent");if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {filename = URLEncoder.encode(filename, "UTF-8");} else {// 非IE浏览器的处理:filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");}// 设置response的Headerresponse.addHeader("Content-Disposition", "attachment;filename=" + filename);response.addHeader("Content-Length", "" + file.length());out = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream");out.write(buffer);} catch (Exception e) {e.printStackTrace();response.setContentType("application/json;charset=utf-8");try {response.getWriter().write(JSON.toJSONString(DtoUtil.returnFail("出错啦", "E400")));} catch (IOException ex) {ex.printStackTrace();}} finally {try {if (fis != null) {fis.close();}} catch (IOException e) {e.printStackTrace();}if (out != null) {try {out.close();} catch (IOException e) {e.printStackTrace();}}}}

4.批量下载

public void downloadZip(String ids, HttpServletResponse response, HttpServletRequest request) {//响应头的设置response.reset();response.setCharacterEncoding("utf-8");response.setContentType("multipart/form-data");//设置压缩包的名字String billname = "附件包";String downloadName = billname + ".zip";//返回客户端浏览器的版本号、类型String agent = request.getHeader("USER-AGENT");//设置压缩流:直接写入response,实现边压缩边下载ZipOutputStream zipos = null;//循环将文件写入压缩流DataOutputStream os = null;try {//针对IE或者以IE为内核的浏览器:if (agent.contains("MSIE") || agent.contains("Trident")) {downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");} else {//非IE浏览器的处理:downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1");}response.setHeader("Content-Disposition", "attachment;fileName=" + downloadName);zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法List<String> fileIds = Arrays.asList(ids.split(","));String lastFileName=""; //记录上个文件名List<String> lastFileNames=new ArrayList<>();int number=0;  //上个文件名括号里的数字for (String fileId : fileIds) {//获取文件路径以及文件名ProjectFileEntity entity = projectFileDao.getFilePath(fileId);String filePath = entity.getFilePath();String fileName = entity.getFileName().substring(0,entity.getFileName().lastIndexOf("."));String suffix = entity.getFileName().substring( entity.getFileName().lastIndexOf(".") + 1);if (lastFileNames.contains(fileName)){number++;fileName=fileName+"("+number+")";}lastFileNames.add(fileName);File file = new File(filePath);//添加ZipEntry,并ZipEntry中写入文件流zipos.putNextEntry(new ZipEntry(fileName+"."+suffix));os = new DataOutputStream(zipos);InputStream is = new FileInputStream(file);byte[] b = new byte[100];int length = 0;while ((length = is.read(b)) != -1) {os.write(b, 0, length);}is.close();zipos.closeEntry();}} catch (Exception e) {e.printStackTrace();}//关闭流try {os.flush();os.close();zipos.close();} catch (IOException e) {e.printStackTrace();}}

5.在线打开文件

Tips:下载的是本地文件,后续用了文件存储服务器后可能会改,还有个小问题,在线预览时    响应头    Content-Disposition   文件名称中文乱码

 public void openFile(String filePath, HttpServletResponse response, HttpServletRequest request) {File f = new File(filePath);String suffix = f.getName().substring(f.getName().lastIndexOf(".") + 1);BufferedInputStream br = null;OutputStream out = null;try {if (!f.exists()) {response.sendError(404, "File not found!");return;}br = new BufferedInputStream(new FileInputStream(f));byte[] buf = new byte[1024];int len = 0;response.reset(); // 非常重要URL u = new URL("file:///" + filePath);if (suffix.equalsIgnoreCase("pdf")) {response.setContentType("application/pdf");} else {response.setContentType(u.openConnection().getContentType());}//解决文件名乱码String userAgent = request.getHeader("User-Agent");String formFileName;if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {formFileName = URLEncoder.encode(f.getName(), "UTF-8");} else {// 非IE浏览器的处理:formFileName = new String(f.getName().getBytes("UTF-8"), "ISO-8859-1");}response.setHeader("Content-Disposition", "inline; filename=" + formFileName);response.setCharacterEncoding("UTF-8");out = response.getOutputStream();while ((len = br.read(buf)) > 0)out.write(buf, 0, len);} catch (IOException e) {e.printStackTrace();response.setContentType("application/json;charset=utf-8");try {response.getWriter().write(JSON.toJSONString(DtoUtil.returnFail("出错啦", "E400")));} catch (IOException ex) {ex.printStackTrace();}} finally {try {if (br != null) {br.close();}} catch (IOException e) {e.printStackTrace();}if (out != null) {try {out.close();} catch (IOException e) {e.printStackTrace();}}}}

java实现文件下载,批量下载,文件在线预览,word转pdf,excel转pdf相关推荐

  1. java将office文档,word,ppt,pdf文档转换成swf文件在线预览

    java将office文档pdf文档转换成swf文件在线预览 第一步,安装openoffice.org openoffice.org是一套sun的开源office办公套件,能在widows,linux ...

  2. 快速实现word、excel、ppt、txt等办公文件在线预览功能(Java版)

    点击关注公众号,实用技术文章及时了解 来源:blog.csdn.net/weixin_40986713/ article/details/109527294 java实现办公文件在线预览功能是一个大家 ...

  3. Java 实现word、excel、ppt、txt等办公文件在线预览功能!

    大家好,我是宝哥! 如何用 Java 实现word.excel.ppt.txt等办公文件在线预览功能?本文告诉你答案! java 实现办公文件在线预览功能是一个大家在工作中也许会遇到的需求,网上些公司 ...

  4. 手把手教你用 Java 实现word、excel、ppt、txt等办公文件在线预览功能!

    如何用 Java 实现word.excel.ppt.txt等办公文件在线预览功能?本文告诉你答案! java 实现办公文件在线预览功能是一个大家在工作中也许会遇到的需求,网上些公司专门提供这样的服务, ...

  5. java flexpaper_java web word文件 pdf文件在线预览源码(flexpaper)

    [实例简介]java web word文件 pdf文件在线预览源码 经过测试 [实例截图] [核心代码] BrowsenOnline html, body{ height:100%; } body { ...

  6. Nginx搭建文件服务器以及文件在线预览和强制下载

    文件服务 直接查看server块配置 server {listen 1234;server_name 127.0.0.1;charset utf-8; # 避免中文乱码 location / {roo ...

  7. java下载文件以及预览

    java下载文件以及预览 1.代码如下 /*** 不需要返回HttpServletResponse,会报错* @param response*/@GetMapping("/downloadF ...

  8. SpringBoot+Vue+OpenOffice实现文档管理(文档上传、下载、在线预览)

    场景 SpringBoot集成OpenOffice实现doc文档转html: SpringBoot集成OpenOffice实现doc文档转html_BADAO_LIUMANG_QIZHI的博客-CSD ...

  9. Spring Boot 实现万能文件在线预览-开源学习一

    Spring Boot 实现万能文件在线预览-开源学习一 1. 项目特性 支持word excel ppt,pdf等办公文档 支持txt,java,php,py,md,js,css等所有纯文本 支持z ...

  10. doc文件在线预览 vue_跨平台(uniapp)文件在线预览解决方案

    一.前言 之前写过一篇文章关于上传目录文件:uni-app系统目录文件上传(非只图片和视频)解决方案,这次来解决文件预览问题. uni-app 是一个使用 Vue.js 开发所有前端应用的框架,开发者 ...

最新文章

  1. Handlebars的基本用法
  2. java强引用、软引用、弱引用、虚引用-Java的引用类型总共有四种,你都知道吗
  3. 数据结构与索引-- mysql InnoDB存储引擎索引
  4. 蚂蚁链发布新一代网络平台「FAIR」 区块链进入隐私计算原生时代
  5. Kubernetes 部署 Mysql 8.0 数据库(单节点)
  6. ELK温度监控--lmsensorsbeat
  7. linux 安装tuxedo
  8. 【总结】前缀和与差分(一维差分、二维差分、树上差分(待学!))
  9. 使用 Infiniband 实现 RDMA !IB卡介绍!下载IB 驱动 !lspci | grep Mell 查看 IB卡!
  10. 微信支付开通流程,及微信支付商户号申请详细流程介绍
  11. 病毒入侵:全靠分布式 Gossip 协议
  12. epub 电子书文件如何使用浏览器打开
  13. 干货|我的三年产品基本功之PRD文档攥写
  14. java模拟键盘按键
  15. GitLab上传文件教程
  16. Win11调整分区大小的方法有哪些?
  17. html雾霾蓝色号rgb,新型流行色—雾霾蓝
  18. Python使用Plotly绘图工具,绘制散点图、线形图
  19. 软件测试---前言篇
  20. 软考高级 真题 2013年上半年 信息系统项目管理师 综合知识

热门文章

  1. 一文搞懂Redis缓存穿透/击穿/雪崩
  2. 最强蜗牛击败毁灭机器人_最强蜗牛恶魔形态怎么玩_恶魔形态能力变化突变攻略_3DM手游...
  3. 智能洁面仪的功能特点
  4. 直播网站需要多大的服务器,手机直播服务器需要多大带宽是由哪些方面决定的?...
  5. css实现圆环效果,利用css实现圆环效果的方法
  6. Linux下的二进制文件比较工具
  7. python怎么加字幕_使用Python和百度语音识别生成视频字幕的实现
  8. 使用hex6x.exe将out文件生成hex文件方法
  9. 深大操作系统:xv6 综合实验一:copy on write,slab,信号量,调度与系统调用
  10. 无货源模式是什么?亚马逊店群是什么?