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();
        
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM