java 文件转成pdf文件 预览
一、前端代码
//预览功能
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文件 预览的更多相关文章
- java实现word转pdf在线预览(前端使用PDF.js;后端使用openoffice、aspose)
背景 之前一直是用户点击下载word文件到本地,然后使用office或者wps打开.需求优化,要实现可以直接在线预览,无需下载到本地然后再打开. 随后开始上网找资料,网上资料一大堆,方案也各有不同,大 ...
- java原装代码完成pdf在线预览和pdf打印及下载
这是我在工作中,遇到这样需求,完成需求后,总结的成果,就当做是工作笔记,以免日后忘记,当然,能帮助到别人是最好的啦! 下面进入正题: 前提准备: 1. 项目中至少需要引入的jar包,注意版本: a) ...
- C# 将PowerPoint文件转换成PDF文件
PowerPoint的优势在于对演示文档的操作上,而用PPT查看资料,反而会很麻烦.这时候,把PPT转换成PDF格式保存,再浏览,不失为一个好办法.在日常编程中和开发软件时,我们也有这样的需要.本文旨 ...
- 在Linux下将HTML文件转换成PDF文件
今天要写一个上交的作业,本来是想用Office Word来写的,但是,我的Office貌似不能用了,但是,Linux下的LibreOffice写出的文档,在打印的时候是经常出现乱码的.所以,后来想到可 ...
- html 转成 pdf 进行预览、下载、打印
html 页面转成 pdf,直接看代码: 参考地址: https://github.com/linwalker/render-html-to-pdf 给出代码 方便粘贴: var downPdf = ...
- C#调用WPS将文档转换成pdf进行预览
引用:https://www.jianshu.com/p/445996126c75 vs启动项目可以生成wps实例 本地iis部署的站点却不行 原因是vs是管理员权限,而iis没有权限 解决方法 启动 ...
- Linux不用使用软件把纯文本文档转换成PDF文件的方法
当你有一大堆文本文件要维护的时候,把它们转换成PDF文档会好一些.比如,PDF更适合打印,因为PDF文档有预定义布局.除此之外,还可以减少文档被意外修改的风险. 要将文本文件转换成PDF格式,你要按照 ...
- windwos下的转excel到PDF并预览的工具,有Aspose,Spire,原生Office三种方式
SchacoPDFViewer 项目链接:https://github.com/tiancai4652/SchacoPDFViewer/tree/master 主要实现了对于Excel文件转换PDF, ...
- 实战动态PDF在线预览及带签名的PDF文件转换
开篇语: 最近工作需要做一个借款合同,公司以前的合同都是通过app端下载,然后通过本地打开pdf文件,而喜欢创新的我,心想着为什么不能在线H5预览,正是这个想法,说干就干,实践过程总是艰难的,折腾了3 ...
随机推荐
- 算法图解第一章_二分查找_python
什么是二分查找? 我们先玩一个游戏. 在1至100之间我写下一个数,由你来猜测这个数是多少.我会告诉你高了还是低了. 最简单的办法就是每次取一半. 例如 "50""低了& ...
- 数据库零基础之---了解数据库的事务[ACID]
事务指逻辑上的一组操作,组成这组操作的各个单元,要不全部成功,要不全部不成功. 我们先举一个例子来描述一下事务: 假设要张三通过银行给李四进行转账1000元钱,张三原有余额10000元整,李四有人民币 ...
- fastjsion反序列化漏洞渗透测试笔记
本文原创地址:https://www.cnblogs.com/yunmuq/p/14268028.html 一.背景 fastjsion是阿里的开源Java工具:https://github.com/ ...
- Ts有限状态机
ts版本的有限状态机 最近做小游戏要做切换人物状态,花点时间写了一个有限状态机,使用语言为Ts,也可改成自己的语言 按照目前的逻辑,这个可以继续横向扩展,某些做流程管理 先上预览图 Fsm:状态机类 ...
- MySQL常用字符串函数和日期函数
数据函数 SELECT ABS(-8); /*绝对值*/ SELECT CEILING(9.4); /*向上取整*/ SELECT FLOOR(9.4); /*向下取整*/ SELECT RAND() ...
- 怎么启用apache的mod_log_sql模块将所有的访问信息直接记录在mysql中
怎么启用apache的mod_log_sql模块将所有的访问信息直接记录在mysql中
- 【Oracle】查看表空间是否为自动扩展
查看指定的表空间是否为自动扩展 SQL> select file_name,autoextensible,increment_by from dba_data_files where tab ...
- [SSL]在线检查服务器HTTPS安全
https://myssl.com/ SSL/TLS安全评估报告 https://www.ssllabs.com/ssltest/ SSL Server Test HTTPS开启工具(IIS) htt ...
- Linux Shell 编程基础详解——吐血整理,墙裂推荐!
第一部分:Linux Shell 简介 Shell 是一个用 C 语言编写的程序,它是用户使用 Linux 的桥梁.Shell 既是一种命令语言,又是一种程序设计语言. Shell 是指一种应用程序, ...
- 把vscode打造成技术写作神器
作为技术开发,大家平时肯定需要记录技术笔记.甚至有的同学还开通可自己的技术博客或者技术公众号进行创作. 这个时候有套趁手的写作工具尤为重要,节省下时间好好休息一下,对于咱们程序员来说更加重要.因为最近 ...