Java生成PDF之iTextPDF的使用

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

 package com.smart.produce.modules.finance.controller;

 import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import com.smart.produce.modules.finance.service.IExportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.lang.reflect.Method; @Controller
@RequestMapping("${admin.url.prefix}/finance/export")
public class ExportController { @Autowired
private IExportService exportService; private String exportPath = "/static/financeExport"; @ResponseBody
@RequestMapping(value="exportPDF", method={RequestMethod.GET, RequestMethod.POST})
public String expStatementPDF(HttpServletRequest request, String name) {
JSONObject result = new JSONObject();
result.put("code", 0);
result.put("msg", "success");
// 输出文件路径
String filePath = exportPath + "/" + name + ".pdf";
result.put("data", filePath);
String realPath = request.getServletContext().getRealPath("/");
try {
//Step 1—Create a Document.
Rectangle rectangle = new Rectangle(PageSize.A4);
Document document = new Document(rectangle);
document.setMargins(20, 20, 40, 40);
//Step 2—Get a PdfWriter instance.
PdfWriter.getInstance(document, new FileOutputStream(realPath + filePath));
//Step 3—Open the Document.
document.open();
//Step 4—Add content.
Method method = IExportService.class.getDeclaredMethod(name + "Print", new Class[]{Document.class, String.class});
method.invoke(exportService, document, realPath);
//Step 5—Close the Document.
document.close();
} catch(Exception e) {
e.printStackTrace();
result.put("code", -1);
result.put("msg", e.getMessage());
}
return result.toString();
} }

生成文档类

 package com.smart.produce.modules.finance.service.impl;

 import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.smart.produce.modules.basic.entity.Customer;
