JAVA中iText生成PDF的基本使用

iText是一个能够快速产生PDF文件的java类库。iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的。

1.表单打印事例:

/**
 * Itext 的基本使用
 * 内容注释
 *
 * Document : PDF对象
 * Rectangle :页面对象
 * Table、PdfPTable : 表格对象
 * Phrase短语对象 : a List of Chunks with leading
 * Paragraph : a Phrase with extra properties and a newline ,新段落另起一行
 * PdfPCell :单元格对象
 *
 * Created by llh on 2018-04-26
 */
public class testPdfFour {

    public static void main(String[] args) throws Exception {
        List<Dish> menu = Arrays.asList(
                new Dish("porkrrrrrrrrrrrrrrr", false, 800, Dish.Type.MEAT),
                new Dish("beef", false, 700, Dish.Type.MEAT),
                new Dish("chicken", false, 400, Dish.Type.MEAT),
                new Dish("french fries", true, 530, Dish.Type.OTHER),
                new Dish("rice", true, 350, Dish.Type.OTHER),
                new Dish("season fruit", true, 120, Dish.Type.OTHER),
                new Dish("pizza", true, 550, Dish.Type.OTHER),
                new Dish("prawns", false, 300, Dish.Type.FISH),
                new Dish("salmon", false, 450, Dish.Type.FISH));
        //        float[] widths = {144, 113, 191};
        //写出文件的位置
        FileOutputStream fos = new FileOutputStream("testPdfFour--.pdf");

        //1-创建文本对象 Document
        Document document = new Document();
//        document = new Document(PageSize.A4.rotate());// 横向打印

        //为pdf添加属性信息 (添加的属性测试没找到在哪体现,有知道的可告知 谢谢)
//        document.addAuthor("作者llh");
//        document.addTitle("标题llh");
//        document.addSubject("主题llh");
//        document.addKeywords("关键字llh");

        //设置纸张(A4)
        document.setPageSize(PageSize.A4);
        //设置左,右,上,下边距
        document.setMargins(30, 30, 50, 30);

        // 2-初始化 pdf输出对象 PdfWriter
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        //设置PDF文档外观,可不设置(未测出效果)
        writer.setViewerPreferences(PdfWriter.PageModeUseThumbs);  //PdfWriter.PageModeUseThumbs – 缩略图可见

        Float pageHeight = PageSize.A4.getHeight();
        Float pageWidth = PageSize.A4.getWidth();
        System.out.println("page高度=" + pageHeight + ",  宽度" + pageWidth + "  ---document--" + document.getPageSize());

        // 3-打开 Document
        document.open();

        //BaseFont-确认支持中文
        BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

        //设置字体
        Font fontChinese = new Font(bfChinese, 20, Font.NORMAL);

        PdfPTable table1 = new PdfPTable(1);

        String content = "凭证表单";
        Paragraph pagragraph = new Paragraph(content, fontChinese);  //Paragraph : a Phrase with extra properties and a newline
       /* //设置段落属性 (未测试)
        pagragraph.setAlignment(Element.ALIGN_JUSTIFIED);// 对齐方式

        pagragraph.setIndentationLeft(12);// 左缩进
        pagragraph.setIndentationRight(12);// 右缩进
        pagragraph.setFirstLineIndent(24);// 首行缩进

        pagragraph.setLeading(20f);// 行间距
        pagragraph.setSpacingBefore(5f);// 设置上面空白
        pagragraph.setSpacingAfter(10f);// 设置段落下空白*/

        //        PdfPCell cell = new PdfPCell();
        //        Paragraph p = new Paragraph("table title");
        //        p.setAlignment(1);
        //        p.setSpacingBefore(15f);
        //        cell.addElement(p);
        //        cell.setBorder(0);

        PdfPCell cell = new PdfPCell(pagragraph);
        cell.setHorizontalAlignment(Paragraph.ALIGN_CENTER); //设置水平位置
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//设置垂直位置
        //        table1.setTotalWidth(458);
        table1.setHorizontalAlignment(Element.ALIGN_LEFT);
        table1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        table1.addCell(cell);
        // table1.addCell(createCell("table title sample",14,bfChinese,null,Paragraph.ALIGN_RIGHT,null)); //封装方法

        List<String> headerList = Arrays.asList(new String[] { "名字", "vegetarian", "calories" }); //打印内容中表格的表头

        for (int i = 0; i < menu.size(); i++) {
            PdfPTable tableHeader = new PdfPTable(3);
            //设置宽度
            tableHeader.setWidthPercentage(100);
            tableHeader.setHorizontalAlignment(Element.ALIGN_CENTER);

            PdfPTable tableContent = new PdfPTable(new float[] { 144, 113, 191 });
            //        table2.setTotalWidth(458);
            tableContent.setWidthPercentage(100);
            tableContent.setHorizontalAlignment(Element.ALIGN_CENTER);
            //表头
            for (int k = 0; k < headerList.size(); k++) {
                tableContent.addCell(createCell(headerList.get(k) + " " + i, 14, bfChinese, null, null, null));
            }

            //内容不满6行,填充空格到6行
            for (int j = 0; j < 6; j++) {
                if (j > 0) {
                    for (int col = 0; col < 3; col++) {
                        tableContent.addCell(createCell(" ", 14, bfChinese, null, null, null));
                    }
                    continue;
                }
                tableContent.addCell(createCell(menu.get(i).getName(), 14, bfChinese, null, null, null));
                tableContent.addCell(createCell(menu.get(i).isVegetarian() + "", 14, bfChinese, null, null, null));
                tableContent.addCell(createCell(menu.get(i).getCalories() + "", 14, bfChinese, null, null, null));

            }

            //开始测试时demo内容
            //        for(int i = 0; i < menu.size(); i++) {
            //            for(int j = 0; j < headerList.size(); j++) {
            //                PdfPCell pdfCell = new PdfPCell(); //表格的单元格
            //                if(headerList.get(j).equals("名字")){
            ////                    String content = menu.get(i).getName();
            ////                    Paragraph paragraph = new Paragraph(content, getPdfChineseFont());
            ////                    pdfCell.setPhrase(paragraph);
            //                    table2.addCell(createCell(menu.get(i).getName(),14,bfChinese,null,null,null));
            //                }else if(headerList.get(j).equals("vegetarian")){
            ////                    String content = menu.get(i).isVegetarian()+"";
            ////                    Paragraph paragraph = new Paragraph(content, getPdfChineseFont());
            ////                    pdfCell.setPhrase(paragraph);
            //                    table2.addCell(createCell(menu.get(i).isVegetarian()+"",14,bfChinese,null,null,null));
            //                }else if(headerList.get(j).equals("calories")){
            ////                    String content = menu.get(i).getCalories()+"";
            ////                    Paragraph paragraph = new Paragraph(content, getPdfChineseFont());
            ////                    pdfCell.setPhrase(paragraph);
            //                    table2.addCell(createCell(menu.get(i).getCalories()+"",14,bfChinese,null,null,null));
            //                }
            //
            //            }

            PdfPTable table = new PdfPTable(1);

            PdfPCell c1 = new PdfPCell();
            c1.setBorder(0);
            c1.addElement(table1);

            PdfPCell c3 = new PdfPCell();
            c3.setBorder(0);
            c3.addElement(tableHeader);

            PdfPCell c2 = new PdfPCell();
            c2.setBorder(0);
            c2.addElement(tableContent);

            //将子表格按顺序全部添加到父表格中
            table.addCell(c1);
            table.addCell(c3);
            table.addCell(c2);

            //设置每页打印两个父表格内容(账单),达到两个就新建一页
            if (i >= 2 && (i % 2 == 0)) {
                document.newPage(); //新建一页
            }
            table.setSpacingAfter(60f);//设置表格下面空白

            //添加水印
            PdfContentByte under = writer.getDirectContentUnder();
            //            PdfContentByte under = writer.getDirectContent();

            //打开设置水印的文本
            under.beginText();
            //BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            under.setFontAndSize(bfChinese, 18);
            //             under.setTextMatrix(30, 30);
            under.showTextAligned(Element.ALIGN_LEFT, "水印.......summer........", 230, 660, 45);

            under.showTextAligned(Element.ALIGN_LEFT, "水印.......summer........", 230, 240, 45);

            //设置透明度 (暂未测出效果)
            //            PdfGState gstate = new PdfGState();
            //            gstate.setStrokeOpacity(0.1f);
            //            under.setGState(gstate);

            //关闭设置水印的文本
            under.endText();

            //写入绝对位置时不需要添加document.add(table)
            table.setTotalWidth(pageWidth - 60);
            if (i % 2 == 0) {
                PdfContentByte tContent = writer.getDirectContent(); //-得到层
                table.writeSelectedRows(0, -1, 0, -1, 30, 782, tContent); //-写入绝对位置
            } else {
                PdfContentByte tContent = writer.getDirectContent(); //-得到层
                table.writeSelectedRows(0, 11, 0, -1, 30, 351, tContent); //-写入绝对位置
            }
            System.out.println("table--总宽度--" + table.getTotalWidth());

            /**往 Document 添加内容 , 写入绝对位置时不需要添加document.add(table),不然会重复打印 */
            //  document.add(table); //pdf文档中加入table2

        }

        // 关闭 Document
        document.close();

    }

