天天看點

java 檔案輸出到頁面

轉發請注明:https://blog.csdn.net/somdip/article/details/96113875 

第一種:檔案流直接列印到HttpServletResponse ,進而輸出到頁面。

controller

@RequestMapping("/p")
    public void p(HttpServletResponse response) {
        String wordPath ="D://副本.doc";
        File file_1 = new File(wordPath);
        String fileFullName=  file_1.getName();
        String fileType  =  fileFullName.substring(fileFullName.lastIndexOf(".")+1,fileFullName.length());//副本.doc
        String fileName  =  fileFullName.substring(0,fileFullName.lastIndexOf("."));//副本
        OutputStream outputStream = null;
        try {
            fileFullName = fileName+".pdf";//副本.pdf
            //防止中文亂碼
//            fileName = URLEncoder.encode(fileName+".pdf", "UTF-8");
            String downloadFileName = new String(fileFullName.getBytes(), "ISO-8859-1");//檔案名中文亂碼
            response.reset();
            log.info("檔案名:"+downloadFileName);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            //生成pdf檔案
            ActiveWord2Pdf.p(outputStream,wordPath);
       }catch (Exception e){
            log.error("異常:"+e);
        }
        finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
           

utils

public static  String p(OutputStream outputStream,String wordPath) throws Exception {
//        String wordPath ="D://1.doc";
        File file_1 = new File(wordPath);
        String fileFullName=  file_1.getName();
        String fileType  =  fileFullName.substring(fileFullName.lastIndexOf(".")+1,fileFullName.length());
        String fileName  =  fileFullName.substring(0,fileFullName.lastIndexOf("."));
        String filePath  =  file_1.getParent();
        String html = filePath+fileName+".html";
        Word2PdfUtil.docToHtml(wordPath,html);
        String pdf = filePath+fileName+".pdf";
//        HtmlCovertPdf(html,pdf);
        HtmlCovertPdf(html,outputStream);
        return pdf;
//        System.out.println(file_1.getName());
//        System.out.println(file_1.getParent());
//
//        System.out.println(file_1.getPath());
//        System.out.println(file_1.getAbsolutePath());
//        System.out.println(file_1.getParentFile());
    }

    public static Boolean HtmlCovertPdf(String inputFile,OutputStream outputStream) throws FileNotFoundException {
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        try {
            ITextRenderer renderer = new ITextRenderer();
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont(path+"\\static\\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            String url = new File(inputFile).toURI().toURL().toString();
            renderer.setDocument(url);
            renderer.layout();
            renderer.createPDF(outputStream);//此處輸出到respones
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            System.out.println("bb");
        }
    }
           

第二種 把檔案轉成字元流輸出到頁面,也是通過HttpServletResponse 的輸出流輸出到頁面。

@RequestMapping("/word2Pdf")
    public void word2Pdf(HttpServletResponse response) {
//        String fileName = "企業基本情況登記表.pdf";
        String wordPath ="D://1.doc";
//        File file_1 = new File(wordPath);
//        String fileFullName=  file_1.getName();
//        String fileType  =  fileFullName.substring(fileFullName.lastIndexOf(".")+1,fileFullName.length());
//        String fileName  =  fileFullName.substring(0,fileFullName.lastIndexOf("."));
        OutputStream outputStream = null;
        try {
            // 防止中文亂碼
//            fileName = URLEncoder.encode(fileName+".pdf", "UTF-8");
String downloadFileName = new String(fileName+".pdf".getBytes(), "ISO-8859-1");//檔案名中文亂碼
//            response.reset();
//            response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
//            response.setContentType("application/octet-stream;charset=UTF-8");
//            outputStream = new BufferedOutputStream(response.getOutputStream());
            //生成pdf檔案
            String pdf = ActiveWord2Pdf.word2Pdf(outputStream,wordPath);//檔案的路徑D://1.pdf
            log.info("已經生成:"+pdf);
            File file = new File(pdf);
            String fileFullName=  file.getName();
            log.info("檔案名:"+fileFullName);
            String fileName  = fileFullName;
            InputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[fis.available()];//擷取到檔案流
            fis.read(buffer);//檔案流放入到字元流中
            fis.close();
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);//寫出到頁面
            toClient.flush();
            toClient.close();
       }catch (Exception e){
            log.error("pdf異常:"+e);
        }
        finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

//        return R.ok();
    }
           

uitls

public static  String word2Pdf(OutputStream outputStream,String wordPath) throws Exception {
//        String wordPath ="D://1.doc";
        File file_1 = new File(wordPath);
        String fileFullName=  file_1.getName();
        String fileType  =  fileFullName.substring(fileFullName.lastIndexOf(".")+1,fileFullName.length());
        String fileName  =  fileFullName.substring(0,fileFullName.lastIndexOf("."));
        String filePath  =  file_1.getParent();
        String html = filePath+fileName+".html";
        Word2PdfUtil.docToHtml(wordPath,html);
        String pdf = filePath+fileName+".pdf";
        Word2PdfUtil.HtmlCovertPdf(html,pdf);
        return pdf;
}
           

繼續閱讀