生成pdf文件并打包zip下载

简介: 使用itextpdf生成pdf文件,使用ant的org.apache.tools.zip生成zip包,并下载

第一种写法,使用org.apache.tools.zip,具体流程:
1、逐个生成pdf文件
2、打包zip
3、下载

第二种写法,使用java.util.zip,这种写法没成功。
1、使用pdf文件流进行打包
2、下载
这里介绍第一种。

一、导入相应的依赖包

<!--itext pdf-->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.2</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>
<!--ant zip-->
<dependency>
    <groupId>org.apache.ant</groupId>
    <artifactId>ant</artifactId>
    <version>1.10.12</version>
</dependency>

二、生成pdf 和 zip 文件

PdfUtil.java 关键代码

/**
* 创建document对象
*/
public static Document createDocument() {
   
   //生成pdf
   Document document = new Document();
   // 页面大小
   Rectangle rectangle = new Rectangle(PageSize.A4);
   // 页面背景颜色
   rectangle.setBackgroundColor(BaseColor.WHITE);
   document.setPageSize(rectangle);
   // 页边距 左,右,上,下
   document.setMargins(20, 20, 20, 20);
   return document;
}

/**
 * @param text 段落内容
 * @return
 */
public static Paragraph createParagraph(String text, Font font) {
   
   Paragraph elements = new Paragraph(text, font);
   elements.setSpacingBefore(5);
   elements.setSpacingAfter(5);
   elements.setSpacingAfter(spacing);
   return elements;
}

/**
 * 创建默认列宽,指定列数、水平(居中、右、左)的表格
 *
 * @param colNumber
 * @param align
 * @return
 */
public static PdfPTable createTable(int colNumber, int align) {
   
   PdfPTable table = new PdfPTable(colNumber);
   try {
   
      table.setTotalWidth(maxWidth);
      table.setLockedWidth(true);
      table.setHorizontalAlignment(align);
      table.getDefaultCell().setBorder(1);
   } catch (Exception e) {
   
      e.printStackTrace();
   }
   return table;
}

/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并)
*
* @param value
* @param font
* @param align
* @param colspan
* @return
*/
public static PdfPCell createCell(String value, Font font, int align, int colspan) {
   
   PdfPCell cell = new PdfPCell();
   cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
   cell.setHorizontalAlignment(align);
   cell.setColspan(colspan);
   cell.setPhrase(new Phrase(value, font));
   cell.setMinimumHeight(20f);
   return cell;
}

业务代码

/**
* 生成单个pdf文件,并返回文件对象
* @param dto 需要生成pdf的数据对象
* @return UploadResult 自定义文件对象
*/
private UploadResult generatePDF(ActivityApplyLogDto dto) {
   
     Document document = null;
     try {
   
         document = PdfUtil.createDocument();

        // 这里是返回一个pdf的存放地址和文件名,可自定义,如下
        // UploadResult rs = new UploadResult();
         // rs.setPath(filePath);
        // rs.setName(fileName);            
           UploadResult fileUploadResult = fileService.getFilePath("pdf");
         FileOutputStream fos = new FileOutputStream(fileUploadResult.getPath());
         PdfWriter.getInstance(document, fos);
         document.open();

         // 字体定义
         BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
         Font titlefont = new Font(bfChinese, 16, Font.BOLD);
         Font textfont = new Font(bfChinese, 10, Font.NORMAL);

         // 生成居中标题
         Paragraph title = PdfUtil.createParagraph("活动报名信息\n", titlefont);
         title.setAlignment(Element.ALIGN_CENTER);
         document.add(title);
         document.add(new Paragraph("   "));

         PdfPTable table = PdfUtil.createTable(6, Element.ALIGN_CENTER);

         BizUser user = dto.getUser();
         BizActivity activity = dto.getActivity();
         table.addCell(PdfUtil.createCell("关联活动名称", textfont, Element.ALIGN_LEFT, 1));
         table.addCell(PdfUtil.createCell(activity.getName(), textfont, Element.ALIGN_LEFT, 2));
         table.addCell(PdfUtil.createCell("姓名", textfont, Element.ALIGN_LEFT, 1));
         table.addCell(PdfUtil.createCell(user.getName(), textfont, Element.ALIGN_LEFT, 2));

         table.addCell(PdfUtil.createCell("手机号码", textfont, Element.ALIGN_LEFT, 1));
         table.addCell(PdfUtil.createCell(user.getPhone(), textfont, Element.ALIGN_LEFT, 2));            
         table.addCell(PdfUtil.createCell("性别", textfont, Element.ALIGN_LEFT, 1));
         table.addCell(PdfUtil.createCell(user.getGender(), textfont, Element.ALIGN_LEFT, 2));

         table.addCell(PdfUtil.createCell("证件类型", textfont, Element.ALIGN_LEFT, 1));
         table.addCell(PdfUtil.createCell(user.getCardType(), textfont, Element.ALIGN_LEFT, 2));
         table.addCell(PdfUtil.createCell("证件号码", textfont, Element.ALIGN_LEFT, 1));
         table.addCell(PdfUtil.createCell(user.getCardNum(), textfont, Element.ALIGN_LEFT, 2));

         table.addCell(PdfUtil.createCell("报名状态", textfont, Element.ALIGN_LEFT, 1));
         table.addCell(PdfUtil.createCell(dto.getStatus(), textfont, Element.ALIGN_LEFT, 2));
         table.addCell(PdfUtil.createCell("报名时间", textfont, Element.ALIGN_LEFT, 1));
         table.addCell(PdfUtil.createCell(dto.getApplyTime(), textfont, Element.ALIGN_LEFT, 2));

         document.add(table);

         return fileUploadResult;
    }catch (Exception e) {
   
         throw new BadRequestException("生成失败");
    } finally {
   
         if (document != null) document.close();
    }
}

生成 zip 文件
ZipUtil.java 关键代码,参考了https://www.cnblogs.com/alphajuns/p/12442315.html的写法

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

public class ZipUtil {
   
    public static final String SYS_TEM_DIR = System.getProperty("java.io.tmpdir") + File.separator;

    /**
     * 这里先不关闭流,否则会报异常
     * @param zip      压缩目的地址
     * @param srcFiles 压缩的源文件     
     */
    public static String zipFile(String zip, List<File> srcFiles) throws Exception{
   
        String path = SYS_TEM_DIR + zip;
        FileOutputStream fos = new FileOutputStream(path);
        ZipOutputStream out = new ZipOutputStream(fos);
        out.setEncoding("GBK");
        for (File _f : srcFiles) {
   
            handlerFile(out, _f);
        }
        return path;
    }

    /**
     * 处理压缩
     * @param out 目标文件流
     * @param srcFile 源文件信息
     */
    private static void handlerFile(ZipOutputStream out, File srcFile) throws IOException {
   
        InputStream in = new FileInputStream(srcFile);
        out.putNextEntry(new ZipEntry(srcFile.getName()));
        int len = 0;
        byte[] _byte = new byte[1024];
        while ((len = in.read(_byte)) > 0) {
   
            out.write(_byte, 0, len);
        }
        in.close();
        out.closeEntry();
    }
}

三、下载

后台代码

public void downloadPDF(List<BizActivityApplyLogDto> all, HttpServletResponse response) throws Exception {
   
   List<File> fileList = new ArrayList<>();
   for (BizActivityApplyLogDto dto : all) {
   
       UploadResult rs = generatePDF(dto);
       fileList.add(new File(rs.getPath()));
   }
   //zip压缩包名称
   String zipFileName = "活动报名信息.zip";
   response.setCharacterEncoding("UTF-8");
   response.setContentType("application/octet-stream");
   String path = ZipUtil.zipFile(zipFileName, fileList);

   FileInputStream fileInputStream = new FileInputStream(path);
   //设置Http响应头告诉浏览器下载文件名 Filename
   response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(zipFileName, "UTF-8"));
   OutputStream outputStream = response.getOutputStream();
   byte[] bytes = new byte[2048];
   int len = 0;
   while ((len = fileInputStream.read(bytes)) > 0) {
   
       outputStream.write(bytes, 0, len);
   }
   outputStream.flush();
   fileInputStream.close();
   outputStream.close();
}

前端代码

//点击导出按钮
<el-button type="primary" icon="el-icon-download" size="mini" :loading="exportLoading" @click="downloadPDF">导出PDF</el-button>

downloadPDF(){
   
  let total = this.page.total
  if (total == null || total == undefined || parseInt(total) <= 0) {
   
    this.$alert('没有数据可导出')
  }
  this.$confirm('确定导出结果列表中的'+ total +'个pdf文件吗?', '提示', {
   
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
   
    this.exportLoading = true
    download(this.baseUrl + '/downloadPDF', this.getParams()).then(res => {
   
      downloadFile(res, this.title + '数据', 'zip')
      this.exportLoading = false
    }).catch(()=>{
   
      this.exportLoading = true
    })
  })
}

// download 使用了axios 和 qs,
export function download(url, params) {
   
  return request({
   
    url: url + '?' + qs.stringify(params, {
    indices: false }),
    method: 'get',
    responseType: 'blob'
  })
}