import com.smart.produce.modules.basic.service.ICustomerService;
import com.smart.produce.modules.finance.service.IExportService;
import com.smart.produce.modules.finance.service.IFinReceiptService;
import com.smart.produce.modules.printorder.service.IOprPrintOrderService;
import com.smart.produce.modules.printorder.service.ISettlementService;
import com.smart.produce.modules.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.ArrayList;
import java.util.List; /**
* @Title: PDF输出
* @Description: PDF输出
* @author guanghe
* @date 2018-09-26 15:32:08
* @version V1.0
*
*/
@Service("finExportService")
public class ExportServiceImpl implements IExportService { @Autowired
protected IUserService userService; @Autowired
protected IOprPrintOrderService oprPrintOrderService; @Autowired
protected IFinReceiptService finReceiptService; @Autowired
protected ICustomerService customerService; @Autowired
protected ISettlementService settlementService; // 标题字体
private Font simheiBig = null;
// 副标题字体
private Font simheiMiddle = null;
// 表头字体
private Font simhei = null;
// 正文字体
private Font simfang = null;
// 正文加粗字体
private Font simfangBold = null; //初始化字体
protected void initFonts(String realPath) throws Exception{
String fontPath = realPath +"/static/fonts";
if(simhei == null) {
BaseFont baseFont = BaseFont.createFont(fontPath + "/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
simheiBig = new Font(baseFont, 20);
simheiMiddle = new Font(baseFont, 16);
simhei = new Font(baseFont, 12);
baseFont = BaseFont.createFont(fontPath + "/simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
simfang = new Font(baseFont, 10);
simfangBold = new Font(baseFont, 10, Font.BOLD);
}
} protected PdfPCell getCell(String content) {
Paragraph p = new Paragraph(content, simfangBold);
p.setAlignment(Element.ALIGN_CENTER);
PdfPCell cell = new PdfPCell();
cell.addElement(p);
cell.setBorderColor(BaseColor.LIGHT_GRAY);
cell.setFixedHeight(25);
cell.setUseAscender(true);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
return cell;
} @Override
public void statementPrint(Document document, String realPath, String dataStr) throws Exception {
initFonts(realPath);
JSONObject data = JSONObject.parseObject(dataStr);
String customerId = data.getString("customerId");
Customer customer = customerService.selectById(customerId);
JSONArray detail = data.getJSONArray("detail");
//创建三列的表头表格
PdfPTable tbTitle = new PdfPTable(3);
//去掉表头表格的边框
int wtTitle[] = {30,40,30};
tbTitle.setWidths(wtTitle);
tbTitle.getDefaultCell().setBorder(0);
//留出空余
tbTitle.addCell("");
//添加主标题
PdfPCell cellTitle = new PdfPCell();
Paragraph pTitle = new Paragraph();
Chunk chkTitle = new Chunk("对 账 单", simheiBig);
chkTitle.setUnderline(1, -3f);
pTitle.add(chkTitle);
pTitle.setAlignment(Element.ALIGN_CENTER);
cellTitle.addElement(pTitle);
cellTitle.setVerticalAlignment(Element.ALIGN_BOTTOM);
cellTitle.setBorder(0);
tbTitle.addCell(cellTitle);
//添加标注
PdfPCell cellLabel = new PdfPCell();
Paragraph pLabel = new Paragraph("单据记录式", simheiMiddle);
pLabel.setAlignment(Element.ALIGN_RIGHT);
cellLabel.setVerticalAlignment(Element.ALIGN_TOP);
cellLabel.setBorder(0);
cellLabel.addElement(pLabel);
tbTitle.addCell(cellLabel);
document.add(tbTitle);
//添加空行
Paragraph blankRow = new Paragraph(18f, " ");
document.add(blankRow);
//添加副标题
PdfPTable tbSubtitle = new PdfPTable(1);
PdfPCell cellSubtitle = new PdfPCell();
Paragraph pSubtitle = new Paragraph("客户信息", simheiMiddle);
cellSubtitle.addElement(pSubtitle);
cellSubtitle.setPaddingBottom(5);
cellSubtitle.setBorderWidthTop(0);
cellSubtitle.setBorderWidthLeft(0);
cellSubtitle.setBorderWidthRight(0);
cellSubtitle.setBorderWidthBottom(2);
tbSubtitle.addCell(cellSubtitle);
document.add(tbSubtitle);
//添加明细表头
PdfPTable tbNote = new PdfPTable(3);
int wtNote[] = {30,40,30};
tbNote.setWidths(wtNote);
//添加客户编号
PdfPCell cellNo = new PdfPCell();
Paragraph pNo = new Paragraph("客户编号:" + customer.getCustomerNo(), simhei);
cellNo.addElement(pNo);
cellNo.setBorder(0);
tbNote.addCell(cellNo);
//添加客户名称
PdfPCell cellName = new PdfPCell();
Paragraph pName = new Paragraph("客户名称:" + customer.getCustomerName(), simhei);
cellName.addElement(pName);
cellName.setBorder(0);
tbNote.addCell(cellName);
//添加联系方式
PdfPCell cellContact = new PdfPCell();
Paragraph pContact = new Paragraph("联系电话:" + customer.getPhone(), simhei);
pContact.setAlignment(Element.ALIGN_RIGHT);
cellContact.addElement(pContact);
cellContact.setBorder(0);
tbNote.addCell(cellContact);
document.add(tbNote);
//添加空行
document.add(blankRow);
//添加明细表格
PdfPTable tbDetail = new PdfPTable(7);
int wtDetail[] = {7, 18, 15, 15, 15, 15, 15};;
tbDetail.setWidths(wtDetail);
String heads[] = {"序号", "订单编号", "订单日期", "订单经手", "订单金额", "已清金额", "未清金额"};
for(int i = 0; i < heads.length; i++) {
PdfPCell cellHead = getCell(heads[i]);
cellHead.setBackgroundColor(new BaseColor(230,230,230));
tbDetail.addCell(cellHead);
}
document.add(tbDetail);
for(int i = 0; i < detail.size(); i++) {
JSONObject item = detail.getJSONObject(i);
PdfPTable table = new PdfPTable(7);
int width[] = {7, 18, 15, 15, 15, 15, 15};
table.setWidths(width);
String num = (i + 1) + "";
List<String> contents = new ArrayList<String>(){{
add(num);
add(item.getString("orderNo"));
add(item.getString("createDate"));
add(item.getJSONObject("createBy").getString("username"));
add(item.getString("orderAmount"));
add(item.getString("receivedAmount"));
add(item.getString("debtAmount"));
}};
for(int j = 0; j < contents.size(); j++) {
PdfPCell cell = getCell(contents.get(j));
table.addCell(cell);
}
document.add(table);
}
} @Override
public void topupPrint(Document document, String realPath, String dataStr) throws Exception { } @Override
public void receiptPrint(Document document, String realPath, String dataStr) throws Exception {
initFonts(realPath);
JSONObject data = JSONObject.parseObject(dataStr);
} @Override
public void prestoreExp() { } @Override
public void topupExp() { } @Override
public void receiptExp() { } @Override
public void summaryExp() { }
}
上一篇:分页实现:Offset-Fetch


下一篇:[精品推荐]Android Studio插件整理