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 ...
随机推荐
- 【牛客提高训练营5B】旅游
题目 吉老师的题时过一年还是不会做 从\(1\)号点出发经过每条边至少一次并且还要回到\(1\)号点,这跟欧拉回路的条件非常像,但是欧拉回路的实际上是"经过每一条边恰好一次并且回到出发点&q ...
- 《移山之道》第十一章:两人合作 读书笔记 PB16110698 第六周(~4.15)
本周在考虑阅读材料时,我翻阅了<移山之道>,正好看到这一章:两人合作,心想:正好,我们正值结对作业的紧要关头,书中两人合作的宝贵经验和教诲应当对我们有很大帮助.于是,我开始一边在ddl苦 ...
- myeclipse问题
eclipse使用过程中发现汉字太小,几乎不可辨识. 更改办法:eclipse界面依次选择“window”–“preference”–“general”–“appearance”–“color and ...
- await和async
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- NLP杂点
1.停用词 stop words: 在处理自然语言数据(或文本)之前或之后会自动过滤掉某些字或词. 停用词都是人工输入.或者由一个停用词表导入. 2.jieba是目前最好的 Python 中文分词组件 ...
- HTML样式链接到外部样式表
w3cschool链接:http://www.w3school.com.cn/html/html_css.asp <html> <head><link rel=" ...
- C++之控制内存分配
一.内存分配方式 在C++中,内存分成5个区,他们分别是堆.栈.自由存储区.全局/静态存储区和常量存储区.栈:在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时这些存储单元自动被释 ...
- Java学习 时间类 Period类与Duration类 / LocalDate类与Instant类 用法详解
前言 java 8 中引入的两个与日期相关的新类:Period 和 Duration.两个类看表示时间量或两个日期之间的差,两者之间的差异为:Period基于日期值,而Duration基于时间值.他们 ...
- Java怎样判断身份证号
判断身份证号是否正确使用的是正则,Java与js中使用正则的方式大差不差,下面是Java通过正则判断身份证号是否正确的 * */ @Test public void cardId() { System ...
- ArcGIS Server 10.x查询管理用户名和修改管理员密码
在x:\Program Files\ArcGIS\Server\tools\passwordreset下有个bat文件,用管理员用户运行它. PasswordReset -l PasswordRese ...