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 ...
随机推荐
- 负载均衡各个算法JAVA诠释版
00 前言 首先给大家介绍下什么是负载均衡(来自百科) 负载均衡建立在现有网络结构之上,它提供了一种廉价有效透明的方法扩展 网络设备和 服务器的带宽.增加 吞吐量.加强网络数据处理能力.提高网络的灵活 ...
- Erlang那些事儿第3回之我是函数(fun),万物之源MFA
Erlang代码到处都是模式匹配,这把屠龙刀可是Erlang的看家本领.独家绝学,之前在<Erlang那些事儿第1回之我是变量,一次赋值永不改变>文章提到过,Erlang一切皆是模式匹配. ...
- 加薪攻略之UI组件库实践—storybook
目录 加薪攻略之UI组件库实践-storybook 一.业务背景 二.选用方案 三.引入分析 项目结构 项目效果 四.实现步骤 1.添加依赖 2.添加npm执行脚本 3.添加配置文件 4.添加必要的w ...
- IDEA:配置Tomcat并运行应用
1.File->ProjectStructre->Artifacts 如下界面 3.下一步:如图所示 4.选择相应的Module就行 5.第一次运行程序时最好选择运行的配置,否则可能运行的 ...
- 杭电OJ2039——三角形(c++)(易错题:数据类型不确定)
三角形 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submis ...
- String -- 从源码剖析String类
几乎所有的 Java 面试都是以 String 开始的,String 源码属于所有源码中最基础.最简单的一个,对 String 源码的理解也反应了你的 Java 基础功底. String 是如何实现的 ...
- netty核心组件之EventLoopGroup和EventLoop
这节我们着重介绍netty最为核心的组件EventLoopGroup和EventLoop EventLoopGroup:顾名思义就是EventLoop的组,下面来看它们的继承结构 在netty中我们可 ...
- Ubuntu_Gedit配置
Ubuntu_Gedit配置 为了换Ubuntu的时候能够更加方便,不用再用手重新打一遍代码,丢几个Gedit配置-- External Tools gdb compile (F2) #!/bin/s ...
- 关于spring-data与elasticsearch的使用,自定义repository
之前没有使用过spring-data,关于spring-data有很多很棒的设计,例如仅仅只需要声明一个接口就行,你甚至都不需要去实现,spring-data有内置默认的实现类,基本就上完成绝大多数对 ...
- nodejs中的文件系统
. 目录 简介 nodejs中的文件系统模块 Promise版本的fs 文件描述符 fs.stat文件状态信息 fs的文件读写 fs的文件夹操作 path操作 简介 nodejs使用了异步IO来提升服 ...