2017-04-15 49 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切换到复合模式。一旦你这样做,在单元级定义的一些属性将被忽略。这就解释了为什么你添加的内容不是对齐的。