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();
        });
//后台代码
@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");// 设置强制下载不打开            
            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

猜你喜欢

转载自www.cnblogs.com/langcangsheng/p/11527898.html