简体   繁体   中英

iText shrink table column to fit contents

In my iText document, I have a lot of tables scattered around, each with only one row of two columns. I would like to automatically shrink the leftmost column to fit its contents, and expand the rightmost column to fill the remaining space.

The exact contents of these two columns varies greatly, so there's no way to determine ahead of time what the exact width should be.

All of the content in this screenshot is wrapped in one outer table. Each nested table has its two columns highlighted red and blue. I would like to shrink the red columns as narrow as they can get without forcing the text to take up more lines than it has to. 嵌套表布局

In this case, the contents of the red cells are just a paragraph each, but it's possible they may contain a further-nested table with two cells of its own (which probably faces the same problem).

Is there a simple way to expand one column and shrink another without specifying exact or relative widths?

If you're using iText7 (and ditching the table for layout altogether), you can achieve this look and layout by building on the following example:

Output looks like this: 在此处输入图片说明

Code used to generate output above:

 public void createPdf(String dest) throws IOException, FileNotFoundException{
    PdfWriter writer = new PdfWriter(dest);
    PdfDocument pdfDoc = new PdfDocument(writer);
    Document doc = new Document(pdfDoc);

    Paragraph p = new Paragraph();

    Text t = new Text("Date:").setBold();
    p.add(t);
    t= new Text("10/12/17").setUnderline();
    p.add(t);
    p.add(new Tab());
    p.add(createTwoPartBorderedText("Catalog Year:   ","2017"));
    p.add(new Tab());
    p.add(createTwoPartBorderedText("L Number","2019284"));

    doc.add(p);

    doc.close();
}

public Paragraph createTwoPartBorderedText(String contentOne, String contentTwo){
    Paragraph container= new Paragraph();

    Text one = new Text(contentOne).setBold();
    Border solidRed = new SolidBorder(Color.RED,1f);
    one.setBorder(solidRed);
    container.add(one);

    Text two  =new Text(contentTwo);
    two.setUnderline();
    Border solidBlue = new SolidBorder(Color.BLUE,1f);
    two.setBorder(solidBlue);
    container.add(two);
    return container;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM