练涛

spring boot + pdf.js 实现pdf文件预览

准备工作

  1. pdf.js文件 下载后放入到项目静态文件夹
  2. 可运行的springboot项目

首先为了直观的展示,springboot直接返回一个写死文件路径的输出流

@Slf4j
@RestController
@RequestMapping("/media")
public class GetMediaController {

    @RequiresPermissions("media:index")
    @RequestMapping(value = "index")
    public ModelAndView index(){
        return new ModelAndView("preview/preview");
    }

    @RequestMapping(value = "/preview", method = RequestMethod.GET)
    public void pdfStreamHandler(HttpServletRequest request, HttpServletResponse response) {
        //PDF文件地址
        File file = new File("D:\\kvf-admin-activiti\\userFile\\file\\20200922\\《人类简史》.pdf");
        if (file.exists()) {
            byte[] data = null;
            FileInputStream input=null;
            try {
                input= new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
            } catch (Exception e) {
                System.out.println("pdf文件处理异常:" + e);
            }finally{
                try {
                    if(input!=null){
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

前端获取展示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>pdf预览</title>
</head>
<body>
<h1 onclick="onLineReadPDF()" style="cursor: pointer;color:blue">在线阅读PDF文件</h1>

<script>
    function onLineReadPDF() {
        window.open("/static/plugins/pdfjs-2.5.207-dist/web/viewer.html?file=http://localhost:8077/media/preview");
    }
</script>
</body>
</html>

值得注意的是,/static/plugins/pdfjs-2.5.207-dist/web/viewer.html 应该是自己的文件路径。
http://localhost:8077/media/preview是我们Controller接口。

鼠标点击h1标签,就会跳转出我们的pdf文件预览页面.

以上完成了pdf的预览整合,到此就可结束了。

接下来,把预览嵌入到Layui的弹窗中

 layer.open({
                    type: 2
                    ,title: 'pdf预览' //不显示标题栏
                    ,closeBtn: false
                    ,area: ['90%','90%']
                    // ,shade: 0.8
                    // ,id: 'LAY_layuipro' //设定一个id,防止重复弹出
                    ,btn: ['继续', '关闭']
                    ,btnAlign: 'c'
                    ,moveType: 1 //拖拽模式,0或者1
                    ,moveOut: true
                    ,closeBtn:1
                    ,content: 'http://localhost:8077/static/plugins/pdfjs-2.5.207-dist/web/viewer.html?file=http://localhost:8077/media/preview'
                    ,success: function(layero){
                        //点击按钮 do something
                    }
                });
posted @ 2020-09-23 10:26  练涛  阅读(2421)  评论(0编辑  收藏  举报