第一步

服务器端要安装Apache的 openoffice,下载地址 :http://www.openoffice.org/download

第二步

OpenOffice 文件转换服务,调用接口,传入文件链接,返回转换成pdf的文件流。

如需要转换其他文件类型,可以自己在代码中修改,只需修改文件后缀,就可以转换成对应的文件类型。看下图

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>cn.test</groupId><artifactId>officepreview</artifactId><version>1.0-SNAPSHOT</version><dependencies><!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-local --><dependency><groupId>org.jodconverter</groupId><artifactId>jodconverter-local</artifactId><version>4.4.0</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><!-- poi库主要用来调整excel转pdf的格式调整(将所有列调整到一页) --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>5.0.0</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.0.0</version></dependency></dependencies></project>

OfficePreview.java  主要代码(主要是 toPdfFile 方法 )

package cn.test.office;import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.core.office.OfficeUtils;
import org.jodconverter.core.util.IOUtils;
import org.jodconverter.core.util.StringUtils;
import org.jodconverter.local.JodConverter;
import org.jodconverter.local.office.LocalOfficeManager;import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ResourceBundle;@WebServlet(name = "officepreview")
public class OfficePreview extends HttpServlet {private ResourceBundle rd = ResourceBundle.getBundle("office");@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) {try {// 获取配置String repositoryPath = rd.getString("repository");// 远程文件路径(需要URLDecoder解码,解决存在中文字符问题)String url = URLDecoder.decode(req.getParameter("url"), "utf-8");// 转换后的文件名称String filename = req.getParameter("filename");// 下载到本地downLoad(url, repositoryPath + filename);// 转换文件,使用response,将pdf文件以流的方式发送的前端FileInputStream fis = new FileInputStream(toPdfFile(repositoryPath + filename));// copy文件流到输出流IOUtils.copy(fis, resp.getOutputStream());fis.close();} catch (Exception e) {e.printStackTrace();try {resp.getOutputStream().println(e.getMessage());} catch (IOException ex) {ex.printStackTrace();}}}public File toPdfFile(String sourceFilePath) throws IOException, OfficeException {String officeHomePath = rd.getString("officeHomePath");boolean excelPreviewSetting = "1".equals(rd.getString("excelPreviewSetting"));// 源文件File sourceFile = new File(sourceFilePath);//转换之后文件生成的地址// 如果路径地址不存在if (!sourceFile.exists()) throw new RuntimeException("转换源文件不存在");// 如果本身是pdf文件,就直接返回if(sourceFile.getName().endsWith("pdf")) {return sourceFile;}// 转换后的文件File newFile = new File(String.format("%s\\%s", sourceFile.getParent(), sourceFile.getName().replace(".","")+".pdf"));if (!newFile.exists()){ // 文件不存在,才需要转换// 获取openoffice管理器LocalOfficeManager localOfficeManager = LocalOfficeManager.builder().officeHome(officeHomePath).install().build();// 判断openoffice服务是否打开if(!localOfficeManager.isRunning()) localOfficeManager.start();// 已开启预览设置,并且是xls文件if (excelPreviewSetting && sourceFile.getName().endsWith("xls") || sourceFile.getName().endsWith("xlsx")){// 获取调整预览格式后的文件sourceFile = setExcelPrintParameter(sourceFile.getPath());}//文件转化JodConverter.convert(sourceFile).to(newFile).execute();// 关闭localOfficeManager服务OfficeUtils.stopQuietly(localOfficeManager);}return newFile;}/*** 文件下载* @param url   远程文件链接* @param downloadPath  本地路径*/private void downLoad(String url, String downloadPath){BufferedInputStream bis =null;BufferedOutputStream bos=null;try {// 判断路径合法性if (StringUtils.isBlank(url)) return;// 判断本地是否已存在该文件,已存在则不重复下载if (new File(downloadPath).exists()) return;int contentLength = getConnection(url).getContentLength();System.out.println("文件的大小是:"+contentLength);InputStream is= getConnection(url).getInputStream();bis = new BufferedInputStream(is);FileOutputStream fos = new FileOutputStream(downloadPath);bos= new BufferedOutputStream(fos);int b;byte[] byArr = new byte[1024];while((b= bis.read(byArr))!=-1){bos.write(byArr, 0, b);}System.out.println("下载的文件的大小是----------------------------------------------:"+contentLength);} catch (Exception e) {e.printStackTrace();}finally{try {if(bis !=null) bis.close();if(bos !=null) bos.close();} catch (IOException e) {e.printStackTrace();}}}private HttpURLConnection getConnection(String httpUrl) throws Exception {URL url = new URL(httpUrl);HttpURLConnection connection =  (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setRequestProperty("Content-Type", "application/octet-stream");connection.setDoOutput(true);connection.setDoInput(true);connection.setRequestProperty("Connection", "Keep-Alive");connection.connect();return connection;}/*** 设置Excel打印参数* @param sourceFilePath 源文件路径*/private File setExcelPrintParameter(String sourceFilePath) throws IOException{File sourceFile = new File(sourceFilePath);Workbook workbook = WorkbookFactory.create(new FileInputStream(sourceFile));for (int i = 0; i < workbook.getNumberOfSheets(); i++){Sheet sheet = workbook.getSheetAt(i);sheet.setFitToPage(true);PrintSetup printSetup =  sheet.getPrintSetup();printSetup.setFitWidth((short) 1);//设置打印方向,横向就是trueprintSetup.setLandscape(false);//设置A4纸printSetup.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);}workbook.write(new FileOutputStream(sourceFile));return sourceFile;}/*** 在oldName基础上添加后缀suffix* @param oldName 旧文件名* @param suffix 后缀* @return 返回新文件名*/public static String getNewFileName(String oldName, String suffix){// 名字为空直接返回nullif (StringUtils.isEmpty(oldName)) return oldName;// 获取点符号下标int dotIndex = oldName.lastIndexOf('.');// 如果没有点符号说明没有文件类型,直接添加suffix后缀if (-1 == dotIndex) return oldName + suffix;// 获取没有类型名称的文件名String name = oldName.substring(0, dotIndex);// 获取类型String type = oldName.substring(dotIndex);return name + suffix + type;}
}

office.properties  配置属性文件

# 转换后文件存储路径
repository=I:\\test\\
# openoffice安装路径
officeHomePath=C:\\Program Files (x86)\\OpenOffice 4
# 是否开启excel预览格式调整  1=开启,0=关闭(将所有列调整到同一页)
excelPreviewSetting=0

OpenOffice 文件转PDF,实现文件预览相关推荐

