今天做财务方面相关数据的导出功能,需要导出PDF和Excel,在项目经理那里得知有一个叫iTextPDF的java框架导出PDF文件很好用,于是拿来玩儿玩儿。

  1. package com.smart.produce.modules.finance.controller;
  2.  
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.itextpdf.text.Document;
  5. import com.itextpdf.text.PageSize;
  6. import com.itextpdf.text.Rectangle;
  7. import com.itextpdf.text.pdf.PdfWriter;
  8. import com.smart.produce.modules.finance.service.IExportService;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RequestMethod;
  13. import org.springframework.web.bind.annotation.ResponseBody;
  14.  
  15. import javax.servlet.http.HttpServletRequest;
  16. import java.io.FileOutputStream;
  17. import java.lang.reflect.Method;
  18.  
  19. @Controller
  20. @RequestMapping("${admin.url.prefix}/finance/export")
  21. public class ExportController {
  22.  
  23. @Autowired
  24. private IExportService exportService;
  25.  
  26. private String exportPath = "/static/financeExport";
  27.  
  28. @ResponseBody
  29. @RequestMapping(value="exportPDF", method={RequestMethod.GET, RequestMethod.POST})
  30. public String expStatementPDF(HttpServletRequest request, String name) {
  31. JSONObject result = new JSONObject();
  32. result.put("code", 0);
  33. result.put("msg", "success");
  34. // 输出文件路径
  35. String filePath = exportPath + "/" + name + ".pdf";
  36. result.put("data", filePath);
  37. String realPath = request.getServletContext().getRealPath("/");
  38. try {
  39. //Step 1—Create a Document.
  40. Rectangle rectangle = new Rectangle(PageSize.A4);
  41. Document document = new Document(rectangle);
  42. document.setMargins(20, 20, 40, 40);
  43. //Step 2—Get a PdfWriter instance.
  44. PdfWriter.getInstance(document, new FileOutputStream(realPath + filePath));
  45. //Step 3—Open the Document.
  46. document.open();
  47. //Step 4—Add content.
  48. Method method = IExportService.class.getDeclaredMethod(name + "Print", new Class[]{Document.class, String.class});
  49. method.invoke(exportService, document, realPath);
  50. //Step 5—Close the Document.
  51. document.close();
  52. } catch(Exception e) {
  53. e.printStackTrace();
  54. result.put("code", -1);
  55. result.put("msg", e.getMessage());
  56. }
  57. return result.toString();
  58. }
  59.  
  60. }

