2017-04-15 48 views
0

我正在使用itextpdf創建與表格的pdf。在創建表格時,我需要將某個列對齊,但現在它正常工作,可以幫助我。在itextpdf中對齊單元格java

我試過Google搜索,但沒有爲我工作。即時通訊使用itextpdf 5.4版本。

public void generateMonthlySubReport(String[][] StrArray,String dueMonth,int Amt){ 
    try { 

     Document document = new Document(); 
     PdfWriter.getInstance(document, new FileOutputStream(MON_SUB_FILE));   
     PdfPTable pt = new PdfPTable(StrArray[0].length); 
     pt.setTotalWidth(new float[]{ 55,120,360,140}); 
     pt.setLockedWidth(true); 
     PdfPCell pcell = new PdfPCell(); 
     document.open();       
     addKvLogo(document); 
     Chunk glue = new Chunk(new VerticalPositionMark()); 
     Paragraph p1 = new Paragraph("Monthly Subscription Report",catFont); 
     p1.setAlignment(Element.ALIGN_CENTER); 
     addEmptyLine(p1,2); 
     document.add(p1); 
     Paragraph p2 = new Paragraph("Month : "+dueMonth); 
     p2.add(new Chunk(glue)); 
     p2.add("Per Member : Rs."+Amt);   
     addEmptyLine(p2,2); 
     document.add(p2); 

     for(int i=0;i<StrArray.length;i++){ 
      for(int j=0;j<StrArray[i].length;j++){ 
       pcell = new PdfPCell(); 
       if(i==0){ 
        pcell.setBackgroundColor(BaseColor.LIGHT_GRAY); 
       }else{ 
        pcell.setBackgroundColor(BaseColor.WHITE); 
       }      
       pcell.setUseAscender(true); 
       pcell.setMinimumHeight(22); 
       pcell.setPaddingLeft(10);      
       pcell.setHorizontalAlignment(Element.ALIGN_RIGHT); 
       pcell.setVerticalAlignment(Element.ALIGN_MIDDLE); 
       pcell.addElement(new Phrase(StrArray[i][j])); 
       pt.addCell(pcell); 
      } 
     }    
     pt.setTotalWidth(PageSize.A4.getWidth()-(document.leftMargin()*2)); 
     pt.setLockedWidth(true); 
     document.add(pt); 
     document.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    }   

}    ` 
+0

有人投票結束這個問題,並且還給了你一票。然而,這是一個真正的問題,因此我的投票權。不過,我會建議在將來閱讀文檔,因爲我在答覆中寫的內容在很多地方都有記錄。 –

回答

0

你混合文本模式複合模式

這是文本模式

pcell = new PdfPCell(new Phrase(StrArray[i][j])); 
pcell.setHorizontalAlignment(Element.ALIGN_RIGHT); 

在這種情況下,小區的對準將被用於文本的對準。

這是複合模式

pcell = new PdfPCell(); 
Paragraph p = new Parapgraph(StrArray[i][j]) 
p.setAlignment(Element.ALIGN_RIGHT); 
pcell.addElement(p); 

在這種情況下,小區的取向被忽略,有利於元件的對準。

如何知道文本模式和複合模式之間的區別?

使用addElement()方法時,iText在文本模式下自動從PdfPCell切換到複合模式。一旦你這樣做,在單元級定義的一些屬性將被忽略。這就解釋了爲什麼你添加的內容不是對齊的。