In Itext5, for setting position in a table, we typically use the following snippet,
public static void writeContentInTable(PdfWriter writer, PdfPTable pTable, int xPos, int yPos) {
try {
pTable.writeSelectedRows(0, -1, xPos, yPos, writer.getDirectContent());
} catch(Exception e) {
//Logging Errors
}
}
Now while migrating the code from Itext5 to Itext7, I'm facing the challenges to replicate the same. Could you suggest me to replicate the same? Can we replicate the same with the following classes.
com.itextpdf.layout.element.Table;
com.itextpdf.kernel.pdf.PdfWriter;
The purpose of PdfPTable.writeSelectedRows is to write a table at absolute positions.
In IText7 there is completely another way to specify absolute positions for a table via Table.setFixedPosition
Sets values for an absolute repositioning of the Element. The coordinates specified correspond to the bottom-left corner of the element and it grows upwards. Also has as a side effect that the Element's Property.POSITION is changed to fixed.
Your method can look like this:
public static void writeContentInTable(PdfWriter pdfWriter, Table table, int xPos, int yPos) {
try {
PdfDocument pdf = new PdfDocument(pdfWriter);
try (Document document = new Document(pdf)) {
table.setFixedPosition(xPos, yPos, table.getWidth());
document.add(table);
}
} catch(Exception e) {
//Logging Errors
}
}
Example to write a table to a certain position:
public class TestClass {
@Test
public void pdfTableTest() throws IOException {
PdfWriter pdfWriter = new PdfWriter("D:\\test.pdf");
Table table = createTableExample();
writeContentInTable(pdfWriter, table, 50, 500);
}
public static void writeContentInTable(PdfWriter pdfWriter, Table table, int xPos, int yPos) {
try {
PdfDocument pdf = new PdfDocument(pdfWriter);
try (Document document = new Document(pdf)) {
writeContentInTable(document, table, xPos, yPos);
}
} catch(Exception e) {
//Logging Errors
}
}
public static void writeContentInTable(Document document, Table table, int xPos, int yPos) {
table.setFixedPosition(xPos, yPos, table.getWidth());
document.add(table);
}
private Table createTableExample() {
Table table = new Table(3);
Cell cell = new Cell(1, 3)
.setTextAlignment(TextAlignment.CENTER)
.add("Cell with colspan 3");
table.addCell(cell);
cell = new Cell(2, 1)
.add("Cell with rowspan 2")
.setVerticalAlignment(VerticalAlignment.MIDDLE);
table.addCell(cell);
table.addCell("Cell 1.1");
table.addCell(new Cell().add("Cell 1.2"));
table.addCell(new Cell()
.add("Cell 2.1")
.setBackgroundColor(Color.LIGHT_GRAY)
.setMargin(5));
table.addCell(new Cell()
.add("Cell 1.2")
.setBackgroundColor(Color.LIGHT_GRAY)
.setPadding(5));
return table;
}
}