介绍:文档预览一般实现步骤为:

1、将文档(word,excel,ppt等)转换为pdf文件格式

2、使用网页展示pdf文件

我使用的是aspose+pdf.js方法实现,使用前者将文档转换为pdf格式,在使用pdf.js插件显示。

将pdf.js插件集成到项目后进行如下操作:

1、aspose内置将(word,excel,ppt)转换为pdf的方法,调用即可。
@RequestMapping("/path/{id}") public void getPath(@PathVariable Integer id,
HttpServletResponse response) throws IOException { File file =
service.getPDFById(id, getUploadPath()); try (FileInputStream input = new
FileInputStream(file)) { inToOut(input, response.getOutputStream()); } catch
(Exception e) { response.getOutputStream().write("预览失败,请重试".getBytes()); } }
2、其中file就是转换好的pdf文件,inToOut()的代码如下:
protected void inToOut(InputStream in, OutputStream out) throws IOException {
byte[] dataByte = new byte[1024]; int l; while ((l = in.read(dataByte)) != -1)
out.write(dataByte, 0, l); }
作用是将文件输入流的内容写到response的输出流中,前端显示即可,代码如下:
if(jQuery.inArray(format,noImg)!=-1){
viewPath="${ctxPath}/plugin/onlineView/web/viewer.html?file=${ctxPath}/${code}/path/"+id;
}else{
viewPath="${ctxPath}/plugin/onlineView/imgView.html?id="+id+"&url=${ctxPath}/${code}/getImgStream/";
}
前者就是是显示我的pdf文件的路径,将其做为a标签的href属性值即可。

附上一个额外知识点:
@ResponseBody @RequestMapping("/getImgStream/{id}") public byte[]
getImgStream(@PathVariable Integer id) { String fileName =
service.findById(id).getUrl(); String filePath = getUploadPath() + "document/"
+ fileName; File file = new File(filePath); byte[] buffer = null; try
(FileInputStream inputFile = new FileInputStream(file)) { buffer = new
byte[inputFile.available()]; inputFile.read(buffer); } catch (IOException e) {
e.printStackTrace(); } return Base64.getEncoder().encode(buffer); }
由于第二个路径是显示图片,所以先获取图片的二进制形式传到前端使用img标签显示即可
$("#img").attr("src","data:image/*;base64,"+data);
data就是我的图片二进制形式

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:637538335
关注微信