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 ...
随机推荐
- win10 设置文件夹别名、修改文件夹图标、修改文件夹别名、英文目录和中文目录、设置文件夹中文名称、快捷访问显示设置中文
最近在设置文件夹的时候发现个有趣的事情: 系统路径 C:\Users\Administrator 内的文件夹不仅有图标还显示中文名称,但是打开路径的时候显示的却是英文,这就激发了我的探索欲,究竟是为 ...
- HTML文本格式化标签
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 < ...
- 指令重排序 as-if-serial
笔者认为看完一本书或刚要了解完一个知识点 最好自己先运行一些DEMO 自己尝试着去了解下各种意思 这样知识点最终一定是你的.靠死记硬背的讨论或简单的粗暴的看下资料 脑子里肯定还是一团浆糊. p.p ...
- java线程与内核线程的关系,及怎么定义ThreadPoolExecutor相关参数
p.p1 { margin: 0; font: 12px Menlo } p.p1 { margin: 0; font: 12px Menlo } p.p2 { margin: 0; font: 12 ...
- jupyter安装插件Nbextensions,实现代码提示功能(终极方法)
jupyter安装插件,实现代码提示功能 第一步 pip install jupyter_contrib_nbextensions -i https://mirrors.tuna.tsinghua.e ...
- 简单TCP服务器和TCP客户端源码(Golang)
以下代码为服务端,非最终版代码,服务端可以接受多个客户端的请求,且所有消息会显示在服务端上,服务端无法发送消息: package main import ( "fmt" " ...
- python基础语法1-变量
l Python基础语法1-变量
- 在IDEA中通过Module管理多个项目
你身边有没有这种顽固的Eclipse忠实用户:IDEA不能一个窗口管理多个项目!太不方便了! 对于一个窗口同时管理多个项目的需求,在我们日常开发时候是经常需要的.尤其当我们在分布式环境下,在一个窗口中 ...
- Git软件安装过程
Git程序安装过程 官网: https://git-scm.com/ 下载: https://git-scm.com/downloads 我的操作系统是 Windows + 64位的 https:// ...
- 【Linux】使用grep快速比较两个文件不同
两个文件的比较,会有同学说使用diff,和vimdiff就可以快速比较,为什么还要使用grep呢? 有些时候,diff和vimdiff的时候环境不符合,这样的情况,就可以使用grep来解决这个问题. ...