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
                    }
                });


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM