最近在做报表打印,使用的是itextPDF,第一次用到它,简单做个笔记。主要涉及到字体设置,文字处理操作,表格及单元格设置,绘制一些图形

IText中有三个处理text的类com.lowagie.text.Chunk,com.lowagie.text.Phrase,com.lowagie.text.Paragraph。

官网的API:https://api.itextpdf.com/iText5/5.5.9/

document文档的一些基本设置:https://blog.csdn.net/tomatocc/article/details/80666361

document.setPageSize(PageSize.A4.rotate());// A4横向打印
document.newPage(); //另起一页面
document.add(new Paragraph(" ", CUtility.getSun(4)));//间接到达换行效果

关于表格宽度,单元格宽度的设置

PDF画表格,确定表格每一列的宽度和表格总宽度

// 中间表格部分
for (int i = 0; i < 7; i++) {
document.add(new Paragraph(" ", CUtility.getSun(10))); //Cutility为我操作PDF的一个工具类 
}
float[] widths = { 70, 95, 55, 95, 55, 90 };//
PdfPTable table = new PdfPTable(widths);  //确定每一列的宽度
table.setLockedWidth(true);  //锁定表格宽度  
int tableWidth = 0;
for (int i = 0; i < widths.length; i++)
tableWidth += widths[i];
table.setTotalWidth(tableWidth);  //设定表格总宽度
table.setHorizontalAlignment(Element.ALIGN_CENTER);  //设置表格内的内容水平居中

详细内容添加完之后想在表格下面接着画一个宽度一样的表格等分成三列

table = new PdfPTable(3);//设置一个三列的表格,均分
table.setTotalWidth(765);//设置表格总宽度 //不想均分也可以对每列进行设置table.setTotalWidth(new float[] { 200, 300, 265 });
//或者:table.setTotalWidth(765);table.setWidth(new int[]{200,300,265});
table.setLockedWidth(true);//设置锁定表格宽度

关于表格单元格常用API

PdfPCell pdfCell = new PdfPCell(); // 表格的单元格
pdfCell.setMinimumHeight(rowHeight);// 设置表格行高
pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
pdfCell.setRowspan(2);//合并2行
pdfCell.setColspan(2);//合并2列
pdfCell.setMinimumHeight(70);//设置最小高度
pdfCell.setBackgroundColor(BaseColor.ORANGE);//设置背景颜色
pdfCell.setBorder(Rectangle.NO_BORDER);//设置无边框
pdfCell.setBorder(0);//设置无边框

这篇博客介绍表格操作比较详细:https://blog.csdn.net/u010142437/article/details/84303581

如何给文字加下划线:

Chunk chunk = new Chunk("    " + num_1 + "   ");
chunk.setUnderline(0.1f, -2f);// 下划线
paragraph = new Paragraph("\r\n 以上共计 ", CUtility.getKai());
paragraph.add(chunk);

操作itextPDF的工具类

package com.common;

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.UUID; import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.pool.ServerInfo; public class CUtility {
private static final char[] numArray = { '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' };
private static final int fontSize = 12; public static final int UNIT_STEP = 4; // 单位进位,中文默认为4位即(万、亿)
public static final String[] CN_UNITS = new String[] { "个", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万" };
public static final String[] CN_CHARS = new String[] { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" }; /**
* 将阿拉伯数字转换为中文数字123=》一二三
*
* @param srcNum
* @return
*/
public static String getCNNum(int srcNum) {
String desCNNum = ""; if (srcNum <= 0)
desCNNum = "零";
else {
int singleDigit;
while (srcNum > 0) {
singleDigit = srcNum % 10;
desCNNum = String.valueOf(numArray[singleDigit]) + desCNNum;
srcNum /= 10;
}
} return desCNNum;
} /**
* 将日期转化为上中下旬
*
* @param inDate
* @return
*/
public static String get10DayClass(String inDate) {
String returnCode = "月下旬"; Calendar cal = Calendar.getInstance();
try {
cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(inDate));
} catch (ParseException e) {
e.printStackTrace();
}
int day = cal.get(Calendar.DATE);
if (day < 11)
returnCode = "月上旬";
else if (day < 21)
returnCode = "月中旬";
returnCode = cal.get(Calendar.YEAR) + "年" + String.valueOf(cal.get(Calendar.MONTH) + 1) + returnCode; return returnCode;
} /**
* 格式化KindEditor中输入的字符串,进行显示和输出
*
* @param content
* @return
*/
public static String formatEditorStr(String c8) {
c8 = c8.replaceAll(" ", "");
c8 = c8.replaceAll("\r", "");
c8 = c8.replaceAll("\n", "");
c8 = c8.replaceAll("<p>", "");
c8 = c8.replaceAll("</p>", "");
c8 = c8.replaceAll("<br/>", "\r\n");
return c8;
} /**
* 打印中的楷体
*
* @return
* @throws Exception
*/
public static Font getKai() throws Exception {
return getKai(fontSize, Font.NORMAL);
} public static Font getKai(int fontSize) throws Exception {
return getKai(fontSize, Font.NORMAL);
} public static Font getKai(int fSize, int fonStyle) throws Exception {
fSize = fSize > 0 ? fSize : fontSize;
return getFont(fSize, fonStyle, "simkai.ttf");
} /**
* 打印中的黑体
*
* @return
* @throws Exception
*/
public static Font getHei() throws Exception {
return getHei(fontSize, Font.NORMAL);
} public static Font getHei(int fontSize) throws Exception {
return getHei(fontSize, Font.NORMAL);
} public static Font getHei(int fSize, int fonStyle) throws Exception {
fSize = fSize > 0 ? fSize : fontSize;
return getFont(fSize, fonStyle, "simhei.ttf");
} /**
* 打印中的宋体
*
* @return
* @throws Exception
*/
public static Font getSun() throws Exception {
return getSun(fontSize, Font.NORMAL);
} public static Font getSun(int fontSize) throws Exception {
return getSun(fontSize, Font.NORMAL);
} public static Font getSun(int fSize, int fonStyle) throws Exception {
fSize = fSize > 0 ? fSize : fontSize;
return getFont(fSize, fonStyle, "simsun.ttc,1");
} /**
* 打印中的word字体
*
* @return
* @throws Exception
*/
public static Font getWSun() throws Exception {
return getWSun(fontSize, Font.NORMAL);
} public static Font geWSun(int fontSize) throws Exception {
return getWSun(fontSize, Font.NORMAL);
} public static Font getWSun(int fSize, int fonStyle) throws Exception {
fSize = fSize > 0 ? fSize : fontSize;
return getFont(fSize, fonStyle, "WINGDNG2.ttf");
} private static Font getFont(int fontSize, int fonStyle, String fontName) throws Exception {
BaseFont bfChinese = BaseFont.createFont(ServerInfo.getInstance().getFontPath() + fontName, BaseFont.IDENTITY_H,
BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, fontSize, fonStyle);
return fontChinese;
} /**
* 打印时需要的Cel
*
* @param content
* @param font
* @return
*/
public static PdfPCell getCell(String content, Font font) {
return getCell(content, font, 1, 1, 30);
} public static PdfPCell getCell(String content, Font font, int rowsSpan, int colsSpan) {
return getCell(content, font, rowsSpan, colsSpan, 30);
} public static PdfPCell getCell(String content, Font font, int rowsSpan, int colsSpan, int rowHeight) {
PdfPCell pdfCell = new PdfPCell(); // 表格的单元格
pdfCell.setMinimumHeight(rowHeight);// 设置表格行高
pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE); if (rowsSpan > 1)
pdfCell.setRowspan(rowsSpan);
if (colsSpan > 1)
pdfCell.setColspan(colsSpan);
pdfCell.setPhrase(new Paragraph(content, font)); return pdfCell;
} /**
* 格式化输出为Span标签
*
* @param title
* @param value
* @param type
* @return
*/
public static String setBadge(String title, String value, int type) {
String returnCode = " <span class='layui-badge";
switch (type) {
case 0:
returnCode += "'>";
break;// 赤
case 1:
returnCode += " layui-bg-orange'>";
break;// 橙
case 2:
returnCode += " layui-bg-green'>";
break;// 绿
case 3:
returnCode += " layui-bg-cyan'>";
break;// 青
case 4:
returnCode += " layui-bg-blue'>";
break;// 蓝
}
returnCode += "" + title + "" + value + "</span> ";
return returnCode;
} /**
* 获取本地中文货币显示样式
*
* @param currency
* @return
*/
public static String getLocalCurrency(String currency) {
double currcencyNum = 0;
try {
currcencyNum = Double.parseDouble(currency);
} catch (Exception e) {
}
return getLocalCurrency(currcencyNum);
} public static String getLocalCurrency(double currency) {
NumberFormat numberFormat = NumberFormat.getNumberInstance();
return "¥ " + numberFormat.format(currency);
} /**
* 获取系统当前时间
*
* @return
*/
public static String genCD() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
} /**
* 获取系统唯一码
*
* @return
*/
public static String genUUID() {
return UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
} /**
* 数值转换为中文字符串(口语化)
* @param isColloquial
* 是否口语化。例如12转换为'十二'而不是'一十二'。
* @return
*/
public static String cvt(long num, boolean isColloquial) {
String[] result = convert(num, isColloquial);
StringBuffer strs = new StringBuffer(32);
for (String str : result) {
strs.append(str);
}
return strs.toString();
} /**
* 将数值转换为中文
* @param isColloquial
* 是否口语化。例如12转换为'十二'而不是'一十二'。
* @return
*/
public static String[] convert(long num, boolean isColloquial) {
if (num < 10) {// 10以下直接返回对应汉字
return new String[] { CN_CHARS[(int) num] };// ASCII2int
} char[] chars = String.valueOf(num).toCharArray();
if (chars.length > CN_UNITS.length) {// 超过单位表示范围的返回空
return new String[] {};
} boolean isLastUnitStep = false;// 记录上次单位进位
ArrayList<String> cnchars = new ArrayList<String>(chars.length * 2);// 创建数组,将数字填入单位对应的位置
for (int pos = chars.length - 1; pos >= 0; pos--) {// 从低位向高位循环
char ch = chars[pos];
String cnChar = CN_CHARS[ch - '0'];// ascii2int 汉字
int unitPos = chars.length - pos - 1;// 对应的单位坐标
String cnUnit = CN_UNITS[unitPos];// 单位
boolean isZero = (ch == '0');// 是否为0
boolean isZeroLow = (pos + 1 < chars.length && chars[pos + 1] == '0');// 是否低位为0 boolean isUnitStep = (unitPos >= UNIT_STEP && (unitPos % UNIT_STEP == 0));// 当前位是否需要单位进位 if (isUnitStep && isLastUnitStep) {// 去除相邻的上一个单位进位
int size = cnchars.size();
cnchars.remove(size - 1);
if (!CN_CHARS[0].equals(cnchars.get(size - 2))) {// 补0
cnchars.add(CN_CHARS[0]);
}
} if (isUnitStep || !isZero) {// 单位进位(万、亿),或者非0时加上单位
cnchars.add(cnUnit);
isLastUnitStep = isUnitStep;
}
if (isZero && (isZeroLow || isUnitStep)) {// 当前位为0低位为0,或者当前位为0并且为单位进位时进行省略
continue;
}
cnchars.add(cnChar);
isLastUnitStep = false;
} Collections.reverse(cnchars);
// 清除最后一位的0
int chSize = cnchars.size();
String chEnd = cnchars.get(chSize - 1);
if (CN_CHARS[0].equals(chEnd) || CN_UNITS[0].equals(chEnd)) {
cnchars.remove(chSize - 1);
} // 口语化处理
if (isColloquial) {
String chFirst = cnchars.get(0);
String chSecond = cnchars.get(1);
if (chFirst.equals(CN_CHARS[1]) && chSecond.startsWith(CN_UNITS[1])) {// 是否以'一'开头,紧跟'十'
cnchars.remove(0);
}
}
return cnchars.toArray(new String[] {});
} }

