一、前端代码

 //预览功能
preview: function () {
//判断选中状态
var ids ="";
var num = 0; $(".checkbox").each(function () {
if($(this).is(':checked')){
ids +=$(this).val() + ",";
num++;
}
});
if(num <=0 ){
toastr.error('请选择需要预览的文件!');
return;
}
if(num > 1){
toastr.error('页面下载只支持单个文件预览!');
return;
}
ids = ids.slice(0,ids.length-1);
$.ajax({
type: "post",
url: backbasePath+'/apia/v1/file/queryById',
dataType:"json",
data:{
token:$("#token").val(),
id:ids,
},
success: function(data) {
if('000000'==data.code){
// 文件路径
var path=data.data.file_path;
// 文件名称
var fileName=data.data.file_name;
// 获取文件后缀名
var suffix=fileName.substring(fileName.lastIndexOf(".")+1);
//如果对应的是文档
if(suffix == 'doc' || suffix == 'docx' || suffix == 'txt'|| suffix == 'pdf'){
//打开跳转页面
window.open(frontTemplatesPath + 'previewFile.html?suffix='+suffix+'&path='+path+'&fileName='+fileName,"_blank");
} else{
toastr.error('当前文件类型暂不支持预览!');
}
} else if (('900000' == data.code) || ('999999'== data.code)) {
toastr.error('查询文件信息失败!');
} else {
toastr.error(data.msg);
}
},
error: function () {
toastr.error('查询文件信息失败!');
}
});
},
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件预览界面</title>
</head>
<body>
<div class="container">
<div>
<div >
<iframe style="width: 100%;height: 1000px;" src="" id="pdf"></iframe>
</div>
</div>
</div>
</body>
</html>
<script src="/coalminehwaui/static/js/jquery-3.1.1.min.js"></script>
<script src="/coalminehwaui/static/js/project/common.js"></script>
<script src="/coalminehwaui/static/js/plugins/toastr/toastr.min.js"></script>
<!-- slimscroll把任何div元素包裹的内容区加上具有好的滚动条-->
<script src="/coalminehwaui/static/js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
<script>
'use strict';
$(function () {
LookPlan.getUrlString();
LookPlan.init();
});
var LookPlan = new Object({
getUrlString:function(name){
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return '';
},
init:function() {
var suffix =LookPlan.getUrlString('suffix');
var path =LookPlan.getUrlString('path');
var fileName =LookPlan.getUrlString('fileName');
var src=backbasePath + '/apia/v1/file/previewFile?path='+path+'&fileName='+fileName+'&suffix='+suffix;
setTimeout(function () {
document.getElementById("pdf").src=src;
}, 500);
}
});
</script>

二、后端代码

<!-- 文件转换成pdf-->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.1.1</version>
</dependency>

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
/**
* 文档文件预览
*/
@RequestMapping(path = "/previewFile")
public void preview(HttpServletResponse response, @RequestParam(required = true)String path, @RequestParam(required = true)String fileName, @RequestParam(required = true)String suffix) throws Exception {
// 读取pdf文件的路径
String pdfPath="";
// 将对应的后缀转换成小写
String lastSuffix=suffix.toLowerCase();
//读取文件内容,获取文件存储的路径
String orgPath = filePath + path;
// 生成pdf文件的路径
String toPath = filePath + "pdf/";
// 判断对应的pdf是否存在,不存在则创建
File folder = new File(toPath);
if (!folder.exists()) {
folder.mkdirs();
}
// doc类型
if (lastSuffix.equals("pdf")) {
// pdf 文件不需要转换,直接从上传文件路径读取即可
pdfPath=orgPath;
} else {
// 转换之后的pdf文件
String newName=fileName.replace(lastSuffix,"pdf");;
File newFile = new File( toPath+"/"+newName);
// 如果转换之后的文件夹中有转换后的pdf文件,则直接从里面读取即可
if (newFile.exists()) {
pdfPath =toPath+"/"+newName;
}else {
pdfPath = wordToPdf(fileName,orgPath, toPath,lastSuffix);
}
}
// 读取文件流上
FileInputStream fis = new FileInputStream(pdfPath);
//设置返回的类型
response.setContentType("application/pdf");
//得到输出流,其实就是发送给客户端的数据。
OutputStream os = response.getOutputStream();
try {
int count = 0;
//fis.available()返回文件的总字节数
byte[] buffer = new byte[fis.available()];
//read(byte[] b)方法一次性读取文件全部数据。
while ((count = fis.read(buffer)) != -1)
os.write(buffer, 0, count);
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null)
os.close();
if (fis != null)
fis.close();
}
}
   /**
* 将之前对应的word文件转换成pdf,然后预览pdf文件
*/
public String wordToPdf(String orgFile,String orgPath, String toPath, String suffix ){
// 转换之后的pdf文件
String targetFile=orgFile.replace(suffix,"pdf");
File inputWord = new File(orgPath);
File outputFile = new File(toPath+targetFile);
try {
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
if(suffix.equals("doc")){
converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
} else if(suffix.equals("docx")){
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
} else if(suffix.equals("txt")){
converter.convert(docxInputStream).as(DocumentType.TEXT).to(outputStream).as(DocumentType.PDF).execute();
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return toPath+targetFile;
}

java 文件转成pdf文件 预览的更多相关文章

  1. java实现word转pdf在线预览(前端使用PDF.js;后端使用openoffice、aspose)

    背景 之前一直是用户点击下载word文件到本地,然后使用office或者wps打开.需求优化,要实现可以直接在线预览,无需下载到本地然后再打开. 随后开始上网找资料,网上资料一大堆,方案也各有不同,大 ...

  2. java原装代码完成pdf在线预览和pdf打印及下载

    这是我在工作中,遇到这样需求,完成需求后,总结的成果,就当做是工作笔记,以免日后忘记,当然,能帮助到别人是最好的啦! 下面进入正题: 前提准备: 1. 项目中至少需要引入的jar包,注意版本: a)  ...

  3. C# 将PowerPoint文件转换成PDF文件

    PowerPoint的优势在于对演示文档的操作上,而用PPT查看资料,反而会很麻烦.这时候,把PPT转换成PDF格式保存,再浏览,不失为一个好办法.在日常编程中和开发软件时,我们也有这样的需要.本文旨 ...

  4. 在Linux下将HTML文件转换成PDF文件

    今天要写一个上交的作业,本来是想用Office Word来写的,但是,我的Office貌似不能用了,但是,Linux下的LibreOffice写出的文档,在打印的时候是经常出现乱码的.所以,后来想到可 ...

  5. html 转成 pdf 进行预览、下载、打印

    html 页面转成 pdf,直接看代码: 参考地址: https://github.com/linwalker/render-html-to-pdf 给出代码 方便粘贴: var downPdf = ...

  6. C#调用WPS将文档转换成pdf进行预览

    引用:https://www.jianshu.com/p/445996126c75 vs启动项目可以生成wps实例 本地iis部署的站点却不行 原因是vs是管理员权限,而iis没有权限 解决方法 启动 ...

  7. Linux不用使用软件把纯文本文档转换成PDF文件的方法

    当你有一大堆文本文件要维护的时候,把它们转换成PDF文档会好一些.比如,PDF更适合打印,因为PDF文档有预定义布局.除此之外,还可以减少文档被意外修改的风险. 要将文本文件转换成PDF格式,你要按照 ...

  8. windwos下的转excel到PDF并预览的工具,有Aspose,Spire,原生Office三种方式

    SchacoPDFViewer 项目链接:https://github.com/tiancai4652/SchacoPDFViewer/tree/master 主要实现了对于Excel文件转换PDF, ...

  9. 实战动态PDF在线预览及带签名的PDF文件转换

    开篇语: 最近工作需要做一个借款合同,公司以前的合同都是通过app端下载,然后通过本地打开pdf文件,而喜欢创新的我,心想着为什么不能在线H5预览,正是这个想法,说干就干,实践过程总是艰难的,折腾了3 ...

随机推荐

  1. java中byte,byte[]和int之间的转换

    1>byte类型转换为,直接隐式转换,适用于要求保持数值不变,例如要求进行数值计算 如 byte b=0x01; int i=b; 2>另一种是要求保持最低字节中各个位不变,3个高字节全部 ...

  2. 11. const 修饰成员函数

    const 限定只读,对函数的实参进行保护 常数据成员:必须出现在类的定义体中,常数据成员必须进行初始化,并且不能被更新,但常数据成员的初始化只能通过构造函数的初始化列表进行 1. 常函数 成员函数加 ...

  3. ArrayDeque API 与算法分析

    ArrayDeque 是双端队列的动态数组实现,可以当作栈和队列来使用.作为栈时,它的效率比 Stack 更高,作为队列时,效率比 LinkedList 更高.ArrayDeque 大部分操作的时间复 ...

  4. Java 在windows中配置Maven环境和阿里云镜像

    目录 1. 下载Maven 2. 配置环境变量 3. 配置镜像 4. 配置本地仓库 1. 下载Maven 官网:https://maven.apache.org/ 下载:apache-maven-3. ...

  5. 【ASM】asm中添加 diskgroup

    环境:rhel5 Oracle10g rac 背景:在esxi中添加了一个20g的共享磁盘准备存放归档日志用 一.准备环境 1.添加共享磁盘并且格式化 #fdisk -l查看磁盘已经添加完成 #fdi ...

  6. ctfshow—web—web5

    打开靶机,代码审计 附上代码 <?php error_reporting(0); ?> <html lang="zh-CN"> <head> & ...

  7. 通过LOGMNR查找程式带入的实际值

    生产库中出现了大量的锁表,需要得到当时程式执行的SQL以及其带入的值 1.查看SQL SELECT SQL_ID FROM V$SESSION WHERE SID=(SELECT FINAL_BLOC ...

  8. oracle释放空间到OS

    测试: 建表空间 CREATE TABLESPACE TESTTBS DATAFILE '/oradata01/dfhdb/testtbs01.dbf' SIZE 2G; 在表空间上建表 CREATE ...

  9. PyTorch 于 JupyterLab 的环境准备

    PyTorch 是目前主流的深度学习框架之一,而 JupyterLab 是基于 Web 的交互式笔记本环境.于 JupyterLab 我们可以边记笔记的同时.边执行 PyTorch 代码,便于自己学习 ...

  10. ABAP中SQL语句,指定索引(oracle)

    ①常用的两种方法: 1.指定使用全表扫描:%_HINTS ORACLE 'FULL(table_name)' 表示扫描整个表 2.指定索引:%_HINTS ORACLE 'INDEX("ta ...