    //    /**
    //     * 设置字体
    //     * @return
    //     * @throws Exception
    //     */
    //    public static Font getPdfChineseFont() throws Exception {
    //        BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",
    //                BaseFont.NOT_EMBEDDED);
    //        Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);
    //        return fontChinese;
    //    }

    /**
     *
     * @param content 内容
     * @param fontsize 字体大小
     * @param font 字体
     * @param colspan 列合并单元数量
     * @param align 排列方式
     * @param borderColor 边框颜色
     * @return
     */
    private static PdfPCell createCell(String content, int fontsize, BaseFont font, Integer colspan, Integer align, BaseColor borderColor) {
        Paragraph pagragraph = new Paragraph(content, new Font(font, fontsize));
        PdfPCell cell = new PdfPCell(pagragraph);
        cell.setFixedHeight(30);
        cell.setNoWrap(true);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 上中下,Element对象
        if (align != null)
            cell.setHorizontalAlignment(align);
        if (colspan != null && colspan > 1)
            cell.setColspan(colspan);
        if (borderColor != null)
            cell.setBorderColor(borderColor);
        //        if (bgColor != null)
        //            cell.setBackgroundColor(bgColor);
        return cell;
    }

}

打印效果:

图片.png

2.PDF单元格操作(合并单元格方式):

