批量生成pdf文件并下载

controller层:

public String exportBatchMerchantInspection( HttpServletRequest request, HttpServletResponse response,MerchantInspection merchantInspection)
        throws Exception {
    String downloadName = "巡检单.zip";
    try {
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(downloadName, "UTF-8"));
        response.setContentType("application/zip");// 定义输出类型

    } catch (UnsupportedEncodingException e) {
        throw new Exception("下载文件名编码时出现错误.", e);
    }
    if (null == merchantInspection){
        merchantInspection = new MerchantInspection();
        merchantInspection.setStatus(MerchantInspectionStatusEnum.SUBMIT.getCode());
    }else {
        merchantInspection.setStatus(MerchantInspectionStatusEnum.SUBMIT.getCode());
    }

    List<MerchantInspection> merchantInspections = merchantInspectionService
            .queryMerchantInspectionList(merchantInspection);
    if (null != merchantInspections && merchantInspections.size() > 0) {
        for (int i = 0; i <merchantInspections.size() ; i++) {
            MerchantInspection merchantInspectionFind = merchantInspections.get(i);
            HttpUtils.downLoadByUrl(merchantInspectionFind.getInspectionPic(),merchantInspectionFind.getMno()+"_"+i+".pdf",pdfTemplatePath);//将远程文件下载到本地,并放在同一个目录下

        }
    }
    //压缩文件
    ZipUtil.compressBegin(zipTemplatePath+downloadName, pdfTemplatePath);//将放在本地文件下载下来,并且压缩称zip文件
    DownloadFileUtil.getInstance().downloadExcelTemplate(zipTemplatePath, downloadName,
            "商户巡检导入模板.zip", response);//下载zip文件
    ZipUtil.delFolder(pdfTemplatePath);//删除临时目录下的文件
    ZipUtil.delFolder(zipTemplatePath);//删除压缩文件
    return null;
}

 

httpUtils文件:,针对远程的路径文件文件进行下载,并且保存到本地服务器上,创建一个临时文件;

public static void  downLoadByUrl(String urlStr,String fileName,String savePath) throws IOException{
   URL url = new URL(urlStr);
   HttpURLConnection conn = (HttpURLConnection)url.openConnection();
   //设置超时间为3秒
   conn.setConnectTimeout(5*1000);
   //防止屏蔽程序抓取而返回403错误
   conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
   //得到输入流
   InputStream inputStream = conn.getInputStream();
   //获取自己数组
   byte[] getData = readInputStream(inputStream);
   //文件保存位置
   File saveDir = new File(savePath);
   if(!saveDir.exists()){
      saveDir.mkdir();
   }
   File file = new File(saveDir+File.separator+fileName);
   FileOutputStream fos = new FileOutputStream(file);
   fos.write(getData);
   if(fos!=null){
      fos.close();
   }
   if(inputStream!=null){
      inputStream.close();
   }
   System.out.println("info:"+url+" download success");

}

第三步

/**
 * 压缩文件工具类
 * @author sun.kai
 * 2016年8月14日
 */
public class ZipUtil {
    static final int BUFFER = 8192;

    private static File zipFile;
    private static String pdfTemplatePath  = "/Users/huangxiaogen/work/pdftemp";
    private static String zipTemplatePath  = "/Users/huangxiaogen/work/ziptemp/";
    
    public static void main(String[] args) {
       /*String sourceFilePath = "/Users/huangxiaogen/work/temp2/";
      String zipFilePath = "/Users/huangxiaogen/work/1234.zip";
        try {
            HttpUtils.downLoadByUrl("http://172.16.154.131:9999/0/2/32MDJhYjIyYWYzRlBpVTJheDIwMTlfMDhfMDlfMDlfMzVfOGNhNDUwMTA2OWYxNDlkMWE3NTJhODhmYWRiMmMyYzUyYWd0ZXN0XzEyYWIx.pdf","12454.pdf",sourceFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
       compressBegin(zipFilePath, sourceFilePath);
        delFolder(zipTemplatePath);*/

   }

