天天看点

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;
}
           

继续阅读