// 下载文件
export function downloadFile(obj, name, suffix) {
   
  const url = window.URL.createObjectURL(new Blob([obj]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  const fileName = parseTime(new Date()) + '-' + name + '.' + suffix
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
相关文章
|
存储 JSON API
如何将 Swagger 文档导出为 PDF 文件
你会发现自己可能需要将 Swagger 文档导出为 PDF 或文件,以便于共享和存档。在这篇博文中,我们将指导你完成将 Swagger 文档导出为 PDF 格式的过程。
|
10月前
|
C#
【PDF提取内容改名】批量提取PDF指定区域内容重命名PDF文件,PDF自动提取内容命名的方案和详细步骤
本工具可批量提取PDF中的合同编号、日期、发票号等关键信息,支持PDF自定义区域提取并自动重命名文件,适用于合同管理、发票处理、文档归档和数据录入场景。基于iTextSharp库实现,提供完整代码示例与百度、腾讯网盘下载链接,助力高效处理PDF文档。
1320 40
|
11月前
|
人工智能 文字识别 自然语言处理
熊猫 OCR 识别软件下载,支持截图 OCR、PDF 识别、多语言翻译的免费全能工具,熊猫OCR识别
本文介绍了几款实用的图文识别软件,包括熊猫OCR、Umi-OCR和天若OCR_本地版。熊猫OCR功能强大,支持多窗口操作、AI找图找色、OCR识别等;Umi-OCR免费且高效,具备截图OCR、批量处理等功能;天若OCR界面简洁,适合快速文字识别。文章还提供了下载链接及软件特点、界面展示等内容,便于用户根据需求选择合适的工具。
1340 36
|
10月前
|
编译器 Python
如何利用Python批量重命名PDF文件
本文介绍了如何使用Python提取PDF内容并用于文件重命名。通过安装Python环境、PyCharm编译器及Jupyter Notebook,结合tabula库实现PDF数据读取与处理,并提供代码示例与参考文献。
|
人工智能 算法 安全
使用CodeBuddy实现批量转换PPT、Excel、Word为PDF文件工具
通过 CodeBuddy 实现本地批量转换工具,让复杂的文档处理需求转化为 “需求描述→代码生成→一键运行” 的极简流程,真正实现 “技术为效率服务” 的目标。感兴趣的快来体验下把
824 10
|
11月前
|
存储 安全 算法
Java 集合面试题 PDF 下载及高频考点解析
本文围绕Java集合面试题展开,详细解析了集合框架的基本概念、常见集合类的特点与应用场景。内容涵盖`ArrayList`与`LinkedList`的区别、`HashSet`与`TreeSet`的对比、`HashMap`与`ConcurrentHashMap`的线程安全性分析等。通过技术方案与应用实例,帮助读者深入理解集合类的特性和使用场景,提升解决实际开发问题的能力。文末附带资源链接,供进一步学习参考。
290 4
|
11月前
|
数据采集 存储 API
Python爬虫结合API接口批量获取PDF文件
Python爬虫结合API接口批量获取PDF文件
|
文字识别 Serverless 开发工具
【全自动改PDF名】批量OCR识别提取PDF自定义指定区域内容保存到 Excel 以及根据PDF文件内容的标题来批量重命名
学校和教育机构常需处理成绩单、报名表等PDF文件。通过OCR技术,可自动提取学生信息并录入Excel,便于统计分析和存档管理。本文介绍使用阿里云服务实现批量OCR识别、内容提取、重命名及导出表格的完整步骤,包括开通相关服务、编写代码、部署函数计算和设置自动化触发器等。提供Python示例代码和详细操作指南,帮助用户高效处理PDF文件。 链接: - 百度网盘:[链接](https://pan.baidu.com/s/1mWsg7mDZq2pZ8xdKzdn5Hg?pwd=8866) - 腾讯网盘:[链接](https://share.weiyun.com/a77jklXK)
2408 5
|
人工智能 编解码 文字识别
OCRmyPDF:16.5K Star!快速将 PDF 文件转换为可搜索、可复制的文档的命令行工具
OCRmyPDF 是一款开源命令行工具,专为将扫描的 PDF 文件转换为可搜索、可复制的文档。支持多语言、图像优化和多核处理。
1475 17
OCRmyPDF:16.5K Star!快速将 PDF 文件转换为可搜索、可复制的文档的命令行工具
|
机器学习/深度学习 人工智能 文字识别
Zerox:AI驱动的万能OCR工具,精准识别复杂布局并输出Markdown格式,支持PDF、DOCX、图片等多种文件格式
Zerox 是一款开源的本地化高精度OCR工具,基于GPT-4o-mini模型,支持PDF、DOCX、图片等多种格式文件,能够零样本识别复杂布局文档,输出Markdown格式结果。
1700 4
Zerox:AI驱动的万能OCR工具,精准识别复杂布局并输出Markdown格式,支持PDF、DOCX、图片等多种文件格式

热门文章

最新文章