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

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. 盒子模型 W3C中和IE中盒子的总宽度分别是什么

    W3C盒模型 总宽度 = margin-left + border-left + padding-left + width + padding-right + border-right + margi ...

  2. SDWebImage使用,图片加载和缓存

    本文转载至 http://blog.163.com/wzi_xiang/blog/static/659829612012111402812726/     清除缓存: [[SDImageCache s ...

  3. PyQt4关闭窗口

    一个显而易见的关闭窗口的方式是但集标题兰有上角的X标记.接下来的示例展示如何用代码来关闭程序,并简要介绍Qt的信号和槽机制. 下面是QPushButton的构造函数,我们将会在下面的示例中使用它. Q ...

  4. JS 获取中英字符串字节长度

    正则匹配中文字: 这里限定中文字的范围,一般的使用是没什么问题的.如果要求十分严格的话,那么就只能使用更加严谨的代码匹配了 1:/([^\u0000-\u00FF])/g 2:/[^\x00-\xff ...

  5. poj_3580 伸展树

    自己伸展树做的第一个题 poj 3580 supermemo. 题目大意 对一个数组进行维护,包含如下几个操作: ADD x, y, d 在 A[x]--A[y] 中的每个数都增加d REVERSE ...

  6. javascript飞机大战-----007爆炸效果

    要检验什么时候碰撞,我们必须了解什么时候不相撞.以上四种情况是不相撞的时候 首先在引擎里面写好什么时候碰撞什么时候不碰撞 /* 游戏引擎 */ var Engine = { //刚开始的游戏状态 ga ...

  7. nginx软件的编译安装步骤

    1.1 检查软件安装的系统环境 [root@web02 conf]# cat /etc/redhat-release CentOS release 6.8 (Final) [root@web02 co ...

  8. SaltStack配置管理-状态间关系

    上一篇:SaltStack配置管理-LAMP状态设计 include包含 上篇安装LAMP环境是一个个环境安装,可以通过include模块全部安装 lamp.sls include: - apache ...

  9. Eclipse Tomcat插件的配置, 及 Tomcat 的配置

    Eclipse Tomcat插件的配置, 及 Tomcat 的配置   首先下载 对应 eclipse 版本的 tomcat 插件版本,(这里要注意: Tomcat 插件是Tomcat 插件,Tomc ...

  10. oracle goldengate安装

    1.ftp工具上传ogg112101_fbo_ggs_Linux_x64_ora11g_64bit.zip分别到source和target服务器 [oracle@localhost mnt]$ ll ...