使用itext在一个单元格中的同一行中的图像和文本

时间:2019-09-27 16:26:53

标签: java itext

我只想使用一个单元格在同一行中添加图像和文本。我可以在一个单元格中添加图像和文本,但是图像会出现在新行中,而不是在文本旁边

1 个答案:

答案 0 :(得分:0)

来自iText example的引用:

public static void main(String[] args) throws Exception {
    String dest = "sample.pdf";     
    String img1 = "sample.jpg";

    File file = new File(dest);
    file.getParentFile().mkdirs();

    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc);
    Table table = new Table(UnitValue.createPercentArray(new float[]{1, 2}));
    table.addCell(createImageCell(img1));
    table.addCell(createTextCell("Some Text"));
    doc.add(table);

    doc.close();
}

public static Cell createImageCell(String path) throws MalformedURLException {
    Image img = new Image(ImageDataFactory.create(path));
    img.setWidth(UnitValue.createPercentValue(100));
    Cell cell = new Cell().add(img);
    cell.setBorder(null);
    return cell;
}

public static Cell createTextCell(String text) {
    Cell cell = new Cell();
    Paragraph p = new Paragraph(text);
    p.setTextAlignment(TextAlignment.RIGHT);
    cell.add(p).setVerticalAlignment(VerticalAlignment.BOTTOM);
    cell.setBorder(Border.NO_BORDER);
    return cell;
}
相关问题