JAVA导出PDF借助 iText

pom先引入两个jar包

 <dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>${itextpdf.version}</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>${asian.version}</version></dependency>

导出逻辑

@SneakyThrows@Overridepublic  ResponseEntity<InputStreamResource>   exportTradeAckPdfFile(QueryTradeAckDetailReqDto queryTradeAckDetailDto){FileOutputStream fileOutputStream = null;PdfWriter writer=null;File pdfFile=null;Document tradeAckPdfDocument=null;List<File> files = new ArrayList<>();InputStreamResource inputStreamResource=null;String zipFilePath=null;String zipFileName="交易确认单"+ DateUtils.getDateyyyyMMdd()+".zip";try{QueryTradeAckDetailReqBo reqBo= AcctUserInfoReq.Req.getReqBo(queryTradeAckDetailDto);//获取筛选条件内所有客户交易账号List<QueryCustNoRespBo> queryCustNoRespBoList= sAcktradeblotterMapper.queryCustNoListByChannelCode(reqBo);for (QueryCustNoRespBo custNoRespBo:queryCustNoRespBoList) {QueryAccountUserTradeAckDetailReqBo queryAccountUserTradeAckDetailReqBo=new QueryAccountUserTradeAckDetailReqBo();queryAccountUserTradeAckDetailReqBo.setAckStartDate(reqBo.getAckStartDate());queryAccountUserTradeAckDetailReqBo.setAckEndDate(reqBo.getAckEndDate());queryAccountUserTradeAckDetailReqBo.setChannelCodes(reqBo.getChannelCodes());queryAccountUserTradeAckDetailReqBo.setCustNo(custNoRespBo.getCustNo());//单个客户信息QueryAccountUserInfoRespBo queryAccountUserInfoRespBo=sAcktradeblotterMapper.queryAccountUserInfo(custNoRespBo.getCustNo());tradeAckPdfDocument=new Document();//pdfFile=new File(pathProperties.getFilePath());zipFilePath=pathProperties.getFilePath()+"/"+zipFileName;pdfFile=new File(pathProperties.getFilePath()+"/"+queryAccountUserInfoRespBo.getInvName()+custNoRespBo.getCustNo()+".pdf");//输出文件到服务器本地fileOutputStream = new FileOutputStream(pdfFile);writer = PdfWriter.getInstance(tradeAckPdfDocument, fileOutputStream);writer.setViewerPreferences(PdfWriter.PageModeUseThumbs);tradeAckPdfDocument.setPageSize(PageSize.A4);tradeAckPdfDocument.open();tradeAckPdfDocument.add(getPdfTitleParagraph("交易对账单"));//客户交易详情List<QueryAccountUserTradeDetailRespBo> queryAccountUserTradeDetailRespBoList=sAcktradeblotterMapper.queryAccountUserTradeDetail(queryAccountUserTradeAckDetailReqBo);tradeAckPdfDocument=addAccountUserTradeDetailToDocument(queryAccountUserTradeDetailRespBoList,tradeAckPdfDocument,reqBo);Paragraph titleParagraph = new Paragraph("    风险提示", getPdfTableTitleFont());tradeAckPdfDocument.add(titleParagraph);Paragraph firstParagraph = new Paragraph("             在线自助交易单据服务仅供客户查询及打印参考使用,不得伪造、篡改。投资者在本机构持有的基金份额及交易确", getPdfRowCellFont());tradeAckPdfDocument.add(firstParagraph);Paragraph secendParagraph = new Paragraph("    认结果以注册登记机构最终确认的结果为准。", getPdfRowCellFont());tradeAckPdfDocument.add(secendParagraph);              Paragraph fourthParagraph = new Paragraph("    快协助您解决。", getPdfRowCellFont());tradeAckPdfDocument.add(fourthParagraph);files.add(pdfFile);if(tradeAckPdfDocument.isOpen()){tradeAckPdfDocument.close();}writer.close();fileOutputStream.close();}inputStreamResource=addFileToZipPackage(files,zipFilePath);}catch (Exception e) {log.error("导出交易确认PDF表出错",e);}finally {return ResponseEntity.ok().header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS,"FileName",HttpHeaders.CONTENT_DISPOSITION).header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=" + zipFileName).header("FileName", zipFileName).contentType(MediaType.APPLICATION_OCTET_STREAM).body(inputStreamResource);}}private Document addAccountUserTradeDetailToDocument(List<QueryAccountUserTradeDetailRespBo> queryAccountUserTradeDetailRespBoList, Document document,QueryTradeAckDetailReqBo reqBo){try{document.add(getPdfTableTitleParagraph("    交易明细("+reqBo.getAckStartDate()+"-"+reqBo.getAckEndDate()+"申请数据明细)"));final List<String> acctUserInfoTradeDetailColumns =Collections.unmodifiableList( Arrays.asList( new String[]{"确认日期","基金名称","基金代码","业务类型","申请金额(元)","申请份额(份)","确认金额(元)","确认份额(份)","确认净值","手续费  (元)"} ) ) ;PdfPTable pdfTable =getPdfTable(10,496);for (String cellValue:acctUserInfoTradeDetailColumns) {pdfTable.addCell(getPdfHeadCell(cellValue));}for (QueryAccountUserTradeDetailRespBo rowValue:queryAccountUserTradeDetailRespBoList) {pdfTable.addCell(getPdfCell(rowValue.getAckDate()));pdfTable.addCell(getPdfCell(rowValue.getFundName()));pdfTable.addCell(getPdfCell(rowValue.getFundCode()));pdfTable.addCell(getPdfCell(rowValue.getApkType()));pdfTable.addCell(getPdfCenterCell(rowValue.getAppAmt()));pdfTable.addCell(getPdfCenterCell(rowValue.getAppBalance()));pdfTable.addCell(getPdfCenterCell(rowValue.getAckAmt()));pdfTable.addCell(getPdfCenterCell(rowValue.getAckBalance()));pdfTable.addCell(getPdfCenterCell(rowValue.getAckNav()));pdfTable.addCell(getPdfCenterCell(rowValue.getFee()));}document.add(pdfTable);}catch (Exception e){log.error("导出交易确认PDF表附加交易详情出错",e);}finally {return document;}}public static PdfPTable getPdfTable(int rowSize, int tableRowLength) throws Exception {float[] rowWidths=new float[rowSize];for(int i=0;i<rowSize;i++){rowWidths[i]=1f;}PdfPTable pdfTable = new PdfPTable(rowWidths);pdfTable.setLockedWidth(true);pdfTable.setTotalWidth(tableRowLength);pdfTable.setSpacingBefore(10); // 前间距pdfTable.setSpacingAfter(10); // 后间距return pdfTable;}

声明字体和创建一个列

 public static Font getPdfRowCellFont() throws Exception {BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);Font fontChinese = new Font(bfChinese, 10, Font.NORMAL);return fontChinese;}public static Paragraph getPdfTableTitleParagraph(String tableTitle) throws Exception {Paragraph titleParagraph=new Paragraph(tableTitle,getPdfTableTitleFont());titleParagraph.setAlignment(Element.ALIGN_LEFT);titleParagraph.setSpacingAfter(10f);titleParagraph.setSpacingBefore(10f);return titleParagraph;}public static Font getPdfTableTitleFont() throws Exception {BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);Font fontChinese = new Font(bfChinese, 14, Font.BOLD);return fontChinese;}public static Paragraph getPdfTitleParagraph(String pdfTitle) throws Exception {Paragraph titleParagraph=new Paragraph(pdfTitle,getPdfTitleFont());titleParagraph.setAlignment(Element.ALIGN_CENTER);titleParagraph.setSpacingAfter(10f);titleParagraph.setSpacingBefore(10f);return titleParagraph;}public static Font getPdfTitleFont() throws Exception {BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);Font fontChinese = new Font(bfChinese, 18, Font.BOLD);return fontChinese;}public static PdfPCell getPdfCell(String cellValue) throws Exception {PdfPCell pdfCell = new PdfPCell();Paragraph paragraph = new Paragraph(cellValue, getPdfRowCellFont());pdfCell.setMinimumHeight(30);//设置表格行高pdfCell.setUseAscender(true);pdfCell.setVerticalAlignment(pdfCell.ALIGN_MIDDLE);pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);pdfCell.setPhrase(paragraph);return pdfCell;}public static PdfPCell getPdfCenterCell(String cellValue) throws Exception {PdfPCell pdfCell = new PdfPCell();pdfCell.setMinimumHeight(30);//设置表格行高Paragraph paragraph = new Paragraph(cellValue, getPdfRowCellFont());pdfCell.setUseAscender(true);pdfCell.setVerticalAlignment(pdfCell.ALIGN_MIDDLE);pdfCell.setVerticalAlignment(Element.ALIGN_CENTER);pdfCell.setHorizontalAlignment(Element.ALIGN_RIGHT);pdfCell.setPhrase(paragraph);return pdfCell;}public static PdfPCell getPdfHeadCell(String cellValue) throws Exception {PdfPCell pdfCell = new PdfPCell();pdfCell.setMinimumHeight(30);//设置表格行高pdfCell.setUseAscender(true);pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);pdfCell.setVerticalAlignment(pdfCell.ALIGN_MIDDLE);Paragraph paragraph = new Paragraph(cellValue, getPdfRowCellFont());pdfCell.setPhrase(paragraph);return pdfCell;}

压缩文件

 private InputStreamResource addFileToZipPackage(List<File> pdfFile,String zipFilePath) throws IOException {ZipOutputStream zipOutputStream=null;FileInputStream fileInputStream=null;InputStreamResource resource=null;File zipFile=new File(zipFilePath);if(zipFile.exists()){zipFile.delete();}else {zipFile.createNewFile();}FileOutputStream fileOutputStream = new FileOutputStream(zipFile);zipOutputStream = new ZipOutputStream(fileOutputStream);for(File file:pdfFile){byte[] buf = new byte[BUFFER_SIZE];zipOutputStream.putNextEntry(new ZipEntry(file.getName()));int len;fileInputStream = new FileInputStream(file);while ((len = fileInputStream.read(buf)) != -1) {zipOutputStream.write(buf, 0, len);}fileInputStream.close();file.delete();}zipOutputStream.close();//从服务器读取文件 流传给前端fileInputStream = new FileInputStream(zipFile) ;resource = new InputStreamResource(fileInputStream);fileOutputStream.close();return resource;}

JAVA导出PDF并压缩成zip相关推荐

  1. java将文件夹压缩成zip java按照目录结构压缩文件夹

    前言 用java将文件夹压缩成zip包,像压缩软件一样,按照目录结构压缩(包含当前文件夹) 网上没有找到太合适的,借鉴其它帖子,自己写了一个 代码 package xin.yangshuai.myba ...

  2. java导出excel压缩包_java动态导出excel压缩成zip下载的方法

    本文实例为大家分享了java动态导出excel压缩成zip下载的具体代码,供大家参考,具体内容如下 package pack.java.io.demo; import java.io.Buffered ...

  3. Java导出多个excel压缩成zip下载

    Java导出多个excel压缩成zip下载 maven <!--hutoos工具类根据需要可以导入不同的模块,我这里是导入全部的模块--><dependency><gro ...

  4. java批量文件打包成压缩成zip下载和大量数据导出excel时的处理方法

    对于我们来说,java导出数据成excel或其他数据文件,或者下载资源是开发中的家常便饭, 但是在导出的时候,如果点击一个按钮导出几百万条数据,如果不作处理的话很可能会出现一系列的问题. 这里介绍打包 ...

  5. Java实现将文件或者文件夹压缩成zip

    Java实现将文件或者文件夹压缩成zip 最近碰到个需要下载zip压缩包的需求,于是我在网上找了下别人写好的zip工具类.但找了好多篇博客,总是发现有bug.因此就自己来写了个工具类. 这个工具类的功 ...

  6. java 把文件压缩成zip文件

    ackage org.fh.util;import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStr ...

  7. java zip压缩 加密码_java 压缩成zip文件、解压zip文件(可设置密码)

    1.情景展示 java实现将文件夹进行压缩打包的功能及在线解压功能 2.解决方案 方式一:压缩.解压zip 准备工作:slf4j-api.jar org.slf4j slf4j-api 1.7.25 ...

  8. Java将指定文件/文件夹压缩成zip、rar压缩文件

    import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream;import java.io.*; ...

  9. java压缩zip文件夹错误_Java将文件或者文件夹压缩成zip(修复文件夹中存在多个文件报Stream Closed错误问题)...

    项目场景: Java将文件或者文件夹压缩成zip(修复文件夹中存在多个文件报Stream Closed错误问题) 问题描述: 最近的项目需要将多级文件夹压缩成zip,网上找了几个工具类,都会报错,所以 ...

最新文章

  1. anaconda越新越好吗
  2. 使用ISAPI_Rewrite做实用的重定向
  3. 微信小程序项目实战知识点总结(swiper组件自适应高度,自定义弹出层,悬浮按钮,虚拟键盘)...
  4. Atitit.json类库的设计与实现 ati json lib
  5. Google开放最大目标检测数据集,还要为它举办AI挑战赛
  6. Output path is shared between the same module error
  7. 数据挖掘概念与技术(第三版)课后答案——第一章
  8. 有限元二阶拉格朗日插值函数理论
  9. 50 个实用小工具(图片处理、截屏录屏、格式转化、下载工具、浏览器、工具箱等)
  10. 【WebLogic使用】1.WebLogic的下载与安装
  11. 视频合并技巧,如何将多个视频合并在一起
  12. 【蓝桥杯单片机组实战】2、高级计算器
  13. git 冲突解决一把梭
  14. fastapi官方文档翻译 -目录
  15. 工程流体力学笔记暂记9(伯努利方程在工程中的应用)
  16. 德州仪器计算器 C语言编程,德州仪器因取消对计算器编程的支持而激怒业余爱好者...
  17. Baumer工业相机堡盟工业相机如何联合BGAPI SDK和OpenCVSharp实现Mono12和Mono16位深度的图像保存(C#)
  18. 修改exe文件的图标
  19. [go学习笔记.第一章] go可以做什么
  20. 知乎7000赞的通识教育书单

热门文章

  1. 两步轻松解除盗版Windows XP盗版警告
  2. 对口单招计算机电工试题答案,2015年对口单招机电专业电工技能试题一
  3. [系统安全] PE文件格式详解1
  4. Windows电脑、vmware虚拟机、ARM开发板互相ping通
  5. ubuntu下copyTranslator、Office插件安装
  6. mcgs 日期选择窗口_MCGS中想在页面上显示当前时间,要怎样做啊?
  7. pandorabox mysql_GitHub - gy-games/pandorabox: 基于非对称加密(RSA)的私密信息传递工具,数据由本地客户端进行加密、解密操作。...
  8. catia初学 v5R21
  9. VUE使用VLC插件播放RTSP流
  10. 用友华表Cell一些用法小结(cs.net版本)