PDF文件預覽和下載


背景:項目中實現pdf文件的預覽以及下載

    環境:jdk1.8、SpringBoot2.0、Maven
    PDF.js下載地址: http://mozilla.github.io/pdf.js/getting_started/#download(下載2.1.266版本即可)

將下載的源碼拷入項目中
    修改viewer.js:

將defaultUrl: {
    value: 'compressed.tracemonkey-pldi-09.pdf',---此處是默認的pdf的路徑
    kind: OptionKind.VIEWER
  }
  修改為:
  defaultUrl: {
    value: '',
    kind: OptionKind.VIEWER
  }

    打開新窗口預覽:

     <input type="button" value="預覽" id="viewBtn">
    <script type="text/javascript">
        $("#viewBtn")
                .click(
                        function() {
                            var curWwwPath = window.document.location.href;
                            var pathName = window.document.location.pathname;
                            var pos = curWwwPath.indexOf(pathName);
                            var localhostPath = curWwwPath.substring(0, pos);

                         //此處以get請求調用后台接口   並在新的窗口下打開此pdf文件

             window.open("http://localhost:8081/api/file/preview?fileName=2019_PDF.pdf");


                        });
    //后台controller代碼,根據前端傳入的fileName到指定目錄讀取pdf文件,進行展示
    @RequestMapping(value = "/preview", method = RequestMethod.GET)
    public void prePDF(String fileName, HttpServletRequest request, HttpServletResponse response) {
        logger.info("文件名:" + fileName);
        File file = new File("E:/pdf/" + fileName);
        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) {
                logger.info("pdf文件處理異常...");
            }
        }
    }

    PDF文件下載:

<input type="button" value="下載" id="download">
$("#download").click(function() {
            var form = $("<form>");
            form.attr("style", "display:none");
            form.attr("target", "");
            form.attr("method", "post");//提交方式為post
            form.attr("action", "/downloadFile");//定義action
            $("body").append(form);
            form.submit();
        });

 

//這個例子是展示傳的死的參數  如果想實現前台向后台傳參  可以在Html中寫一個form表單然后隱藏掉  在form表單中寫入一個input 通過這個input進行傳值

//例:

 

<form action="/api/file/downloadFile" style="display: none" method="post" id="downloadForm">
<input type="text" name="fileId" value="0" id="downloadFilename">
</form>

function downloadpdf(fileId) {
if(parseInt(fileId)==0){
layer.msg("暫無文件!")
}else {
// var form = $("<form>");
// var input = document.createElement('input'); //創建input節點
// input.setAttribute('type', 'text'); //定義類型是文本輸入
// document.getElementsByTagName("input")[0].name="fileName";
// document.getElementsByName("fileName")[0].value="lalla";
// document.getElementsByTagName("form")[0].appendChild(input);
// form.attr("style", "display:none");
// form.attr("target", "");
// form.attr("method", "post");//提交方式為post
// form.attr("action", "/api/file/downloadFile");//定義action
document.getElementById("downloadFilename").value = fileId;
var form = document.getElementById("downloadForm");
$("body").append(form);
form.submit();
}


//我這里通過前台向后台傳入了一個id 然后后台通過id在數據庫中查詢文件的地址

//若想傳其他參數可以參考這個...
 


//后台代碼
@RequestMapping(value="/downloadFile")
    public void downloadFile(HttpServletResponse response) {
        String downloadFilePath = "E:/pdf/";    //被下載的文件在服務器中的路徑,
        String fileName = "0602.pdf";            //被下載文件的名稱
    
        File file = new File(downloadFilePath+fileName);
        if (file.exists()) {

            // 設置強制下載不打開      針對於瀏覽器能打開的文件類型  如果不進行這一行的設置  瀏覽器並不會進行下載  而是直接在瀏覽器中打開
            response.setContentType("application/force-download");     

           //當點擊下載時  指定瀏覽器中彈出下載框的文件名  如果注釋這段代碼 文件名會默認顯示為當前接口注解的名字(比如本文中的downloadFile)
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                  outputStream.write(buffer, 0, i);
                  i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(bis != null) {
                    try {
                        bis.close();
                    }catch(IOException e) {
                        e.printStackTrace();
                    }
                }
                if(fis != null) {
                    try {
                        fis.close();
                    }catch(IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

 
    預覽頁面頂部會有相應的工具欄,打印、下載、翻頁、放大等,根據個人實際需要,可以查看頁面源碼,在viewer.html中注釋掉相應的功能.

    也可以通過pdfbox讀取PDF文件內容:

引入jar包:
<!-- PDF讀取依賴 -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.4</version>
        </dependency>


后台讀取pdf文件代碼:

public String viewPDF(String proCode,String fileName,String originPage, HttpServletRequest request) {
        request.setAttribute("dse_sessionId", request.getParameter("dse_sessionId").trim());
        logger.info("披露報告預覽文件名:" + fileName);
        File file = new File(constant.getExposeLocalDir() + fileName);
        if (!file.exists()) { // 文件不存在,則 從FTP下載文件到本地
            }
        }
        //讀取pdf文件內容-代碼實現
        try {
            PDDocument document = PDDocument.load(file);
            document.getClass();
            if(!document.isEncrypted()) {
                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
                stripper.setSortByPosition(true);
                PDFTextStripper textStripper = new PDFTextStripper();
                String exposeContent = textStripper.getText(document);
                String[] content = exposeContent.split("\\n");
                StringBuffer stringBuffer = new StringBuffer();
                for(String line:content) {
                    stringBuffer.append(line);
                }
            }
            
        } catch (Exception e) {
            logger.info("讀取pdf文件異常...");
        }
    
        return "";
    }

 

聲明:本片文章轉載自:https://blog.csdn.net/Xing_Pengfei/article/details/97649888

筆者只不過在此基礎上稍微進行修改,筆者用的是Maven項目,可能和此位博客稍微有些不同
————————————————
版權聲明:本文為CSDN博主「午夜學徒xpf」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/Xing_Pengfei/article/details/97649888


免責聲明!

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



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