zoukankan      html  css  js  c++  java
  • 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[] {});  
        }
      
    }  
  • 相关阅读:
    630. Course Schedule III
    20151:补足程序1
    5w5:第五周程序填空题1
    621. Task Scheduler
    452. Minimum Number of Arrows to Burst Balloons
    435. Non-overlapping Intervals
    402. Remove K Digits
    406. Queue Reconstruction by Height
    376. Wiggle Subsequence
    122. Best Time to Buy and Sell Stock II
  • 原文地址:https://www.cnblogs.com/zengcongcong/p/11228532.html
Copyright © 2011-2022 走看看