  1. 【SpringBoot】40、SpringBoot中使用Aspose将文件转为PDF实现在线预览

    一.简介 Aspose 是 .NET 和 Java 开发组件以及为 Microsoft SQL Server Reporting Services 和 JasperReports 等平台提供渲染扩展的 ...

  2. 前端js打开pdf文件--文件通过浏览器打开,以pdf形式进行预览

    通过点击button按钮,触发 @click="openPDF(performance_report)"方法,把对应需要展示的pdf传送到openPDF()方法内,这里的pdf文件 ...

  3. 用 Adobe 设置 PDF 文件在文件管理器右侧预览窗格预览

    用 Adobe 设置 PDF 文件在文件管理器右侧预览窗格预览 前提 安装 Adobe Acrobat Pro DC (64-bit) 示例如下: (上图下面部分是CSDN自动添加的水印) 说明:其他 ...

  4. 最近很火的在线文件预览txt、doc、ppt、pdf、excel、jpg、png、zip、tar.gz等各种文件及压缩文件在线解压和预览,包括前后端设计和源码,编写搜索引擎多关键词检索名称和内容(四)

    最近很火的在线文件预览txt.doc.ppt.pdf.excel.jpg.mp4.png.zip.tar.gz等各种文件及压缩文件在线解压和预览,包括前后端设计和源码,编写一个文件搜索引擎实现多关键词 ...

