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() {
- }
- }
Java生成PDF之iTextPDF的使用的更多相关文章
- Java 生成pdf表格文档
最近在工作做一个泰国的项目,应供应商要求,需要将每天的交易生成pdf格式的报表上传到供应商的服务器,特此记录实现方法.废话不多说,直接上代码: THSarabunNew.ttf该文件是泰国字体自行网上 ...
- JAVA 生成PDF报表()
许多应用程序都要求动态生成 PDF 文档.这些应用程序涵盖从生成客户对帐单并通过电子邮件交付的银行到购买特定的图书章节并以 PDF 格式接收这些图书章节的读者.这个列表不胜枚举.在本文中,我们将使用 ...
- Java生成PDF报表
一.前言 前几天,做ASN条码收货模块,需要实现打印下载收货报表,经一番查找,选定iText--用于生成PDF文档的一个Java类库.废话不多说,进入正题. 二.iText简介 iText是著名的开放 ...
- java生成PDF文件(itext)
itextpdf-5.4.3.jar下载地址: http://www.kuaipan.cn/file/id_58980483773788178.htm 导入itextpdf-5.4.3.jar ToP ...
- 电子凭证 : Java 生成 Pdf
来源:蛙牛, my.oschina.net/lujianing/blog/894365 如有好文章投稿,请点击 → 这里了解详情 1.背景 在某些业务场景中,需要提供相关的电子凭证,比如网银/支付宝中 ...
- java生成pdf
介绍 本篇博客主要是为了介绍如何使用:flying-saucer+itext+freemark实现导出复杂点的pdf文件. 思路 先把pdf的内容以html形式准备好 使用freemarker将htm ...
- java生成PDF,并下载到本地
1.首先要写一个PDF工具类,以及相关工具 2.PDF所需jar包 iText是一种生成PDF报表的Java组件 freemarker是基于模板来生成文本输出 <dependency> & ...
- Java生成PDF文件(转)
原文地址:https://www.cnblogs.com/shuilangyizu/p/5760928.html 一.前言 前几天,做ASN条码收货模块,需要实现打印下载收货报表,经一番查找,选定iT ...
- [itext]Java生成PDF文件
一.前言 最近在做也导出试卷的功能,刚开始是导出为doc,可是导出来格式都有变化,最后说直接将word转为pdf,可是各种不稳定,各种报错.最后想到直接将文件写入pdf(参考:http://www.c ...
随机推荐
- 策略模式原理及Java代码实例
一.策略模式的定义 —— 定义了一组算法,将每个算法包装起来,并且使它们之间可以互换 —— 策略模式使这些算法在客户端调用它们的时候能够相互不影响的变化,改变不同算法的实现方式不影响客户端的使用,即策 ...
- HTTP/2笔记之消息交换
前言 无论是HTTP/1.*还是HTTP/2,HTTP的基本语义是不变的,比如方法语义(GET/PUST/PUT/DELETE),状态码(200/404/500等),Range Request,Cac ...
- MQTT的学习研究(十四) MQTT moquette 的 Callback API 消息发布订阅的实现
在moquette-mqtt中提供了回调callback模式的发布和订阅但是在订阅之后没有发现有消息接收的方法,参看moquette-mqtt中Block,Future式的发布订阅基础是callbac ...
- Java多线程详解(三)
1)死锁 两个线程相互等待对方释放同步监视器时会出现死锁的现象,这时所有的线程都处于阻塞状态,程序无法继续向下执行. 如下就是会出现死锁的程序. 首先flag = 1,线程d1开始执行,锁住对象o1, ...
- Linux命令学习之xargs命令
xargs命令是给其他命令传递参数的一个过滤器,也是组合多个命令的一个工具.它擅长将标准输入数据转换成命令行参数,xargs能够处理管道或者stdin并将其转换成特定命令的命令参数.xargs也可以将 ...
- SenchaTouch学习博客
魔狼在世: http://www.cnblogs.com/mlzs/
- 【黑金ZYNQ7000系列原创视频教程】01.熟悉vivado——纯逻辑led实验
黑金论坛地址: http://www.heijin.org/forum.php?mod=viewthread&tid=36627&extra=page%3D1 爱奇艺地址: http: ...
- 【BZOJ3362-3365】USACO水题四连A
[BZOJ3362][Usaco2004 Feb]Navigation Nightmare 导航噩梦 Description 农夫约翰有N(2≤N≤40000)个农场,标号1到N,M(2≤M≤ ...
- SpringMVC中 解决@ResponseBody注解返回中文乱码
问题:在前端通过get请求服务端返回String类型的服务时,会出现中文乱码问题 原因:由于spring默认对String类型的返回的编码采用的是 StringHttpMessageConverter ...
- 【php】---mysql语法增、删、改、查---【巷子】
1.mysql基本语法 001.增 语法: insert into 表名 (列1,列2,列3) values(值1,值2,值3) 批量插入:插入insert-插入多行 语 ...