昨晚尋找了網上很多關於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(); } }