itextPDF使用笔记
最近在做报表打印,使用的是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使用笔记的更多相关文章
- git-简单流程(学习笔记)
这是阅读廖雪峰的官方网站的笔记,用于自己以后回看 1.进入项目文件夹 初始化一个Git仓库,使用git init命令. 添加文件到Git仓库,分两步: 第一步,使用命令git add <file ...
- js学习笔记:webpack基础入门(一)
之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...
- SQL Server技术内幕笔记合集
SQL Server技术内幕笔记合集 发这一篇文章主要是方便大家找到我的笔记入口,方便大家o(∩_∩)o Microsoft SQL Server 6.5 技术内幕 笔记http://www.cnbl ...
- PHP-自定义模板-学习笔记
1. 开始 这几天,看了李炎恢老师的<PHP第二季度视频>中的“章节7:创建TPL自定义模板”,做一个学习笔记,通过绘制架构图.UML类图和思维导图,来对加深理解. 2. 整体架构图 ...
- PHP-会员登录与注册例子解析-学习笔记
1.开始 最近开始学习李炎恢老师的<PHP第二季度视频>中的“章节5:使用OOP注册会员”,做一个学习笔记,通过绘制基本页面流程和UML类图,来对加深理解. 2.基本页面流程 3.通过UM ...
- NET Core-学习笔记(三)
这里将要和大家分享的是学习总结第三篇:首先感慨一下这周跟随netcore官网学习是遇到的一些问题: a.官网的英文版教程使用的部分nuget包和我当时安装的最新包版本不一致,所以没法按照教材上给出的列 ...
- springMVC学习笔记--知识点总结1
以下是学习springmvc框架时的笔记整理: 结果跳转方式 1.设置ModelAndView,根据view的名称,和视图渲染器跳转到指定的页面. 比如jsp的视图渲染器是如下配置的: <!-- ...
- 读书笔记汇总 - SQL必知必会(第4版)
本系列记录并分享学习SQL的过程,主要内容为SQL的基础概念及练习过程. 书目信息 中文名:<SQL必知必会(第4版)> 英文名:<Sams Teach Yourself SQL i ...
- 2014年暑假c#学习笔记目录
2014年暑假c#学习笔记 一.C#编程基础 1. c#编程基础之枚举 2. c#编程基础之函数可变参数 3. c#编程基础之字符串基础 4. c#编程基础之字符串函数 5.c#编程基础之ref.ou ...
随机推荐
- 【工具原则】5W2H法学习笔记
目录 问题描述 事件(原因)描述 任务描述 方案决策 小结 5W2H法又叫七问分析法,是二战中美国陆军兵器修理部首创.按事务构成要素,从规范的七个方面思考,避免疏忽遗漏. 可以应用在:问题描述.事件描 ...
- 分享一套高级Java笔试题(实拍高清图)
分享一套高级Java笔试题 微信群里群友分享的 刚好他在笔试 有些问题不会发到群里求助 如果你最近正好在面试 需要参考需要提升 这套试题或许对你有用 下面是部分分享原图 下面是微信群中群友的热议 非常 ...
- 人脸识别-常用的数据库Face Databases From Other Research Groups
Static/Videos Static Single/Multiple faces Single? Gray/Color Color Resolution Vaious Face pose Fron ...
- FCC知识点总结
1.DOMContentLoaded事件 2.延迟脚本 defer 3.异步脚本async 4.[找最长单词]—— 找出句子中最长的单词,并返回它的长度. 5.数组slice().splice() s ...
- 使用CompletionService批处理任务(线程池阻塞线程)
CompletionService ExecutorService BlockingQueueFuture 如果你向Executor提交了一个批处理任务,并且希望在它们完成后获得结果.为此你可以保存与 ...
- JavaScript - DOM相关
DOM节点分类 ( node ) : 元素节点 ( element node ) 属性节点 ( attribute node ) 文本节点 ( text node) DOM的相关操作 : 1. 查询元 ...
- 配置文件一applicationContext.xml
p命名空间注入 需要引入xmlns:p="http://www.springframework.org/schema/p" p命名空间注入的特点是使用属性而不是子元素的形式配置Be ...
- 概率dp——期望水题hdu4405
还是逆推,如果遇到跳板直接继承目标地的期望即可 #include<bits/stdc++.h> using namespace std; #define maxn 200005 doubl ...
- 深入浅出写一个多级异步回调从基础到Promise实现的Demo
今天一时兴起,写了一个渐进升级的异步调用demo,记录一下. 1. 最基础的同步调用 //需求:f2在f1之后执行,且依赖f1的返回值.如下: function f1(){ var s="1 ...
- ie9 jscript7 内存不足 页面无响应
花了我差不多一天时间 我是加载一个datagrid ,多表联查,查询几遍(不一定,又是1遍就死了)后 就卡死了...后台日志都是过的.... 后来我发现数据库某个表的数据很多有一模一样的两条,把一份删 ...