【问题标题】:align cell in itextpdf java在itextpdf java中对齐单元格
【发布时间】:2017-09-11 13:19:38
【问题描述】:

我正在使用 itextpdf 创建带有表格的 pdf。在创建表格时,我需要将某些列向右对齐,但它现在可以正常工作,你们能帮帮我吗?

我也尝试过谷歌搜索,但对我没有用。我使用的是 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();
    }        

}             `

【问题讨论】:

  • 有人投票结束了这个问题,也给了你一个反对票。但是,这是一个真正的问题,因此我投赞成票。不过,我建议将来阅读文档,因为我在回答中写的内容在很多地方都有记录。

标签: java itext pdf-generation


【解决方案1】:

您正在混合文本模式复合模式

这是文本模式

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 中自动从文本模式切换到复合模式。执行此操作后,将忽略在单元级别定义的某些属性。这解释了为什么您添加的内容没有右对齐。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-27
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 2022-11-28
    相关资源
    最近更新 更多