我必须使用 iText PDF 库创建一个表格。该表包含 3 列,并且可以有多行。在任何行中,任何字段都可以为空或可以有值。 我无法在 iText 中找到在特定列中创建单元格的方法。因此,如果任何条目为空,则发生的情况是,我下一列的数据将到达第一列。 代码片段 -
//Printing First column data
if (!attributes.getJSONObject(i).isNull("First")) {
PdfPCell cell = new PdfPCell(new Phrase(attributes.getJSONObject(i).getString("First"), h4));
table.addCell(cell);
}
//Printing Second column data
if (!attributes.getJSONObject(i).isNull("Second ")) {
PdfPCell cell = new PdfPCell(new Phrase(attributes.getJSONObject(i).getString("Second "), h4));
table.addCell(cell);
}
//Printing Third column data
if (!attributes.getJSONObject(i).isNull("Third")) {
PdfPCell cell = new PdfPCell(new Phrase(attributes.getJSONObject(i).getString("Third"), h4));
table.addCell(cell);
}
如果不明确检查所有可能的情况,我该如何处理这个问题?
为了使用 Apache POI 生成 Excel 表,我可以非常轻松地执行此操作,因为我可以在行中插入特定列的数据。我完成的 Excel 代码片段 -
//Printing First column data
if (!attributes.getJSONObject(i).isNull("First")) {
row.createCell(1); //This will insert in first column
row.getCell(1).setCellValue(attributes.getJSONObject(i).getString("First"));
}
//Printing Second column data
if(!attributes.getJSONObject(i).isNull("Second")) {
row.createCell(2); //This will insert in second column
row.getCell(2).setCellValue(attributes.getJSONObject(i).getString("Second"));
}
//Printing Third column data
if(!attributes.getJSONObject(i).isNull("Third")) {
row.createCell(3); //This will insert in third column
row.getCell(3).setCellValue(attributes.getJSONObject(i).getString("Third"));
}
iText 有什么办法可以实现这一点吗? (在特定列中插入数据)
最佳答案
IText 使用表格单元格来填充表格单元格。因此,您不能跳过空单元格。但在这种情况下,为什么不简单地添加内容为空的 Cell
实例呢?例如。仅仅代替
if(!attributes.getJSONObject(i).isNull("Second")) {
row.createCell(2); //This will insert in second column
row.getCell(2).setCellValue(attributes.getJSONObject(i).getString("Second"));
}
你可以做到
row.createCell(2); //This will insert in second column
if(!attributes.getJSONObject(i).isNull("Second")) {
row.getCell(2).setCellValue(attributes.getJSONObject(i).getString("Second"));
}
或者可能
row.createCell(2); //This will insert in second column
if(!attributes.getJSONObject(i).isNull("Second")) {
row.getCell(2).setCellValue(attributes.getJSONObject(i).getString("Second"));
} else {
row.getCell(2).setCellValue("");
}
关于java - iText : PDFPTable - Not able to insert data in specific column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46377374/