【问题标题】:set the table cell width in iText java pdf在 iText java pdf 中设置表格单元格宽度
【发布时间】:2013-02-08 17:35:02
【问题描述】:

我正在使用开源 http://itextpdf.com/ 来创建一些 pdf 。

我可以创建一个表格,但是所有列的宽度都相同,我需要更改特定列的宽度。

PdfPTable table = new PdfPTable(6);
Phrase tablePhrse = new Phrase("Sl n0", normalFontBold);
    PdfPCell c1 = new PdfPCell(tablePhrse);
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

我找不到任何方法来设置列的宽度,请建议一些方法来实现这一点..

【问题讨论】:

  • 你可以使用column.setPreferredWidth(100);
  • 我在 PdfTable 或 PdfCell 下找不到 .setPreferredWidth(100) 方法..
  • 对不起,我误会了。我认为您可以使用table.setTotalWidth(); table.setWidths();
  • 谢谢.. Setwidths 工作正常..

标签: java itext


【解决方案1】:

试试这个。

float[] columnWidths = new float[]{10f, 20f, 30f, 10f};
table.setWidths(columnWidths);

【讨论】:

  • 您认为您的代码与接受的答案相比有什么优势?
【解决方案2】:

你可以使用 setWidths() 方法。

table.setWidths(new int[]{200,50});

public void setWidths(int[] relativeWidths)

【讨论】:

  • 数组中的元素数必须与PdfPTable构造函数中定义的列数相同
  • @dellasavia:感谢您指出这一点,但这是一个示例。
  • 如果 col 是动态的,我只想设置第一个的宽度
【解决方案3】:

确保设置表格总宽度

// Set Column Number
PdfPTable table = new PdfPTable(2);

// Set Table Total Width
table.setTotalWidth(500);

// Set Each Column Width - Make Sure Array is the same number specified in constructor
table.setWidths(new int[]{50, 450});

【讨论】:

    【解决方案4】:
    float[] columnWidths = {1, 5, 5};
    
    // columnWidths = {column1, column2, column3...}
    
    PdfPTable table = new PdfPTable(columnWidths)
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
    【解决方案5】:

    如果table.setWidths(new int[]{200,50}); 不起作用,这里是更正的。

    innertable.setWidthPercentage(50);
    

    【讨论】: