java 文件轉成pdf文件 預覽


一、前端代碼

 //預覽功能
    preview: function () {
        //判斷選中狀態
        var ids ="";
        var num = 0;

        $(".checkbox").each(function () {
            if($(this).is(':checked')){
                ids +=$(this).val() + ",";
                num++;
            }
        });
        if(num <=0 ){
            toastr.error('請選擇需要預覽的文件!');
            return;
        }
        if(num > 1){
            toastr.error('頁面下載只支持單個文件預覽!');
            return;
        }
        ids = ids.slice(0,ids.length-1);
        $.ajax({
            type: "post",
            url: backbasePath+'/apia/v1/file/queryById',
            dataType:"json",
            data:{
                token:$("#token").val(),
                id:ids,
            },
            success: function(data) {
                if('000000'==data.code){
                    // 文件路徑
                    var path=data.data.file_path;
                    // 文件名稱
                    var fileName=data.data.file_name;
                    // 獲取文件后綴名
                    var suffix=fileName.substring(fileName.lastIndexOf(".")+1);
                    //如果對應的是文檔
                    if(suffix == 'doc' || suffix == 'docx' || suffix == 'txt'|| suffix == 'pdf'){
                        //打開跳轉頁面
                        window.open(frontTemplatesPath + 'previewFile.html?suffix='+suffix+'&path='+path+'&fileName='+fileName,"_blank");
                    } else{
                        toastr.error('當前文件類型暫不支持預覽!');
                    }
                } else if (('900000' == data.code) || ('999999'== data.code)) {
                    toastr.error('查詢文件信息失敗!');
                } else {
                    toastr.error(data.msg);
                }
            },
            error: function () {
                toastr.error('查詢文件信息失敗!');
            }
        });
   },
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件預覽界面</title>
</head>
<body>
<div class="container">
    <div>
        <div >
            <iframe  style="width: 100%;height: 1000px;" src="" id="pdf"></iframe>
        </div>
    </div>
</div>
</body>
</html>
<script src="/coalminehwaui/static/js/jquery-3.1.1.min.js"></script>
<script src="/coalminehwaui/static/js/project/common.js"></script>
<script src="/coalminehwaui/static/js/plugins/toastr/toastr.min.js"></script>
<!-- slimscroll把任何div元素包裹的內容區加上具有好的滾動條-->
<script src="/coalminehwaui/static/js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
<script>
    'use strict';
    $(function () {
        LookPlan.getUrlString();
        LookPlan.init();
    });
    var LookPlan = new Object({
        getUrlString:function(name){
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return '';
        },
        init:function() {
            var suffix =LookPlan.getUrlString('suffix');
            var path =LookPlan.getUrlString('path');
            var fileName =LookPlan.getUrlString('fileName');
            var src=backbasePath + '/apia/v1/file/previewFile?path='+path+'&fileName='+fileName+'&suffix='+suffix;
            setTimeout(function () {
                document.getElementById("pdf").src=src;
            }, 500);
        }
    });
</script>

二、后端代碼

<!-- 文件轉換成pdf-->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.1.1</version>
</dependency>

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
/**
     * 文檔文件預覽
     */
    @RequestMapping(path = "/previewFile")
    public void preview(HttpServletResponse response,  @RequestParam(required = true)String path, @RequestParam(required = true)String fileName, @RequestParam(required = true)String suffix) throws Exception {
        // 讀取pdf文件的路徑
        String pdfPath="";
        // 將對應的后綴轉換成小寫
        String lastSuffix=suffix.toLowerCase();
        //讀取文件內容,獲取文件存儲的路徑
        String orgPath = filePath  + path;
        // 生成pdf文件的路徑
        String toPath = filePath + "pdf/";
        // 判斷對應的pdf是否存在,不存在則創建
        File folder = new File(toPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        // doc類型
        if (lastSuffix.equals("pdf")) {
            // pdf 文件不需要轉換,直接從上傳文件路徑讀取即可
            pdfPath=orgPath;
        } else {
            // 轉換之后的pdf文件
            String newName=fileName.replace(lastSuffix,"pdf");;
            File newFile = new File( toPath+"/"+newName);
            // 如果轉換之后的文件夾中有轉換后的pdf文件,則直接從里面讀取即可
            if (newFile.exists()) {
                pdfPath =toPath+"/"+newName;
            }else {
                pdfPath = wordToPdf(fileName,orgPath, toPath,lastSuffix);
            }
        }
        // 讀取文件流上
        FileInputStream fis = new FileInputStream(pdfPath);
        //設置返回的類型
        response.setContentType("application/pdf");
        //得到輸出流,其實就是發送給客戶端的數據。
        OutputStream os = response.getOutputStream();
        try {
            int count = 0;
            //fis.available()返回文件的總字節數
            byte[] buffer = new byte[fis.available()];
            //read(byte[] b)方法一次性讀取文件全部數據。
            while ((count = fis.read(buffer)) != -1)
                os.write(buffer, 0, count);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null)
                os.close();
            if (fis != null)
                fis.close();
        }
    }
   
   /**
     * 將之前對應的word文件轉換成pdf,然后預覽pdf文件
     */
    public String wordToPdf(String orgFile,String orgPath, String toPath, String suffix ){
        // 轉換之后的pdf文件
        String targetFile=orgFile.replace(suffix,"pdf");
        File inputWord = new File(orgPath);
        File outputFile = new File(toPath+targetFile);
        try  {
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            if(suffix.equals("doc")){
                converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
            } else if(suffix.equals("docx")){
                converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            } else if(suffix.equals("txt")){
                converter.convert(docxInputStream).as(DocumentType.TEXT).to(outputStream).as(DocumentType.PDF).execute();
            }
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toPath+targetFile;
    }

 


免責聲明!

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



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