4

我正在使用 iText 7.0.0(Java 风格),似乎表格单元格 Horizo​​ntalAlignment 被忽略了,因为 CENTER 和 RIGHT 都不起作用。你能重现这个吗?

看 pdf 屏幕截图

以及重现的代码:

private static void brokenTableCellHorizontalAlignmentPdf(OutputStream output) throws IOException {
    PdfWriter writer = new PdfWriter(output);
    PdfDocument pdf = new PdfDocument(writer);
    Document document = new Document(pdf);
    PdfFont font = PdfFontFactory.createFont(FontConstants.HELVETICA);
    Table table = new Table(new float[] {15f, 16f, 4f}).setWidthPercent(100);
    for (int y = 1; y <= 3; ++y) {
        for (int x = 1; x <= 3; ++x) {
            table.addCell(
                    new Cell()
                            .setVerticalAlignment(VerticalAlignment.MIDDLE)
                            .setHorizontalAlignment(HorizontalAlignment.CENTER)
                            .add(new Paragraph(String.format("(%d, %d)%s", y, x, x == 1 ? "\n\ntest" : ""))
                                    .setFont(font)
                                    .setFontSize(8)));
        }
    }
    document.add(table);
    document.close();
}
4

2 回答 2

7

请看一下CellAlignment示例:

public void createPdf(String dest) throws IOException {
    //Initialize PDF document
    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));

    // Initialize document
    Document document = new Document(pdf);
    Table table = new Table(new float[]{2, 1, 1});
    table.setWidthPercent(80);
    table.setHorizontalAlignment(HorizontalAlignment.CENTER);
    table.setTextAlignment(TextAlignment.CENTER);
    table.addCell(new Cell(1, 3).add("Cell with colspan 3"));
    table.addCell(new Cell(2, 1).add("Cell with rowspan 2")
        .setTextAlignment(TextAlignment.RIGHT));
    table.addCell("row 1; cell 1");
    table.addCell("row 1; cell 2");
    table.addCell("row 2; cell 1");
    table.addCell("row 2; cell 2");
    Cell cell = new Cell()
        .add(new Paragraph("Left").setTextAlignment(TextAlignment.LEFT))
        .add(new Paragraph("Center"))
        .add(new Paragraph("Right").setTextAlignment(TextAlignment.RIGHT));
    table.addCell(cell);
    cell = new Cell().add("Middle")
        .setVerticalAlignment(VerticalAlignment.MIDDLE);
    table.addCell(cell);
    cell = new Cell().add("Bottom")
        .setVerticalAlignment(VerticalAlignment.BOTTOM);
    table.addCell(cell);
    document.add(table);
    document.close();
}

运行此示例时生成的 PDF 如下所示:

在此处输入图像描述

对齐没有问题,垂直、水平或文本对齐都没有。

于 2016-07-31T12:26:45.657 回答
3

哦,没关系!在查看了另一个答案(指向http://gitlab.itextsupport.com/itext7/samples/blob/develop/publications/highlevel/src/main/java/com/itextpdf/highlevel/chapter05/C05E03_CellAlignment.java)之后,我们现在应该使用setTextAlignment. 如:

new Paragraph(String.format("(%d, %d)%s", y, x, x == 1 ? "\n\ntest" : ""))
    .setFont(font)
    .setFontSize(8)
    .setTextAlignment(TextAlignment.CENTER)
于 2016-07-31T12:20:54.953 回答