Hi,
I will be sharing Java code for all those developers who are looking for codes to use in their application. As I use Aspose Library for developing my PDF application, the code I will be sharing require Aspose Library but if you don’t want to use any third party tool/library you can just get an idea from the code how to perform that operation on a document.

Today I am sharing a code for adding image in table cell of PDF document in java code:

Java Code

Code:
 //Instantiate a Pdf object by calling its empty constructor
        Pdf pdf1 = new Pdf();

        //Create a section in the Pdf object
        Section sec1 = pdf1.getSections().add();

        //Instantiate a table object
        Table table = new Table(sec1);
        //Add the table in paragraphs collection of the desired section
        sec1.getParagraphs().add(table);
        //Set with column widths of the table
        table.setColumnWidths("100 100 120");

        //Set table border using another customized BorderInfo object
        table.setDefaultCellBorder(new BorderInfo(BorderSide.All.getValue(), 1F));

        //Create an image object in the section
        aspose.pdf.Image img1 = new aspose.pdf.Image(sec1);
        //Set the path of image file
        img1.getImageInfo().setFile("d:/pdftest/Aspose.jpg");

        img1.setImageWidth(100);
        img1.setImageHeight(200);

        //Create rows in the table and then cells in the rows
        Row row1 = table.getRows().add();
        row1.getCells().add("Sample text in cell");
        // Add the cell which holds the image
        Cell cell2 = row1.getCells().add();
        
        //Add the image to the table cell
        cell2.getParagraphs().add(img1);

        row1.getCells().add("Previous cell with image");
        row1.getCells().getCell(2).setVerticalAlignment(VerticalAlignmentType.Center);

        //Save the document 
        pdf1.save("d:/pdftest/Image_in_Cell.pdf");


One must have a clear understanding of cell width, especially when displaying an image in table cell, so that the image width should be fixed according to the width of a cell, in order to display it properly. Width of an Image can be fixed by using the set setFixedWidth() method of ImageInfo class. In this case the image is scaled to the fixed width of table cell.

You can see the result of the above code in the picture given below:

Name:  Adding Image in table Cell-001.png
Views: 623
Size:  25.8 KB