  5. PDF.js + Vue 浏览器以只读方式打开PDF,后台返回文件流,前端实现预览pdf

    如果你想光前端完成 office(xls,doc,ppt) 文件的预览,只能提供你这些库来使用 PDF http://mozilla.github.com/pdf.js/ XLS https://gi ...

  6. 处理pdf文件直接下载,不预览

    ***## 出现文件跨域下载问题 https 域名与http 文件 处理方案**(把图片 http 更换为https)* const toUrl = filePath.split('://')[1] ...

  7. 最近很火的在线文件预览txt、doc、ppt、pdf、excel、jpg、png、zip、tar.gz等各种文件及压缩文件在线解压和预览,包括前后端设计和源码,编写搜索引擎多关键词检索名称和内容(五)

    最近很火的在线文件预览txt.doc.ppt.pdf.excel.jpg.mp4.png.zip.tar.gz等各种文件及压缩文件在线解压和预览,包括前后端设计和源码,编写一个文件搜索引擎实现多关键词 ...

  8. Java通过openOffice实现word,excel,ppt转成pdf实现在线预览

    Java通过openOffice实现word,excel,ppt转成pdf实现在线预览 一.OpenOffice 1.1 下载地址 1.2 JodConverter 1.3 新建实体类PDFDemo ...

  9. h5页面如何预览excel文件_在网页中预览excel表格文件

    项目需求在前端页面中实现预览excel表格的功能,上网了解之后大致总结为一下几种方法. 1.office文档转换为pdf,再转swf,然后通过网页加载flash进行预览 2.通过 xlsx.js,js ...

  10. minio实现大文件分片上传+断点续传+预览

    minio实现大文件分片上传+断点续传+预览 只提供后端java代码 思路: 前端分片 校验文件md5是否已经存在 --不存在创建临时桶存分片 校验分块是否已经上传 分块上传 合并分块 校验合成后md ...

最新文章

  1. 强化学习(九)- 策略梯度方法 - 梯度上升,黑箱优化,REINFORCE算法及CartPole实例
  2. 如何正确实施人工智能
  3. EXP-00091错误的说明和解决方法
  4. Netty源码解析8-ChannelHandler实例之CodecHandler
  5. 不确定mysql是否安装成功了怎么办
  6. knockout checkbox 全选
  7. jQuery on 绑定的事件触发多次
  8. 产品设计体会(2011)网络推广实战
  9. java框架异常怎么处理_java异常处理与处理框架-笔记
  10. 【Lazada新手开店】Lazada开店费用有哪些?
  11. 全国计算机软考程序员考试大纲(2012)
  12. 常用の工具(update 22.11.11)
  13. ST-LINK烧录stm32程序步骤
  14. 让你终身受用的世界顶级思维
  15. 语义标签(Semantic label)与多模态模型的一些关系
  16. 使用代理服务器是否安全?
  17. 使用信用卡 要避开这些陷阱
  18. 谈谈#define xxxx(x,y) x##y
  19. Linux设备驱动子系统第二弹 - SD卡
  20. js开发:数组的push()、pop()、shift()和unshift()

热门文章

  1. ApacheCN 公众号文章汇总 2019.5
  2. 使用SecureFX内容显示中文乱码问题
  3. vb.net控件随窗口大小调整
  4. java创始人现在在哪里直播,三年败光120亿,他曾是某电商巨头创始人,如今却靠直播度日!...
  5. 学生宿舍管理系统之概念结构设计
  6. 【JokerのKintex7325】SDK程序从QSPI启动过慢分析。
  7. AFNetworking官网文档及翻译
  8. 【计算机视觉与深度学习】全连接神经网络(二)
  9. 如何创建一颗“山楂树”
  10. 网络安全 社会工程学--钓鱼网站的制作和利用(让你了解整个钓鱼网站 背后的秘密.)