IText PdfPTable表格 單元的居中顯示


昨晚尋找了網上很多關於IText表格居中問題,他們其中的有些代碼我即使復制上去生成的doc表格的文字都是不居中的,后來我自己找出了一種居中方式:

為PdfPCell對象添加paragraph對象,並將該paragraph設置為居中:

    PdfPCell cell1 = new PdfPCell();
        Paragraph para = new Paragraph("該單元居中");
        //設置該段落為居中顯示
        para.setAlignment(1);
        cell1.setPhrase(para);
        table.addCell(cell1);

 

代碼親測無誤,全部代碼如下:

import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.rtf.RtfWriter2;

import java.io.FileOutputStream;

/**
 * PdfPTable的使用方法,表格居中問題
 * User: HYY
 * Date: 13-8-1
 * Time: 下午9:54
 * To change this template use File | Settings | File Templates.
 */
public class PdfpTableTest {
    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // 創建word文檔,並設置紙張的大小
        Document document = new Document(PageSize.A4);
        //設置存放位置
        RtfWriter2.getInstance(document, new FileOutputStream("C:/1.doc"));
        document.open();

        //生成三列表格
        PdfPTable table = new PdfPTable(3);
        //設置表格具體寬度
        table.setTotalWidth(90);
        //設置每一列所占的長度
        table.setWidths(new float[]{50f, 15f, 25f});


        PdfPCell cell1 = new PdfPCell();
        Paragraph para = new Paragraph("該單元居中");
        //設置該段落為居中顯示
        para.setAlignment(1);
        cell1.setPhrase(para);
        table.addCell(cell1);

        table.addCell(new PdfPCell(new Phrase("無幽之路IText教程")));
        table.addCell(new PdfPCell(new Phrase("無幽之路IText教程")));

        document.add(table);

        document.close();
    }

}

 


免責聲明!

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



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