Search code examples
javaspring-bootpdfbox

How to create a table of this format in EasyTable


I want to have a single header in my case Notes rowspaning to multiple rows (2). When i am trying to code for the same, i am getting

rg.vandeseer.easytable.structure.Table$TableBuilder$TableSetupException: Number of table cells does not match with table setup. This could be due to row or col spanning not being correct. at org.vandeseer.easytable.structure.Table$TableBuilder.build(Table.java:223) ~[easytable-0.8.5.jar:na] at com.fedex.airops.pilot.bank.util.pdf.RollOverPDFAAPB.createSimplePDF(RollOverPDFAAPB.java:79) ~[classes/:na]

Can someone please tell me how can i code for the given sample Table using easy-table enter image description here


Solution

  • Here's a minimal working example for the structure from above:

    try (PDDocument document = new PDDocument()) {
        final PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);
    
        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
    
            // Build the table
            Table myTable = Table.builder()
                    .addColumnsOfWidth(20, 20, 20, 20, 20, 20, 20)
                    .padding(2)
                    .borderWidth(1)
                    .borderColor(Color.gray)
                    .horizontalAlignment(HorizontalAlignment.CENTER)
                    .addRow(Row.builder()
                            .add(TextCell.builder().text("a").colSpan(7).build())
                            .build())
                    .addRow(Row.builder()
                            .add(TextCell.builder().text("b").rowSpan(2).build())
                            .add(TextCell.builder().text("c").colSpan(3).build())
                            .add(TextCell.builder().text("d").colSpan(3).build())
                            .build())
                    .addRow(Row.builder()
                            .add(TextCell.builder().text("e").build())
                            .add(TextCell.builder().text("f").build())
                            .add(TextCell.builder().text("g").build())
                            .add(TextCell.builder().text("h").build())
                            .add(TextCell.builder().text("i").build())
                            .add(TextCell.builder().text("j").build())
                            .build())
                    .build();
    
            // Set up the drawer
            TableDrawer tableDrawer = TableDrawer.builder()
                    .contentStream(contentStream)
                    .startX(20f)
                    .startY(page.getMediaBox().getUpperRightY() - 20f)
                    .table(myTable)
                    .build();
    
            // And go for it!
            tableDrawer.draw();
        }
    
        document.save("example.pdf");
    }