itextPDF使用笔记的更多相关文章

  1. git-简单流程(学习笔记)

    这是阅读廖雪峰的官方网站的笔记,用于自己以后回看 1.进入项目文件夹 初始化一个Git仓库,使用git init命令. 添加文件到Git仓库,分两步: 第一步,使用命令git add <file ...

  2. js学习笔记:webpack基础入门(一)

    之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...

  3. SQL Server技术内幕笔记合集

    SQL Server技术内幕笔记合集 发这一篇文章主要是方便大家找到我的笔记入口,方便大家o(∩_∩)o Microsoft SQL Server 6.5 技术内幕 笔记http://www.cnbl ...

  4. PHP-自定义模板-学习笔记

    1.  开始 这几天,看了李炎恢老师的<PHP第二季度视频>中的“章节7:创建TPL自定义模板”,做一个学习笔记,通过绘制架构图.UML类图和思维导图,来对加深理解. 2.  整体架构图 ...

  5. PHP-会员登录与注册例子解析-学习笔记

    1.开始 最近开始学习李炎恢老师的<PHP第二季度视频>中的“章节5:使用OOP注册会员”,做一个学习笔记,通过绘制基本页面流程和UML类图,来对加深理解. 2.基本页面流程 3.通过UM ...

  6. NET Core-学习笔记(三)

    这里将要和大家分享的是学习总结第三篇:首先感慨一下这周跟随netcore官网学习是遇到的一些问题: a.官网的英文版教程使用的部分nuget包和我当时安装的最新包版本不一致,所以没法按照教材上给出的列 ...

  7. springMVC学习笔记--知识点总结1

    以下是学习springmvc框架时的笔记整理: 结果跳转方式 1.设置ModelAndView,根据view的名称,和视图渲染器跳转到指定的页面. 比如jsp的视图渲染器是如下配置的: <!-- ...

  8. 读书笔记汇总 - SQL必知必会(第4版)

    本系列记录并分享学习SQL的过程,主要内容为SQL的基础概念及练习过程. 书目信息 中文名:<SQL必知必会(第4版)> 英文名:<Sams Teach Yourself SQL i ...

  9. 2014年暑假c#学习笔记目录

    2014年暑假c#学习笔记 一.C#编程基础 1. c#编程基础之枚举 2. c#编程基础之函数可变参数 3. c#编程基础之字符串基础 4. c#编程基础之字符串函数 5.c#编程基础之ref.ou ...