    /**
     * 压缩单个或多文件方法
     * @param zipPath 压缩后的文件路径
     * @param srcPathName 要压缩的文件路径
     * 参数srcPathName也可以定义成数组形式,需调用方把参数封装到数组中传过来即可
     */
    public static void compressBegin(String zipPath,String... srcPathName) {
        //压缩后的文件对象
        zipFile = new File(zipPath);
        try {
            //创建写出流操作
            FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
            CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,new CRC32());
            ZipOutputStream out = new ZipOutputStream(cos);
            for(String srcPath:srcPathName){
                //创建需要压缩的文件对象
                File file = new File(srcPath);
                if (!file.exists()){
                    throw new RuntimeException(srcPath + "不存在!");
                }
                /*
                 * (1)如果在zip压缩文件中不需要一级文件目录,定义String basedir = "";
                 * 下面的compress方法中当判断文件file是目录后不需要加上basedir = basedir + file.getName() + File.separator;
                 * (2)如果只是想在压缩后的zip文件里包含一级文件目录,不包含二级以下目录,
                 * 直接在这定义String basedir = file.getName() + File.separator;
                 * 下面的compress方法中当判断文件file是目录后不需要加上basedir = basedir + file.getName() + File.separator;
                 * (3)如果想压缩后的zip文件里包含一级文件目录,也包含二级以下目录,即zip文件里的目录结构和原文件一样
                 * 在此定义String basedir = "";
                 * 下面的compress方法中当判断文件file是目录后需要加上basedir = basedir + file.getName() + File.separator;
                 */
                //String basedir = file.getName() + File.separator;
                String basedir = "";
                compress(file, out, basedir);
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void compress(File file, ZipOutputStream out, String basedir) {
        /* 
         * 判断是目录还是文件 
         */
        if (file.isDirectory()) {
           basedir += file.getName() + File.separator;
            compressDirectory(file, out, basedir);
        } else {
            System.out.println("压缩:" + basedir + file.getName());
            compressFile(file, out, basedir);
        }
    }

    /**
     * 压缩一个目录
     */
    private static void compressDirectory(File dir, ZipOutputStream out, String basedir) {
        if (!dir.exists()){
            return;
        }
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            /* 递归 */
            compress(files[i], out, basedir);
        }
    }

    /** 
     * 压缩一个文件 
     */
    private static void compressFile(File file, ZipOutputStream out, String basedir) {
        if (!file.exists()) {
            return;
        }
        try {
            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(file));
            //创建Zip实体,并添加进压缩包
            LogUtils.info("文件的名称是"+file.getName());

            ZipEntry entry = new ZipEntry(basedir + file.getName());
            out.putNextEntry(entry);
            //读取待压缩的文件并写进压缩包里
            int count;
            byte data[] = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            bis.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 压缩一个文件
     */
    private static void compressFile2(File file, ZipOutputStream out, String basedir) {
        if (!file.exists()) {
            return;
        }


        try {
            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(file));
            //创建Zip实体,并添加进压缩包
            LogUtils.info("文件的名称是"+file.getName());

            ZipEntry entry = new ZipEntry(basedir + file.getName());
            out.putNextEntry(entry);
            //读取待压缩的文件并写进压缩包里
            int count;
            byte data[] = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            bis.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    
    /**
     * 解压缩 
     * @param sourceFile 要解压缩的文件的路径
     * @param destDir 解压缩后的目录路径
     * @throws Exception
     */
    public static void deCompress(String sourceFile,String destDir) throws Exception{  
       //创建需要解压缩的文件对象
       File file = new File(sourceFile);
        if (!file.exists()){
           throw new RuntimeException(sourceFile + "不存在!");
        }
        //创建解压缩的文件目录对象
       File destDiretory  = new File(destDir);
        if(!destDiretory.exists()){
           destDiretory.mkdirs();
        }
       /*
         * 保证文件夹路径最后是"/"或者"\"
         * charAt()返回指定索引位置的char值
         */
        char lastChar = destDir.charAt(destDir.length()-1);
        if(lastChar!='/'&&lastChar!='\\'){
           //在最后加上分隔符
            destDir += File.separator;
        }
        unzip(sourceFile, destDir);
    }
    
    /**
     * 解压方法
     * 需要ant.jar
     */
    public static void unzip(String sourceZip,String destDir) throws Exception{
        try{
            Project p = new Project();
            Expand e = new Expand();
            e.setProject(p);
            e.setSrc(new File(sourceZip));
            e.setOverwrite(false);
            e.setDest(new File(destDir));
            e.execute();
        }catch(Exception e){
            throw e;
        }
    }




    //删除文件夹
    //param folderPath 文件夹完整绝对路径
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            //java.io.File myFilePath = new java.io.File(filePath);
          //  myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除指定文件夹下所有文件
    //param path 文件夹完整绝对路径
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值