java 预览word,ppt,xls等office文件技术实现

1 篇文章 0 订阅
网上找了很多相关文档,也爬过很多坑,现在基于最新版本的软件(OpenOffice 4.1.3)和jar(Jodconverter Core--4.0.0-RELEASE)
包整理出一份可以实现office文件预览功能,供参考。

1.pdf文件预览

参考pdf js官网:pdf预览例子
准备一个pdf文件,pdf.js,pdf.worker.js(从官网可以下载)
预览代码pdftest.html(从官网copy后做微小改动)必须放到容器中才能预览,tomcat,apache都行

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>pdf预览</title>
<!-- <script src="//mozilla.github.io/pdf.js/build/pdf.js"></script> -->
<!-- 改成引用本地js-->
<script src="js/pdf.js"></script>

<div style="margin: auto;width: 500px;">
  <a href="javascript:void(0)" id="prev">上一页</a>
  <a href="javascript:void(0)"  id="next">下一页</a>
  &nbsp; &nbsp;
  <span>页码: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<div  style="margin: auto;width: 600px;">
<canvas style="width: 100%;" id="the-canvas"></canvas>
</div>
</head>
<body>
<script type="text/javascript">
//预览测试文件
var url = 'Paper.pdf';
// 改成引用本地js
PDFJS.workerSrc = 'js/pdf.worker.js';
//PDFJS.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 1,
canvas = document.getElementById('the-canvas'),
ctx = canvas.getContext('2d');
function renderPage(num) {
pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function(page) {
 var viewport = page.getViewport(scale);
 canvas.height = viewport.height;
 canvas.width = viewport.width;

 // Render PDF page into canvas context
 var renderContext = {
   canvasContext: ctx,
   viewport: viewport
 };
 var renderTask = page.render(renderContext);

 // Wait for rendering to finish
 renderTask.promise.then(function() {
   pageRendering = false;
   if (pageNumPending !== null) {
     // New page rendering is pending
     renderPage(pageNumPending);
     pageNumPending = null;
   }
 });
});

// Update page counters
document.getElementById('page_num').textContent = pageNum;
}

/**
* If another page rendering in progress, waits until the rendering is
* finised. Otherwise, executes rendering immediately.
*/
function queueRenderPage(num) {
if (pageRendering) {
 pageNumPending = num;
} else {
 renderPage(num);
}
}

/**
* Displays previous page.
*/
function onPrevPage() {
if (pageNum <= 1) {
 return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);

/**
* Displays next page.
*/
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
 return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);

/**
* Asynchronously downloads PDF.
*/
PDFJS.getDocument(url).then(function(pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;

// Initial/first page rendering
renderPage(pageNum);
});
</script>
</body>
</html>

预览效果截图
这里写图片描述

2.office文档转pdf

2.1安装openoffice

openoffice官网:下载地址

2.2引入jar包
maven jar地址:jodconverter-core
如果是maven项目直接引用依赖即可

<!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-core -->
<dependency>
    <groupId>org.jodconverter</groupId>
    <artifactId>jodconverter-core</artifactId>
    <version>4.0.0-RELEASE</version>
</dependency>

如果是web项目需下载其依赖包
这里写图片描述

2.3 java将office文件转换成pdf文件
直接粘源码

import java.io.File;
import java.util.Date;
import java.util.regex.Pattern;
import org.jodconverter.OfficeDocumentConverter;
import org.jodconverter.office.DefaultOfficeManagerBuilder;
import org.jodconverter.office.OfficeException;
import org.jodconverter.office.OfficeManager;

public class Test {
    public static void word2pdf(String inputFilePath) {
        System.out.println("inputFilePath==="+inputFilePath);
        String outputFilePath = getOutputFilePath(inputFilePath);  
        File inputFile = new File(inputFilePath);  
        if (inputFile.exists()) {// 找不到源文件, 则不启动  
            DefaultOfficeManagerBuilder config = new DefaultOfficeManagerBuilder();  
            String officeHome = getOfficeHome();  
            config.setOfficeHome(officeHome);  
            OfficeManager officeManager = config.build();  
            try {
                officeManager.start();
                OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);  
                File outputFile = new File(outputFilePath);  
                if (!outputFile.getParentFile().exists()) { // 假如目标路径不存在, 则新建该路径  
                    outputFile.getParentFile().mkdirs();  
                }  
                converter.convert(inputFile, outputFile);  
                officeManager.stop();
            } catch (OfficeException e) {
                e.printStackTrace();
            }  
        }  
    }  
    //如果不输出在同目录,自行构造outputFilePath路径
    public static String getOutputFilePath(String inputFilePath) {  
      String outputFilePath = inputFilePath.replaceAll(".[a-zA-Z]*$", ".pdf");  
      return outputFilePath;  
    }  

    public static String getOfficeHome() {  
      String osName = System.getProperty("os.name");  
      if (Pattern.matches("Linux.*", osName)) {  
          return "/opt/openoffice.org3";  
      } else if (Pattern.matches("Windows.*", osName)) { 
      //openoffice安装路径 
          return "C:/Program Files (x86)/OpenOffice 4";  
      } else if (Pattern.matches("Mac.*", osName)) {  
          return "/Application/OpenOffice.org.app/Contents";  
      }  
      return null;  
    }  

    public static void main(String[] args) throws Exception {
        Date d1 = new Date();
        Test.word2pdf("d:/log/w.doc");
        Date d2 = new Date();
        System.out.println(d2.getTime()-d1.getTime());
//      Test.word2pdf("d:/log/a.pptx");
//      Test.word2pdf("d:/log/w.xlsx");
    }
}

好了,office转pdf,pdf预览都具备,office文件预览就是将其转换成pdf进行预览查看。
相关源码去下面git地址查看
springMvc

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值