先上个效果图

因为做的项目涉及到数据预测,其中有大量打印业务来支撑实体店的运营,因为注重的是数据,要求简洁,清晰,所以写了个很简单也很实用的工具类。

如果需要编写样式或者插入背景,都可以查阅itex官方文档,进行扩展。

这个工具是基于 itext 写的,主要作用是生成最简洁的表格,选用的jar包版本是:

<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>

废话就不多说了,直接贴代码 PDFConstants.class

import java.awt.Color;
import java.util.List; import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable; public class PDFConstants { /**
* PDF大标题字体
*/
public static Font PDFTITLEFONT = new Font(null, 16, Font.BOLD); /**
* PDF小标题字体
*/
public static Font PDFTITLEFONT1 = new Font(null, 13, Font.NORMAL); /**
* 表格宽度百分比
*/
public static Integer WIDTHPERCENTAGE = 98; /**
* 表格标题字体
*/
public static Font TITLEFONT = new Font(null, 12, Font.COURIER); /**
* 翻页加载表头
*/
public static Integer HEADERROWS = 1; /**
* 翻页不加载表头
*/
public static Integer NOHEADERROWS = 0; /**
* 表格内容字体
*/
public static Font CONTENTFONT = new Font(null, 9, Font.NORMAL); /**
* PDF表格样式
*/
private static PdfPCell cell = new PdfPCell(); /**
* 获取表格
*/
public static PdfPCell getCell() {
// 水平居中
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
// 垂直居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// 边距
cell.setPadding(1);
// 行高
cell.setMinimumHeight(22);
// 不换行
// cell.setNoWrap(true);
// 颜色淡化
cell.setBorderColor(Color.decode("#EBEEF5"));
return cell;
} /**
* 获取表格并赋值
*/
public static PdfPCell getCell(Paragraph content) {
cell = getCell();
// 设置内容
cell.setPhrase(content);
return cell;
} /**
* @Description 生成PDF表格
* @param titleNum
* 列数
* @param tableWidth
* 列宽
* @param titles
* 标题集合
* @param contents
* 内容集合
* @param headerRows
* 是否再次加载表头
* @return
* @throws Exception
*/
public static PdfPTable getPDFTable(int titleNum, int[] tableWidth, String[] titles, List<String> contents, int headerRows) throws Exception {
// 创建表格对象
// 列数
PdfPTable table = new PdfPTable(titleNum); //表格宽度百分比
table.setWidthPercentage(WIDTHPERCENTAGE); // 列宽百分比
if (tableWidth != null)
table.setWidths(tableWidth); // 翻页加载表头
if (headerRows == HEADERROWS)
table.setHeaderRows(HEADERROWS); // 标题集合
String[] pdfTitles = titles;
if (pdfTitles != null && pdfTitles.length > 0) {
// 标题
for (String pdfTitle : pdfTitles) {
PdfPCell title = getCell(new Paragraph(pdfTitle, TITLEFONT));
table.addCell(title);
}
}
// 内容集合
List<String> pdfContents = contents;
if (pdfContents != null && pdfContents.size() > 0) {
// 内容
for (String pdfContent : pdfContents) {
PdfPCell content = getCell(new Paragraph(pdfContent, CONTENTFONT));
table.addCell(content);
}
} // 撑行数,否则最后一行会消失
    table.addCell("");
    table.completeRow();
return table;
} }

分页工具类 PDFMaker.class

