我正在使用 itext 生成 pdf。现在,我想让paragrap与table对齐,我该怎么办?

I am using itext to generate pdf. Now , I want to make paragrap align same with table, what should Ido?

就像图像一样,我想让1和3与2对齐。table是默认对齐方式。 我该怎么办?

这是一个简单的方法,将两者添加到同一段落

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class ItextMain {
    public static final String DEST = "simple_table4.pdf";

    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        // file.getParentFile().mkdirs();
        new ItextMain().createPdf(DEST);
    }

    public void createPdf(String dest) throws IOException, DocumentException {
        Document document = new Document();

        PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();
        document.add(new Paragraph("1-Not aligned with table"));

        document.add(new Chunk());

        Paragraph p = new Paragraph();
        p.setIndentationLeft(20);// (20);

        PdfPTable table = new PdfPTable(4);
        for (int aw = 0; aw < 16; aw++) {
            table.addCell("hi");
        }
        table.setHorizontalAlignment(Element.ALIGN_LEFT);
        p.add(table);
        //document.add(table);

        p.add("3- Aligned with table");

        document.add(p);
        document.close();
    }
}

iText 5 PdfPTable class 有一个宽度百分比属性,它包含 table 将在页面中占据的宽度百分比。 默认情况下,此值为 80,结果 table 在页面上水平居中,即特别是缩进。

为防止这种情况,只需将百分比值设置为 100:

PdfPTable table = ...;
table.setWidthPercentage(100);

或者设置水平对齐方式:

table.setHorizontalAlignment(Element.ALIGN_LEFT);