第一种写法,使用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() {//生成pdfDocument 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响应头告诉浏览器下载文件名 Filenameresponse.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.totalif (total == null || total == undefined || parseInt(total) <= 0) {this.$alert('没有数据可导出')}this.$confirm('确定导出结果列表中的'+ total +'个pdf文件吗?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {this.exportLoading = truedownload(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 = urlconst fileName = parseTime(new Date()) + '-' + name + '.' + suffixlink.setAttribute('download', fileName)document.body.appendChild(link)link.click()document.body.removeChild(link)
}

生成pdf文件并打包zip下载相关推荐

  1. Java使用itextpdf生成PDF文件,用浏览器下载

    浏览器下载生成PDF文件 1.引入jar包 <dependency><groupId>com.itextpdf</groupId><artifactId> ...

  2. 批量下载,多文件压缩打包zip下载

    0.写在前面的话 图片批量下载,要求下载时集成为一个压缩包进行下载.从昨天下午折腾到现在,踩坑踩得莫名其妙,还是来唠唠,给自己留个印象的同时,也希望给需要用到这个方法的人带来一些帮助. 1.先叨叨IO ...

  3. 前端生成PDF 文件教程+在线demo案例

    个人博客导航页(点击右侧链接即可打开个人博客):大牛带你入门技术栈 PDF 简介 PDF 全称Portable Document Format (PDF)(便携文档格式),该格式的显示与操作系统.分辨 ...

  4. JQuery插件秀:生成PDF文件(文本+上传图片+电子签名)

    前言 需求如下:根据 docx 模板形成页面,让用户直接填写相关信息,在线生成 PDF 文件,无需用户下载 docx 模板填完信息再转为 PDF. 填写信息包括普通文本.上传图片.在线电子签名. 方案 ...

  5. Java使用itext生成PDF 然后将多个PDF打包zip下载

    先上pom依赖 用于生成pdf文件 <!--pdf start--><dependency><groupId>com.itextpdf</groupId> ...

  6. 通过url地址批量打包zip下载文件

    通过url地址批量打包zip下载文件 controller @ApiOperation("通过下载url批量打包zip下载")@PostMapping("batchDow ...

  7. jsPDF生成PDF文件,文件不全问题,后台进行文件下载,前台不下载

    我是前端使用jsPDF进行生成PDF文件,使用Base64进行加密,解密:后台进行文件流下载 1.前端使用jsPDF和html2canvas进行生成PDF文件(当然有这同样的毛病,生成时候有滚动条的情 ...

  8. 前端实现生成pdf文件并下载

    前端实现生成pdf文件并下载 思路 下载依赖 使用方式 备注 参考 思路 通过 html2canvas 将 HTML 页面转换成图片,然后再通过 jspdf 将图片的 base64 生成为 pdf 文 ...

  9. java导出pdf文件并下载_java根据模板生成pdf文件并导出

    1.首先需要依赖包:itext的jar包,我是maven项目,所以附上maven依赖 [html] view plain copy com.itextpdf itextpdf 5.5.10 [html ...

最新文章

  1. c语言加法减法乘法,一元多项式的加法减法乘法c语言描述线性表应用
  2. python 没反应 生成exe_通过 pyinstaller 将 python 脚本打包成可执行程序!
  3. 怎样在IDEA上将WebService接口打包部署到服务器
  4. 判断一个字符串是否另一个字符串的右移后的
  5. linux内核 panic,linux 内核 panic
  6. MFC工作笔记0009---VC++中 PostMessage和SendMessage的区别
  7. java扫描器创建,java – 如何创建条码扫描器(Android)?
  8. 144个城市坐标Python程序
  9. bch纠错码 码长8_浅析BCH码的编码方法.docx
  10. HP WebInspect 软件 简介
  11. 卸载系统的dhcp服务器,dhcp服务器释放ip地址
  12. 自制MyEclipse豆沙绿主题
  13. 嵌入式STM32深入之RTOS编程
  14. 初中数学抽象教学的案例_初中数学教学案例分析论文2篇
  15. 腾讯游戏助手运行闪退日志查看
  16. 创业者手记:我所犯的那些入门错误
  17. 游戏遇上区块链,从试探到联盟。
  18. 蝙蝠侠:黑暗骑士崛起 离线版(含数据包) v1.1.1
  19. Web安全:文件包含漏洞测试(防止 黑客利用此漏洞.)
  20. 把条件写在 join on 后面和写到where后面的区别

热门文章

  1. PDF软件哪个好?一定要知道这几款
  2. 中断一 中断向量表跳来跳去跳到C
  3. CAS单点登录(一):启动CAS认证中心服务
  4. 农村污水处理系统方案
  5. 认沽期权和认购期权认沽期权初识投资小工具分享
  6. 2015 读书笔记--告诉我你怎样去生活
  7. 麻了,都是科班出身的,学弟月薪却是我的3倍。
  8. JS给table动态添加行和列
  9. PowerPoint中插入并控制Flash播放
  10. HTTP协议简析《图解http》