OpenPDF icon indicating copy to clipboard operation
OpenPDF copied to clipboard

How to remove the default width of PdfPTable?

Open weiZhenkun opened this issue 1 year ago • 1 comments

Describe the bug

How to remove the default width of table? How to keep the starting position of all nested tables at the same position as the red line in the following picture? I have set the seetings including setting the WidthPercentage of each table to 100. Each cell has no border, but it still doesn't work.

image

To Reproduce

UT code:

import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.IntStream;

public class TestWidth {
    @Test
    public void testCreateTable() throws IOException {
        Document document = new Document(PageSize.A4);
        PdfWriter.getInstance(document, Files.newOutputStream(Paths.get("test.pdf")));
        document.open();

        int tableNum = 30;

        PdfPTable[] tables = new PdfPTable[tableNum];

        IntStream.range(0, tableNum).forEach(index -> {
            PdfPTable table = getMainPdfPTable(1);
            table.addCell(getMainPdfPPCell(new Phrase("table_" + index)));
            tables[index] = table;
        });
        IntStream.range(0, tableNum - 1).forEach(index -> {
            tables[index].addCell(getMainPdfPPCell(tables[index + 1]));
        });
        document.add(tables[0]);
        document.close();
    }

    public static PdfPTable getMainPdfPTable(int numColumns) {
        PdfPTable table = new PdfPTable(numColumns);
        table.setWidthPercentage(100F);
        table.setLockedWidth(false);
        table.setSplitLate(false);
        table.setSplitRows(true);
        return table;
    }

    public static PdfPCell getMainPdfPPCell(Element element) {
        PdfPCell cell = new PdfPCell();
        cell.addElement(element);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setUseAscender(true);
        cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setBorder(Table.NO_BORDER);
        cell.setBorderWidth(Rectangle.NO_BORDER);
        return cell;
    }

}

weiZhenkun avatar Mar 05 '23 10:03 weiZhenkun

@weiZhenkun had a similar issue. Set alignment of table to Element.ALIGN_LEFT and add setPadding(0) to the cells, and it should work. Not sure why aligning the table left is needed, but this fixed a couple of similar issues in my project.

JohannesBeranek avatar Mar 14 '23 17:03 JohannesBeranek