itext pdf,下面包含图像和文本列表

use*_*541 2 pdf itext

需要帮助生成一个 pdf,其中包含图像列表和描述图像的文本。

尝试了下面的方法,但将图像和文本放在一起。请在这方面需要帮助。谢谢。

........

PdfPTable table = new PdfPTable(1);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.setSplitRows(true);
table.setWidthPercentage(90f);

Paragraph paragraph = new Paragraph();
for (int counter = 0; counter < empSize; counter++) { 
    String imgPath = ... ".png");
    Image img = Image.getInstance(imgPath);
    img.scaleAbsolute(110f, 95f);

    Paragraph textParagraph = new Paragraph("Test" + counter));
    textParagraph.setLeading(Math.max(img.getScaledHeight(), img.getScaledHeight()));
    textParagraph.setAlignment(Element.ALIGN_CENTER);

        Phrase imageTextCollectionPhase = new Phrase();
    Phrase ph = new Phrase();
    ph.add(new Chunk(img, 0, 0, true));
        ph.add(textParagraph);  

    imageTextCollectionPhase.add(ph);
    paragraph.add(imageTextCollectionPhase);
}

PdfPCell cell = new PdfPCell(paragraph);
table.addCell(cell);
doc.add(table);
Run Code Online (Sandbox Code Playgroud)

Bru*_*gie 5

我假设您想要得到如下所示的结果:

在此输入图像描述

在您的情况下,您将所有内容(所有图像和所有文本)添加到单个单元格中。您应该将它们添加到单独的单元格中,如MultipleImagesInTable示例中所做的那样:

public void createPdf(String dest) throws IOException, DocumentException {
    Image img1 = Image.getInstance(IMG1);
    Image img2 = Image.getInstance(IMG2);
    Image img3 = Image.getInstance(IMG3);
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    PdfPTable table = new PdfPTable(1);
    table.setWidthPercentage(20);
    table.addCell(img1);
    table.addCell("Brazil");
    table.addCell(img2);
    table.addCell("Dog");
    table.addCell(img3);
    table.addCell("Fox");
    document.add(table);
    document.close();
}
Run Code Online (Sandbox Code Playgroud)

您可以轻松更改此概念证明,以便使用循环。只需确保将addCell()方法放在循环而不是循环外。

您还可以显式创建一个PdfPCell并将文本和图像组合在同一单元格中,如下所示:

PdfPCell cell = new PdfPCell();
cell.addElement(img1);
cell.addElement(new Paragraph("Brazil"));
table.addCell(cell);
Run Code Online (Sandbox Code Playgroud)