Java生成PDF之iTextPDF的使用

  今天做财务方面相关数据的导出功能,需要导出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 }

 

posted @ 2018-09-27 16:10  光何  阅读(2217)  评论(0编辑  收藏  举报