/**
 * Created by llh on 2018-04-28
 */
public class pdfCol {
    public static void main(String[] args) throws Exception {
        insertTable();
    }

    public static void insertTable() throws Exception {

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        FileOutputStream fos = new FileOutputStream("pdfCol合并单元格.pdf");
        // 使用PDFWriter进行写文件操作
        PdfWriter.getInstance(document, fos);
        document.open();

        // 中文字体(现在高版本的不支持中文包)
        BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);// 中文、12、正常

        int colNumber = 6;

        // PdfPTable[PdfPTable[PdfPCell[Paragraph]]]
        // 创建有6列的表格
        PdfPTable datatable = new PdfPTable(colNumber);
        // 定义表格的宽度
        int[] cellsWidth = {1, 1, 1, 1, 1, 1};
        datatable.setWidths(cellsWidth);// 单元格宽度
        // datatable.setTotalWidth(300f);//表格的总宽度
        datatable.setWidthPercentage(100);// 表格的宽度百分比

        datatable.getDefaultCell().setPadding(2);// 单元格的间隔
        datatable.getDefaultCell().setBorderWidth(2);// 边框宽度
        // 设置表格的底色
        datatable.getDefaultCell().setBackgroundColor(BaseColor.GREEN);
        datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

//         PdfPTable[PdfPCell[Paragraph]]
        String[] tableHeader = new String[]{"a","b","c","d","e","f"};
        String[] tableCont = new String[]{"1","2","3","4","5","6"};
        // 添加表头元素
        for (int i = 0; i < colNumber; i++) {
            datatable.addCell(new Paragraph(tableHeader[i], fontChinese));
        }
        // 添加表格的内容
        for (int i = 0; i < colNumber; i++) {
            datatable.addCell(new Paragraph(tableCont[i], fontChinese));
        }

        // 空白表格
        for (int i = 0; i < colNumber; i++) {
            PdfPCell cell = new PdfPCell(new Paragraph(""));
            cell.setFixedHeight(10);// 单元格高度
            datatable.addCell(cell);
        }
        datatable.setSpacingAfter(40f);// 设置表格下面空白行
        document.add(datatable);// 把表格加入文档

        // 跨行跨列表格
        PdfPTable table = new PdfPTable(5); // 3列表格
        PdfPCell cell; // 单元格
//        cell = new PdfPCell(new Phrase("跨5列", fontChinese));
//        cell.setColspan(5);// 跨3列
//        table.addCell(cell);

        cell = new PdfPCell(new Phrase("跨2行", fontChinese));
        cell.setRowspan(2);// 跨2行
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("a跨2列", fontChinese));
        cell.setColspan(2);// 跨3列
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("b跨2列", fontChinese));
        cell.setColspan(2);// 跨3列
        table.addCell(cell);
        table.addCell("row 1; cell 1");
        table.addCell("row 1; cell 2");
        table.addCell("row 2; cell 1");
        table.addCell("row 2; cell 2");

        document.add(table);

//        // 表格的嵌套
        PdfPTable tableFather = new PdfPTable(4);
        tableFather.setSpacingBefore(20f);// 设置表格上面空白行
        // 1行2列
        PdfPTable nested1 = new PdfPTable(2);
        nested1.addCell("1.1");
        nested1.addCell("1.2");
        // 2行1列
        PdfPTable nested2 = new PdfPTable(1);
        nested2.addCell("2.1");
        nested2.addCell("2.2");

        // 将表格插入到指定位置
        for (int k = 0; k < 12; ++k) {
            if (k == 1) {
                tableFather.addCell(nested1);
            } else if (k == 6) {
                tableFather.addCell(nested2);
            } else {
                tableFather.addCell("cell " + k);
            }
        }
        document.add(tableFather);

        document.close();
    }
}

单元格效果:


图片.png

附:用到对象(Dish)

public class Dish {

    private final String name;
    private final boolean vegetarian;
    private final int calories;
    private final Type type;
    private List list;

    public List getList() {
        return list;
    }

    public void setList(List list) {
        this.list = list;
    }

    public Dish(String name, boolean vegetarian, int calories, Type type) {
        this.name = name;
        this.vegetarian = vegetarian;
        this.calories = calories;
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public boolean isVegetarian() {
        return vegetarian;
    }

    public int getCalories() {
        return calories;
    }

    public Type getType() {
        return type;
    }

    @Override
    public String toString() {
        return name;
    }

    public enum Type { MEAT, FISH, OTHER }


}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容