java iTextPdf:动态更改单元格宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11996020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iTextPdf: Changing Cell Widths Dynamically
提问by AndroidDev
I'm building a table for a pdf using iTextPdf. Each page will have between 9 and 15 columns on it, the exact number not known until runtime. iTextPDF is really good creating equally sized columns across the page width. But what I can't figure out is how to create columns with different widths.
我正在使用 iTextPdf 为 pdf 构建一个表格。每个页面上将有 9 到 15 列,确切的数字直到运行时才知道。iTextPDF 非常适合在页面宽度上创建相同大小的列。但我想不通的是如何创建具有不同宽度的列。
I can't use a fixed column width, since I want to span the entire page width. Thus, when 9 columns are written, each column will necessarily be wider than when 12 or 15 columns are written. What is fixed is the relationship between these columns widths. To make up an example, I know that column A will always be 75% of the width of column B, which will always be 50% of the width of column C. I can determine this for every column.
我不能使用固定的列宽,因为我想跨越整个页面宽度。因此,当写入 9 列时,每列必然比写入 12 或 15 列时更宽。固定的是这些列宽之间的关系。举个例子,我知道 A 列始终是 B 列宽度的 75%,而 B 列始终是 C 列宽度的 50%。我可以为每一列确定这一点。
Anyone have any ideas for how to divide up the page to properly size these columns? Here is some code that I am using that creates equally sized columns. I need something else towards the end near
任何人都对如何划分页面以正确调整这些列的大小有任何想法?这是我正在使用的一些代码,用于创建大小相同的列。我需要其他的东西接近尾声
cell.setColspan(1);
cell.setColspan(1);
to change the width of the column, but not to a fixed value. Thank you!
更改列的宽度,但不是固定值。谢谢!
public static void newPDF() throws DocumentException, IOException {
PdfWriter writer;
Document document;
int cols = 9; //can be either 9, 12, or 15
document = new Document();
writer = PdfWriter.getInstance(document, new FileOutputStream("test.pdf"));
document.open();
document.add(createTable(cols));
document.close();
}
public static PdfPTable createTable(int cols) {
PdfPTable table = new PdfPTable(cols);
PdfPCell cell;
for (int i = 0; i < cols; i++) {
ph = selector.process("some text");
cell = new PdfPCell(ph);
cell.setColspan(1); //repeated 9, 12, or 15 times
table.addCell(cell);
}
return table;
}
回答by AndroidDev
I found the answer.
我找到了答案。
float[] columnWidths = new float[] {10f, 20f, 30f, 10f};
table.setWidths(columnWidths);
This code apportions the horizontal space of the columns in relative proportion to the values inside the brackets (e.g. col A is 1/2 the size of col b and 1/3 the size of col C).
此代码按与括号内的值的相对比例分配列的水平空间(例如,col A 是 col b 大小的 1/2 和 col C 大小的 1/3)。
Good example of this here: http://www.kodejava.org/examples/833.html
这里的好例子:http: //www.kodejava.org/examples/833.html
Thanks anyway!
不管怎么说,还是要谢谢你!