生成文档类

  1. package com.smart.produce.modules.finance.service.impl;
  2.  
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.itextpdf.text.*;
  6. import com.itextpdf.text.pdf.BaseFont;
  7. import com.itextpdf.text.pdf.PdfPCell;
  8. import com.itextpdf.text.pdf.PdfPTable;
  9. import com.smart.produce.modules.basic.entity.Customer;
  10. import com.smart.produce.modules.basic.service.ICustomerService;
  11. import com.smart.produce.modules.finance.service.IExportService;
  12. import com.smart.produce.modules.finance.service.IFinReceiptService;
  13. import com.smart.produce.modules.printorder.service.IOprPrintOrderService;
  14. import com.smart.produce.modules.printorder.service.ISettlementService;
  15. import com.smart.produce.modules.sys.service.IUserService;
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.stereotype.Service;
  18.  
  19. import java.util.ArrayList;
  20. import java.util.List;
  21.  
  22. /**
  23. * @Title: PDF输出
  24. * @Description: PDF输出
  25. * @author guanghe
  26. * @date 2018-09-26 15:32:08
  27. * @version V1.0
  28. *
  29. */
  30. @Service("finExportService")
  31. public class ExportServiceImpl implements IExportService {
  32.  
  33. @Autowired
  34. protected IUserService userService;
  35.  
  36. @Autowired
  37. protected IOprPrintOrderService oprPrintOrderService;
  38.  
  39. @Autowired
  40. protected IFinReceiptService finReceiptService;
  41.  
  42. @Autowired
  43. protected ICustomerService customerService;
  44.  
  45. @Autowired
  46. protected ISettlementService settlementService;
  47.  
  48. // 标题字体
  49. private Font simheiBig = null;
  50. // 副标题字体
  51. private Font simheiMiddle = null;
  52. // 表头字体
  53. private Font simhei = null;
  54. // 正文字体
  55. private Font simfang = null;
  56. // 正文加粗字体
  57. private Font simfangBold = null;
  58.  
  59. //初始化字体
  60. protected void initFonts(String realPath) throws Exception{
  61. String fontPath = realPath +"/static/fonts";
  62. if(simhei == null) {
  63. BaseFont baseFont = BaseFont.createFont(fontPath + "/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
  64. simheiBig = new Font(baseFont, 20);
  65. simheiMiddle = new Font(baseFont, 16);
  66. simhei = new Font(baseFont, 12);
  67. baseFont = BaseFont.createFont(fontPath + "/simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
  68. simfang = new Font(baseFont, 10);
  69. simfangBold = new Font(baseFont, 10, Font.BOLD);
  70. }
  71. }
  72.  
  73. protected PdfPCell getCell(String content) {
  74. Paragraph p = new Paragraph(content, simfangBold);
  75. p.setAlignment(Element.ALIGN_CENTER);
  76. PdfPCell cell = new PdfPCell();
  77. cell.addElement(p);
  78. cell.setBorderColor(BaseColor.LIGHT_GRAY);
  79. cell.setFixedHeight(25);
  80. cell.setUseAscender(true);
  81. cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
  82. return cell;
  83. }
  84.  
  85. @Override
  86. public void statementPrint(Document document, String realPath, String dataStr) throws Exception {
  87. initFonts(realPath);
  88. JSONObject data = JSONObject.parseObject(dataStr);
  89. String customerId = data.getString("customerId");
  90. Customer customer = customerService.selectById(customerId);
  91. JSONArray detail = data.getJSONArray("detail");
  92. //创建三列的表头表格
  93. PdfPTable tbTitle = new PdfPTable(3);
  94. //去掉表头表格的边框
  95. int wtTitle[] = {30,40,30};
  96. tbTitle.setWidths(wtTitle);
  97. tbTitle.getDefaultCell().setBorder(0);
  98. //留出空余
  99. tbTitle.addCell("");
  100. //添加主标题
  101. PdfPCell cellTitle = new PdfPCell();
  102. Paragraph pTitle = new Paragraph();
  103. Chunk chkTitle = new Chunk("对 账 单", simheiBig);
  104. chkTitle.setUnderline(1, -3f);
  105. pTitle.add(chkTitle);
  106. pTitle.setAlignment(Element.ALIGN_CENTER);
  107. cellTitle.addElement(pTitle);
  108. cellTitle.setVerticalAlignment(Element.ALIGN_BOTTOM);
  109. cellTitle.setBorder(0);
  110. tbTitle.addCell(cellTitle);
  111. //添加标注
  112. PdfPCell cellLabel = new PdfPCell();
  113. Paragraph pLabel = new Paragraph("单据记录式", simheiMiddle);
  114. pLabel.setAlignment(Element.ALIGN_RIGHT);
  115. cellLabel.setVerticalAlignment(Element.ALIGN_TOP);
  116. cellLabel.setBorder(0);
  117. cellLabel.addElement(pLabel);
  118. tbTitle.addCell(cellLabel);
  119. document.add(tbTitle);
  120. //添加空行
  121. Paragraph blankRow = new Paragraph(18f, " ");
  122. document.add(blankRow);
  123. //添加副标题
  124. PdfPTable tbSubtitle = new PdfPTable(1);
  125. PdfPCell cellSubtitle = new PdfPCell();
  126. Paragraph pSubtitle = new Paragraph("客户信息", simheiMiddle);
  127. cellSubtitle.addElement(pSubtitle);
  128. cellSubtitle.setPaddingBottom(5);
  129. cellSubtitle.setBorderWidthTop(0);
  130. cellSubtitle.setBorderWidthLeft(0);
  131. cellSubtitle.setBorderWidthRight(0);
  132. cellSubtitle.setBorderWidthBottom(2);
  133. tbSubtitle.addCell(cellSubtitle);
  134. document.add(tbSubtitle);
  135. //添加明细表头
  136. PdfPTable tbNote = new PdfPTable(3);
  137. int wtNote[] = {30,40,30};
  138. tbNote.setWidths(wtNote);
  139. //添加客户编号
  140. PdfPCell cellNo = new PdfPCell();
  141. Paragraph pNo = new Paragraph("客户编号:" + customer.getCustomerNo(), simhei);
  142. cellNo.addElement(pNo);
  143. cellNo.setBorder(0);
  144. tbNote.addCell(cellNo);
  145. //添加客户名称
  146. PdfPCell cellName = new PdfPCell();
  147. Paragraph pName = new Paragraph("客户名称:" + customer.getCustomerName(), simhei);
  148. cellName.addElement(pName);
  149. cellName.setBorder(0);
  150. tbNote.addCell(cellName);
  151. //添加联系方式
  152. PdfPCell cellContact = new PdfPCell();
  153. Paragraph pContact = new Paragraph("联系电话:" + customer.getPhone(), simhei);
  154. pContact.setAlignment(Element.ALIGN_RIGHT);
  155. cellContact.addElement(pContact);
  156. cellContact.setBorder(0);
  157. tbNote.addCell(cellContact);
  158. document.add(tbNote);
  159. //添加空行
  160. document.add(blankRow);
  161. //添加明细表格
  162. PdfPTable tbDetail = new PdfPTable(7);
  163. int wtDetail[] = {7, 18, 15, 15, 15, 15, 15};;
  164. tbDetail.setWidths(wtDetail);
  165. String heads[] = {"序号", "订单编号", "订单日期", "订单经手", "订单金额", "已清金额", "未清金额"};
  166. for(int i = 0; i < heads.length; i++) {
  167. PdfPCell cellHead = getCell(heads[i]);
  168. cellHead.setBackgroundColor(new BaseColor(230,230,230));
  169. tbDetail.addCell(cellHead);
  170. }
  171. document.add(tbDetail);
  172. for(int i = 0; i < detail.size(); i++) {
  173. JSONObject item = detail.getJSONObject(i);
  174. PdfPTable table = new PdfPTable(7);
  175. int width[] = {7, 18, 15, 15, 15, 15, 15};
  176. table.setWidths(width);
  177. String num = (i + 1) + "";
  178. List<String> contents = new ArrayList<String>(){{
  179. add(num);
  180. add(item.getString("orderNo"));
  181. add(item.getString("createDate"));
  182. add(item.getJSONObject("createBy").getString("username"));
  183. add(item.getString("orderAmount"));
  184. add(item.getString("receivedAmount"));
  185. add(item.getString("debtAmount"));
  186. }};
  187. for(int j = 0; j < contents.size(); j++) {
  188. PdfPCell cell = getCell(contents.get(j));
  189. table.addCell(cell);
  190. }
  191. document.add(table);
  192. }
  193. }
  194.  
  195. @Override
  196. public void topupPrint(Document document, String realPath, String dataStr) throws Exception {
  197.  
  198. }
  199.  
  200. @Override
  201. public void receiptPrint(Document document, String realPath, String dataStr) throws Exception {
  202. initFonts(realPath);
  203. JSONObject data = JSONObject.parseObject(dataStr);
  204. }
  205.  
  206. @Override
  207. public void prestoreExp() {
  208.  
  209. }
  210.  
  211. @Override
  212. public void topupExp() {
  213.  
  214. }
  215.  
  216. @Override
  217. public void receiptExp() {
  218.  
  219. }
  220.  
  221. @Override
  222. public void summaryExp() {
  223.  
  224. }
  225. }

Java生成PDF之iTextPDF的使用的更多相关文章

  1. Java 生成pdf表格文档

    最近在工作做一个泰国的项目,应供应商要求,需要将每天的交易生成pdf格式的报表上传到供应商的服务器,特此记录实现方法.废话不多说,直接上代码: THSarabunNew.ttf该文件是泰国字体自行网上 ...

  2. JAVA 生成PDF报表()

    许多应用程序都要求动态生成 PDF 文档.这些应用程序涵盖从生成客户对帐单并通过电子邮件交付的银行到购买特定的图书章节并以 PDF 格式接收这些图书章节的读者.这个列表不胜枚举.在本文中,我们将使用 ...

  3. Java生成PDF报表

    一.前言 前几天,做ASN条码收货模块,需要实现打印下载收货报表,经一番查找,选定iText--用于生成PDF文档的一个Java类库.废话不多说,进入正题. 二.iText简介 iText是著名的开放 ...

  4. java生成PDF文件(itext)

    itextpdf-5.4.3.jar下载地址: http://www.kuaipan.cn/file/id_58980483773788178.htm 导入itextpdf-5.4.3.jar ToP ...

  5. 电子凭证 : Java 生成 Pdf

    来源:蛙牛, my.oschina.net/lujianing/blog/894365 如有好文章投稿,请点击 → 这里了解详情 1.背景 在某些业务场景中,需要提供相关的电子凭证,比如网银/支付宝中 ...

  6. java生成pdf

    介绍 本篇博客主要是为了介绍如何使用:flying-saucer+itext+freemark实现导出复杂点的pdf文件. 思路 先把pdf的内容以html形式准备好 使用freemarker将htm ...

  7. java生成PDF,并下载到本地

    1.首先要写一个PDF工具类,以及相关工具 2.PDF所需jar包 iText是一种生成PDF报表的Java组件 freemarker是基于模板来生成文本输出 <dependency> & ...

  8. Java生成PDF文件(转)

    原文地址:https://www.cnblogs.com/shuilangyizu/p/5760928.html 一.前言 前几天,做ASN条码收货模块,需要实现打印下载收货报表,经一番查找,选定iT ...

  9. [itext]Java生成PDF文件

    一.前言 最近在做也导出试卷的功能,刚开始是导出为doc,可是导出来格式都有变化,最后说直接将word转为pdf,可是各种不稳定,各种报错.最后想到直接将文件写入pdf(参考:http://www.c ...

随机推荐

  1. 策略模式原理及Java代码实例

    一.策略模式的定义 —— 定义了一组算法,将每个算法包装起来,并且使它们之间可以互换 —— 策略模式使这些算法在客户端调用它们的时候能够相互不影响的变化,改变不同算法的实现方式不影响客户端的使用,即策 ...

  2. HTTP/2笔记之消息交换

    前言 无论是HTTP/1.*还是HTTP/2,HTTP的基本语义是不变的,比如方法语义(GET/PUST/PUT/DELETE),状态码(200/404/500等),Range Request,Cac ...

  3. MQTT的学习研究(十四) MQTT moquette 的 Callback API 消息发布订阅的实现

    在moquette-mqtt中提供了回调callback模式的发布和订阅但是在订阅之后没有发现有消息接收的方法,参看moquette-mqtt中Block,Future式的发布订阅基础是callbac ...

  4. Java多线程详解(三)

    1)死锁 两个线程相互等待对方释放同步监视器时会出现死锁的现象,这时所有的线程都处于阻塞状态,程序无法继续向下执行. 如下就是会出现死锁的程序. 首先flag = 1,线程d1开始执行,锁住对象o1, ...

  5. Linux命令学习之xargs命令

    xargs命令是给其他命令传递参数的一个过滤器,也是组合多个命令的一个工具.它擅长将标准输入数据转换成命令行参数,xargs能够处理管道或者stdin并将其转换成特定命令的命令参数.xargs也可以将 ...

  6. SenchaTouch学习博客

    魔狼在世: http://www.cnblogs.com/mlzs/

  7. 【黑金ZYNQ7000系列原创视频教程】01.熟悉vivado——纯逻辑led实验

    黑金论坛地址: http://www.heijin.org/forum.php?mod=viewthread&tid=36627&extra=page%3D1 爱奇艺地址: http: ...

  8. 【BZOJ3362-3365】USACO水题四连A

    [BZOJ3362][Usaco2004 Feb]Navigation Nightmare 导航噩梦 Description     农夫约翰有N(2≤N≤40000)个农场,标号1到N,M(2≤M≤ ...

  9. SpringMVC中 解决@ResponseBody注解返回中文乱码

    问题:在前端通过get请求服务端返回String类型的服务时,会出现中文乱码问题 原因:由于spring默认对String类型的返回的编码采用的是 StringHttpMessageConverter ...

  10. 【php】---mysql语法增、删、改、查---【巷子】

    1.mysql基本语法 001.增 语法:          insert into 表名 (列1,列2,列3) values(值1,值2,值3)     批量插入:插入insert-插入多行   语 ...