文档在线预览实现方法

文档预览一般先将word、excel、ppt等文档转换为pdf格式,再用网页展示。本文介绍使用aspose+pdf.js实现该功能,aspose内置转换方法,pdf.js用于显示。还提到将文件输入流内容写到响应输出流供前端显示,以及图片二进制形式传前端用img标签显示的额外知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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就是我的图片二进制形式

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值