昨晚尋找了網上不少關於IText表格居中問題,他們其中的有些代碼我即便複製上去生成的doc表格的文字都是不居中的,後來我本身找出了一種居中方式:java
爲PdfPCell對象添加paragraph對象,並將該paragraph設置爲居中:this
PdfPCell cell1 = new PdfPCell();
Paragraph para = new Paragraph("該單元居中");
//設置該段落爲居中顯示
para.setAlignment(1);
cell1.setPhrase(para);
table.addCell(cell1);spa
代碼親測無誤,所有代碼以下:code
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(); } }