import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter; /**
* @Description 分页工具
* @author ry
* @date 2019年7月12日
*/
public class PDFMaker extends PdfPageEventHelper { /** 这个PdfTemplate实例用于保存总页数 */
public PdfTemplate tpl;
/** 页码字体 */
public BaseFont helv; @Override
public void onCloseDocument(PdfWriter writer, com.lowagie.text.Document arg1) {
tpl.beginText();
tpl.setFontAndSize(helv, 12);
tpl.setTextMatrix(0, 0);
tpl.showText("" + (writer.getPageNumber() - 1));
tpl.endText();
} /*
* (non-Javadoc)
*
* @see
* com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf
* .PdfWriter, com.lowagie.text.Document)
*/
@Override
public void onEndPage(PdfWriter writer, com.lowagie.text.Document document) {
PdfContentByte cb = writer.getDirectContent();
cb.saveState(); String text = " Page " + writer.getPageNumber() + " of ";
float textSize = helv.getWidthPoint(text, 9);
float textBase = document.bottom();
cb.beginText();
cb.setFontAndSize(helv, 9);
// for odd pagenumbers, show t cb.setTextMatrix(document.left(), textBase);
cb.showText(text);
cb.endText();
cb.addTemplate(tpl, document.left() + textSize, textBase);
cb.restoreState();
} /*
* (non-Javadoc)
*
* @see
* com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text
* .pdf.PdfWriter, com.lowagie.text.Document)
*/
@Override
public void onOpenDocument(PdfWriter writer, com.lowagie.text.Document arg1) {
try {
// initialization of the template
tpl = writer.getDirectContent().createTemplate(100, 100); // tpl.setBoundingBox(new Rectangle(0, 0, 10, 10));
// initialization of the font
helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
} catch (Exception e) { }
} }

注意:网上大部分此工具类都会报错,生成PDF失败 Unbalanced save/restore state operators,这是因为调用了saveState()但是没调用restoreState(),这里我已经修正了

拿出部分业务代码做例子,使用这个工具是很简单的

首先打开一个文档

  // 定义文件路径 你可以完成过程后删掉这个临时文件 或者存在tmp里
  File f = new File("xxxx/xxx.pdf");
  FileOutputStream output = new FileOutputStream(f);
  // 实例化文档对象
  Document document = new Document(PageSize.A4, 0, 0, 0, 0);
  // 创建 PdfWriter 对象 文件的输出路径+文件的实际名称
  PdfWriter writer = PdfWriter.getInstance(document, output);
  // 设置分页
  writer.setPageEvent(new PDFMaker());   document.open();// 打开文档
Document有横向属性 使用方法是 PageSize.A4.rotate()这个rotate方法是个神奇的方法
后面四个数字对应的是边距 分别是 左,右,上,下

生成table几个传参的例子

  // 标题
  String[] title = { "Min.", "SUN", "MON", "TUE", "WED", "THUR", "FRI", "SAT" };   // 列数
  Integer titleNum = 8;   // 列宽
  int tableWidth[] = { 15, 15, 15, 10, 10, 12, 12, 11 };
  //内容
  List<String> contents = new ArrayList<String>();
  //TODO 业务代码填充contens   // 获取PDFTable
  PdfPTable table = PDFConstants.getPDFTable(titleNum, tableWidth, title, contents, 0);   //表格上间距
  table.setSpacingBefore(0);
  //添加进文档
  document.add(table);
  //关闭文档
  document.close();

如果大家有什么不解,或意见,欢迎在下方留言,楼主看到就会回复的,谢谢。

												

java(itext) 一个很简单的PDF表格生成工具的更多相关文章

  1. (二)一个很好用的自动生成工具——mybatis generator

    mybatis generator-自动生成代码 准备材料: 一个文件夹,一个数据库的驱动包,mybatis-generator-core-1.3.5.jar,一条生成语句 如图:(我用的是derby ...

  2. [.NET] 打造一个很简单的文档转换器 - 使用组件 Spire.Office

    打造一个很简单的文档转换器 - 使用组件 Spire.Office [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/6024827.html 序 之前,& ...

  3. 一个最简单 node.js 命令行工具

    一个最简单 node.js 命令行工具 node.js cli $ node cli.js xyz # OR $ node cli xyz 接受参数 process.argv js "use ...

  4. 一个很简单的jQuery插件实例教程(菜鸟级)

    很多公司的前端设计开发人员都是女孩子,而这些女孩子很多JavaScript技能都不是很好.而前端开发过程中,JavaScript技能又是必不可少的.所以,如果前端小MM正在为某个JavaScript效 ...

  5. 一个很简单的SqlServer生成常用C#语句工具的诞生

    前言: 这个文章只要是记录一下,这个工具的诞生过程.作用.其中的技术实在是太简单可以说没有什么技术~主要是锻炼一下写文章的能力! 正文: 在开发项目的时,常常会要维护或变更一些老项目,涉及到简单的几张 ...

  6. 一个很简单的php留言板。。。。搭建在sae上的。。。

    我在sae上搭建了一个个人简历的页面: 有兴趣的可以访问  http://671coder.sinaapp.com/ 在做下面一个简单的留言板的时候,卡了我很久,虽然完全没用过php..但是还是最后勉 ...

  7. java实现一个最简单的tomcat服务

    在了解tomcat的基本原理之前,首先要了解tomcatt最基本的运行原理. 1.如何启动? main方法是程序的入口,tomcat也不例外,查看tomcat源码,发现main是在Bootstrap  ...

  8. 『NYIST』第八届河南省ACM竞赛训练赛[正式赛一]-CodeForces 236A,虽然很水,但有一个很简单的函数用起来方便

    A. Boy or Girl time limit per test 1 second memory limit per test 256 megabytes input standard input ...

  9. 一个很简单的SpringCloud项目,集成Feign、Hystrix

    Feign的功能:这是个消费者,根据服务注册在Eureka的ID去找到该服务,并调用接口Hystrix的功能:熔断器,假如A服务需要调用B服务的/cities接口获取数据,那就在A服务的control ...

随机推荐

  1. shell批量创建用户随机密码

    批量创建用户随机密码企业面试题3:批量创建10个系统帐号usr01-usr10并设置密码(密码为随机8位字符串). #! /bin/bash . /etc/init.d/functions Path= ...

  2. Codeforces 1107G Vasya and Maximum Profit 线段树最大子段和 + 单调栈

    Codeforces 1107G 线段树最大子段和 + 单调栈 G. Vasya and Maximum Profit Description: Vasya got really tired of t ...

  3. 21. Bypass D盾_防火墙(旧版 and 新版)SQL注入防御(多姿势)

    D盾旧版: 00前言 D盾_IIS防火墙,目前只支持Win2003服务器,前阵子看见官方博客说D盾新版将近期推出,相信功能会更强大,这边分享一下之前的SQL注入防御的测试情况.D盾_IIS防火墙注入防 ...

  4. JavaScript 异常 Exceptions

    JavaScript提供了一套异常处理机制. 异常是干扰程序的正常流程的不寻常(但并非完全是出乎意料的)的事故. 当发现这样的事故时,你的程序应该抛出一个异常. throw语句中断函数的执行. 它应该 ...

  5. Sharepoint2013商务智能学习笔记之Excel Service服务配置(四)

    第一步,新建Excel Service应用程序 第二步,管理中心,在应用程序管理区域点管理服务应用程序,进入应用程序管理列表, 再点击刚才新建好的ExcelServiceApplication进入ex ...

  6. js中top.location.href、parent.location.href用法

    window.location.href.location.href是本页面跳转 parent.location.href是上一层页面跳转 top.location.href是最外层的页面跳转 举例说 ...

  7. webpack4下import()模块按需加载,打包按需切割模块,减少包体积,加快首页请求速度

    一:背景 因为项目功能越加越多,打包后的体积越来越大,导致首页展示的时候速度比较慢,因为要等压缩的js的包加载完毕. 首页展示的时候只需要对应的js,并不需要全部的js模块,所以这里就可以用按需加载, ...

  8. 基本图形的绘制(基于skimage)

    图形包括线条.圆形.椭圆形.多边形等.在skimage包中,绘制图形用的是draw模块,不要和绘制图像搞混了. 一  线条 函数调用格式:     skimage.draw.line(r1,c1,r2 ...

  9. 教大家一个看电视局免广告的方法--由UWP想到的

    将近一年(10个月)来一直在学习.NET技术,这其中包括C#.WPF.WCF和ASP.NET MVC,目前学习即将结束. 本人在学习WPF的过程中,也了解到有UWP这门技术,UWP技术目前来说主要是应 ...

  10. gulp使用文档

    gulp的优势 易于使用:通过代码优于配置的策略,Gulp让简单的任务简单,复杂的任务可管理. 构建快速:利用 Node.js 流的威力,你可以快速构建项目并减少频繁的 IO 操作. 插件高质:Gul ...