Java實現PDF在線預覽功能(四種方式)

Java實現PDF在線預覽

    @RequestMapping("/preview1")
    public void er(HttpServletResponse response){
        File file = new File("G:\\桌面\\Thymeleaf3.0中文翻譯文檔@www.java1234.com.pdf");
        if (file.exists()){
            byte[] data = null;
            try {
                FileInputStream input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
                input.close();
            } catch (Exception e) {
                System.out.println(e);
            }
        }else{
            return;
        }
    }
    @ResponseBody
    @RequestMapping("/preview2")
    public void findPdf( HttpServletResponse response) throws IOException{
        response.setContentType("application/pdf");
        FileInputStream in = new FileInputStream(new File("G:\\桌面\\Thymeleaf3.0中文翻譯文檔@www.java1234.com.pdf"));
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[512];
        while ((in.read(b))!=-1) {
            out.write(b);
        }
        out.flush();
        in.close();
        out.close();
    }
    @ResponseBody
    @RequestMapping("/preview3")
    public void devDoc(HttpServletRequest request, HttpServletResponse response, String storeName) throws Exception {
        request.setCharacterEncoding("UTF-8");
        String ctxPath = request.getSession().getServletContext().getRealPath("");
        String downLoadPath = "G:\\桌面\\Thymeleaf3.0中文翻譯文檔@www.java1234.com.pdf";
        response.setContentType("application/pdf");
        FileInputStream in = new FileInputStream(new File(downLoadPath));
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        while ((in.read(b))!=-1) {
            out.write(b);
        }
        out.flush();
        in.close();
        out.close();
    }
    @ResponseBody
    @RequestMapping("/preview")
    public void download( HttpServletResponse response
                        ) throws IOException {
        String filePath = "G:\\桌面\\Thymeleaf3.0中文翻譯文檔@www.java1234.com.pdf";
        System.out.println("filePath:" + filePath);
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] bs = new byte[1024];
        int len = 0;
        response.reset(); // 非常重要
        if (true) { // 在線打開方式
            URL u = new URL("file:///" + filePath);
            String contentType = u.openConnection().getContentType();
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "inline;filename="
                    + "2019年上半年英語四級筆試準考證(戴林峰).pdf");
            // 文件名應該編碼成utf-8,註意:使用時,我們可忽略這句
        } else {
            // 純下載方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + "2019年上半年英語四級筆試準考證(戴林峰).pdf");
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(bs)) > 0) {
            out.write(bs, 0, len);
        }
        out.flush();
        out.close();
        br.close();
    }

Java快捷實現PDF在線預覽

本文章利用各個瀏覽器的內核支持PDF預覽功能來做,PDF的預覽網上說的最多的是PDF.JS實現預覽,也找瞭好多文章,死活最後實現不瞭,通過這個方法解決瞭,如果有PDF.js解決的可以大傢溝通交流下。

這裡提一下,其他word和excel可以通過aspose代碼轉換成PDF,也很快有效。可以網上搜下。

方法很簡單,首先引入的都是IO的包。

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;

接下來就是在自己的後臺controller裡面寫個方法。裡面file的文件可以通過參數或是封裝方式獲取,這個裡面的流不需要關閉,瀏覽器會自動獲取然後展示。關閉的話瀏覽器就無法加載!

@RequestMapping(value = "/showpdf")
    public void showpdf(HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            File file = new File("D:/xyptFile/java.pdf");
            FileInputStream fileInputStream = new FileInputStream(file);
            response.setHeader("Content-Type", "application/pdf");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

文章來源:從其他各個文章中測試驗證,取得最優方案。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: