itextpdf5操作表格

时间:2019-11-01
本文章向大家介绍itextpdf5操作表格,主要包括itextpdf5操作表格使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

下面是一些对表格排版的常用方法,是在制作pdf的时候通过查看ipa和一些博客积累下来的。

包括,表格的宽度,对齐方式,表的页眉页脚,前后间距,padding;

单元格对齐方式,线条设置,段落于单元格之间的间距,单元格里面的文本的行间距设置。

这些是通过查看ipa记录其中的一部份,还有很多已于理解的ipa没有记录。

package dbzx.pdf;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.junit.Test;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class AllTableMethod {
    
    @Test
    public void createTable() throws FileNotFoundException, DocumentException {
        String FONT = "C:/WINDOWS/Fonts/simsun.ttc,0";
        Font textFont = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED,10,Font.NORMAL,BaseColor.BLACK);
        String path = "E:/demo/pdfCreat/"+System.currentTimeMillis()+".pdf";//输出pdf的路径
        Document doc = new Document();
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.open();
        PdfPTable table = new PdfPTable(4);
        //设置控制
        table.setSpacingBefore(40);//表格前间距
        table.setSpacingAfter(100);//表格后间距
        table.setWidthPercentage(80);//表格宽占page比例
        table.setHorizontalAlignment(Element.ALIGN_LEFT);//表格水平对齐方式
       /*
        *      设置构成标题的顶部行数。只有当表被添加到文档并且表跨页时,这个header才有意义。
        */
        
        table.setHeaderRows(2);
        /*
         *     设置页脚要使用的行数。页脚的数量从页眉行中减去。例如,对于一个有两个页眉行和一个页脚行的表,代码应该是:
         *    table.setHeaderRows (3);
         *    table.setFooterRows (1);
         *    第0行和第1行是页眉行,第2行是页脚行。
         */
        table.setFooterRows(1);
        table.setPaddingTop(10f);//设置表格顶部padding
        //设置单元格
        /**
         * getDefaultCell()得到的Cell代表所有不是table.add(PdfPCell)的Cell。例:table.add(new Paragraph("test")).
         */
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);//单元格中文字垂直对齐方式
        table.getDefaultCell().setBorderColor(BaseColor.WHITE);//单元格线条颜色
        table.getDefaultCell().setMinimumHeight(30);//单元格最小高度
        table.getDefaultCell().setExtraParagraphSpace(5);//段落文字与表格之间的距离,底部距离
        table.getDefaultCell().setLeading(15, 0);//设置行间距
//        table.getDefaultCell().setFixedHeight(20f);//表格固定高度
        for(int i=0;i<16;i++) {
            table.addCell(new Paragraph("test"));
        }
        doc.add(table);
        doc.close();
        
    }
}

原文地址:https://www.cnblogs.com/whalesea/p/11776463.html