实现文件pdf打包上传下载

// pdf 打包下载
    public void downloadWaterPack(@PathVariable String year, @PathVariable Long id,
                                                   HttpServletResponse response,
                                                   HttpServletRequest request,
                                                   ModelMap modelMap) throws Exception {

        String dirNoData = RuoYiConfig.getUploadPath() + "/noData";//获取上传路径
        File dirNoDataFile = new File(dirNoData);//创建文件夹对象
        if (!dirNoDataFile.exists()) {
            dirNoDataFile.mkdirs();//当文件夹不存在创建文件夹
        }
        String fileNoDataAbs = dirNoDataFile + "/" + "暂无数据.txt";//获取文件路径
        File fileNoData = new File(fileNoDataAbs);//根据文件路径创建文件对象
        if (!fileNoData.exists()) {
            fileNoData.createNewFile();//当文件不存在创建文件
        }
        if (id == -1) {
            downloadNoData(response, fileNoDataAbs);//没有水权证下载空压缩包
            return;
        }
        NyysFarmer farmer = new NyysFarmer();//创建用水农户对象
        farmer.setDeptId(id);//获取部门id
        farmer.getParams().put("year", year);//获取农户参数得到年份
        String uploadDir = RuoYiConfig.getUploadPath() + "/quotaPdf/" + id + "/" + year + "/";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        List<NyysFarmerExt> list = nyysFarmerService.selectNyysFarmerQuotaList(farmer);  // 先查农户信息
        if (list.size() == 0) {
            downloadNoData(response, fileNoDataAbs);
            return;
        }
        List<String> uploadFileNameAbsList = new ArrayList<>(); // 水权证文件全名(目录+文件名)集合(压缩时用到)
        for (NyysFarmerExt nyysFarmerExt : list) { // 把水权证写到硬盘上
            nyysFarmerExt.setTotalUnit("");//获取用水单位
            nyysFarmerExt.setYear(year);//获取年份
            String fileName = nyysFarmerExt.getYear() + "-用水权证-" + nyysFarmerExt.getFarmerName() + "-" + nyysFarmerExt.getFarmerId() + ".pdf"; // 防止重名 文件名加上农户id
            String uploadFileNameAbs = uploadDir + fileName; // 水权证文件全名(目录+文件名)
            uploadFileNameAbsList.add(uploadFileNameAbs);//添加文件名
            FileOutputStream fos = new FileOutputStream(uploadFileNameAbs);//输出文件
            drawPdf(nyysFarmerExt, fos);//绘画pdf文件
        }

        // 打包成zip文件
        SysDept sysDept = deptService.selectDeptById(id);
        String zipName = year + "-用水权证-" + sysDept.getDeptName() + "-打包.zip";
        String zipDir = RuoYiConfig.getUploadPath() + "/quotaZip/" + id + "/" + year + "/";
        File zipDirFileObj = new File(zipDir);
        if (!zipDirFileObj.exists()) {
            zipDirFileObj.mkdirs();
        }
        String zipFileNameAbs = zipDir + zipName;
        ZipOutputStream zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileNameAbs)));

        BufferedInputStream bis = null;
        for (String pdfFileNameAbs : uploadFileNameAbsList) {
            File fileTemp = new File(pdfFileNameAbs);
            ZipEntry zEntry = new ZipEntry(fileTemp.getName());
            zipOutput.putNextEntry(zEntry);
            bis = new BufferedInputStream(new FileInputStream(fileTemp));
            byte[] buffer = new byte[1024];
            int read = 0;
            while((read = bis.read(buffer)) != -1){
                zipOutput.write(buffer, 0, read);
            }
        }
        bis.close();
        zipOutput.close();

        // 下载
        ServletOutputStream sos = response.getOutputStream();
        FileInputStream in = new FileInputStream(zipFileNameAbs);
        response.setHeader("Content-Type","application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipName, "UTF-8"));
        byte[] buffer2 = new byte[1024];
        int read2 = 0;
        while((read2 = in.read(buffer2)) != -1){
            sos.write(buffer2, 0, read2);
        }
        File zipFile = new File(zipDir + zipName);
        if (zipFile.exists()) {
            zipFile.delete();
        }
        in.close();
    }
  // 下载空文件
    private void downloadNoData(HttpServletResponse response, String fileNameAbs) throws Exception {
        ServletOutputStream sos = response.getOutputStream();
        FileInputStream in = new FileInputStream(fileNameAbs);
        response.setHeader("Content-Type","application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("暂无数据.txt", "UTF-8"));
        int len = 0;
        while((len = in.read()) != -1){
            sos.write(len);
        }
        sos.close();
        in.close();
    }
 /**
     * 输出到http响应流
     */
    void toHttpServletResponse(HttpServletResponse response, NyysFarmerExt farmerData) throws Exception {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;fileName=" + farmerData.getYear() + "-" + URLEncoder.encode("用水权证", StandardCharsets.UTF_8.name()) + "-" + URLEncoder.encode(farmerData.getFarmerName(), StandardCharsets.UTF_8.name()) + ".pdf");
        ServletOutputStream outputStream = response.getOutputStream();
        // 绘制证书
        drawPdf(farmerData, outputStream);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Python的PyPDF2库读取PDF文件,并使用Pillow库将PDF文件中的每一页转换为JPEG图像。然后,使用ZipFile库将所有JPEG图像打包为一个zip文件并提供下载链接。 以下是具体的步骤: 1. 安装必要的库: ``` pip install streamlit PyPDF2 Pillow ``` 2. 在Streamlit应用程序中添加以下代码: ```python import streamlit as st from PyPDF2 import PdfFileReader from PIL import Image from zipfile import ZipFile import io # 用于将PDF文件中的每一页转换为JPEG图像的函数 def pdf_to_jpeg(pdf_file): with open(pdf_file, 'rb') as f: pdf = PdfFileReader(f) for page in range(pdf.getNumPages()): img = Image.open(io.BytesIO(pdf.getPage(page).render())) yield img # Streamlit应用程序的主要部分 def main(): st.title("PDF转JPEG") # 上传PDF文件 uploaded_file = st.file_uploader("上传PDF文件", type="pdf") if uploaded_file is not None: # 将PDF文件中的每一页转换为JPEG图像 images = list(pdf_to_jpeg(uploaded_file)) # 打包所有JPEG图像到zip文件中 with ZipFile("images.zip", "w") as zf: for i, img in enumerate(images): img.save(f"page_{i+1}.jpg") zf.write(f"page_{i+1}.jpg") # 提供zip文件下载链接 with open("images.zip", "rb") as f: bytes_data = f.read() st.download_button("下载JPEG图像", data=bytes_data, file_name="images.zip", mime="application/zip") ``` 代码的主要部分是 `pdf_to_jpeg` 和 `main` 函数。 `pdf_to_jpeg` 函数读取传递的PDF文件并将每个页面转换为JPEG图像。 `main` 函数是Streamlit应用程序的主要部分,它提供了一个上传PDF文件的界面,然后将PDF文件中的每一页转换为JPEG图像,并将所有图像打包到zip文件中。最后,它提供了一个下载按钮,让用户下载打包的zip文件。 注意,为了将生成的JPEG图像打包到zip文件中,我们使用了Python的内置 `zipfile` 库。在下载zip文件时,我们使用了Streamlit的 `download_button` 函数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值