itextPDF使用笔记

摘要:
最近,我使用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 };// 460
 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("
    以上共计  ", 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("
", "");
        c8 = c8.replaceAll("
", "");
        c8 = c8.replaceAll("<p>", "");
        c8 = c8.replaceAll("</p>", "");
        c8 = c8.replaceAll("<br/>", "
");
        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使用笔记》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇oracle数据库常见案例_oracleFlask基础知识下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

C# PropertyGrid控件应用心得

最近项目中做一模块时偶发奇想,希望使用propertygrid的控件实现类似visual studio的属性样式,于是拿来一用,发现还真不是自己想象的那么简单,如果要实现一个比较好的展示,还真的需要不少技巧,通过自己的实践和网络的力量,“逢山开道,遇水搭桥”,总算是摸出一些门道,不敢私藏,拿出来与大家分享,呵呵。 先来转一个基础的,源自msdn http:...

Jackson 通过自定义注解来控制json key的格式

Jackson 通过自定义注解来控制json key的格式 最近我这边有一个需求就是需要把Bean中的某一些特殊字段的值进行替换。而这个替换过程是需要依赖一个第三方的dubbo服务的。为了使得这个转换功能更加的通用,我们采用了下面的方式: client端使用自定义的注解(假设为@Dimension)标记Bean中所有的「特殊字段」 client端把bea...

Android Learning:数据存储方案归纳与总结

前言 最近在学习《第一行android代码》和《疯狂android讲义》,我的感触是Android应用的本质其实就是数据的处理,包括数据的接收,存储,处理以及显示,我想针对这几环分别写一篇博客,记得我的学习心得,也希望跟各位新手同学相互努力促进。今天这篇博客,我想介绍一下数据的存储,因为数据的接收,存储,处理以及显示这几环环环相扣,而数据的存储直接关系到...

Scala入门系列(十一):模式匹配

引言 模式匹配是Scala中非常有特色,非常强大的一种功能。 类似于Java中的switch case语法,但是模式匹配的功能要比它强大得多,switch只能对值进行匹配,但是Scala的模式匹配除了可以对值进行匹配之外,还可以对类型进行匹配、对Array和List的元素情况进行匹配、对case class进行匹配甚至对有值或没值(Option)进行匹配...

华为机试 计算字符个数

题目描述 写出一个程序,接受一个由字母和数字组成的字符串,和一个字符,然后输出输入字符串中含有该字符的个数。不区分大小写。 输入描述: 第一行输入一个有字母和数字以及空格组成的字符串,第二行输入一个字符。 输出描述: 输出输入字符串中含有该字符的个数。 示例1 输入 ABCDEF A 输出 1 sing System; using Syste...

springboot整合amazonS3,封装上传文件接口

1.在pom.xml中引入amazonS3的依赖。 <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-s3</artifactId>...