随机推荐

  1. Openstack Nova 源码分析 — RPC 远程调用过程

    目录 目录 Nova Project Services Project 的程序入口 setuppy Nova中RPC远程过程调用 nova-compute RPC API的实现 novacompute ...

  2. [14]APUE:API for Mysql

    库:/usr/lib64/libmysqlclient.so.#.#... 头文件:/usr/lib64/mysql/mysql.h 一.建立连接 MYSQL *mysql_init(MYSQL *) ...

  3. 《DSP using MATLAB》Problem 8.46

    下雨了,大风降温,一地树叶,终于进入冬季了 代码: %% ----------------------------------------------------------------------- ...

  4. IK 用java 代码实现分词

    需要导入IK 对应的jar 包 IKAnalyzer2012.jar lucene-core-4.10.jar public static void main(String[] args) throw ...

  5. C#枚举转化示例大全,数字或字符串转枚举

    本文重点举例说明C#枚举的用法,数字转化为枚举.枚举转化为数字及其枚举数值的判断,以下是具体的示例: 先举两个简单的例子,然后再详细的举例说明: 字符串转换成枚举:DayOfWeek week=(Da ...

  6. 手动从零使用ELK构建一套搜索服务

    前言 这两天需要对接一个新的搜索业务,由于测试机器还没到位,所以就自己创造条件,通过在Windows上安装VM虚拟机,模拟整套环境,从而能快速进入核心业务的开发测试状态中. 系统环境安装配置 虚拟机V ...

  7. git提交流程简述

    1.初始化:一个项目只执行一次 只要有.git隐藏文件夹就ok了 git init 或者 git clone url 2.为远程github仓库生成别名(remote-name就是远程仓库的别名)这一 ...

  8. Spark运行架构设计

  9. sql (8) AVG

    SQL avg 语法SELECT AVG(column_name) FROM table_name新建表:StudentS S_id Grade Name phone1 98 小明 1234562 9 ...

  10. 校园商铺-4店铺注册功能模块-6店铺注册之Controller层的实现

    1. 从request请求获取获取相关的值 HttpservletRequest request代表的是客户端的请求.当客户端通过http协议访问服务器的时候,http请求头中的所有信息,都封装在这个 ...