Insert Images to a Table in Word in Java

This article demonstrates how to insert images to table cells in a Word document using Spire.Doc for Java.

import com.spire.doc.AutoFitBehaviorType;
import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.Table;
import com.spire.doc.fields.DocPicture;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class InsertImageToTableCell {

    public static void main(String[] args) throws FileNotFoundException {

        //Create a Document object
        Document document = new Document();

        //Add a section
        Section section  = document.addSection();

        //Add a table
        Table table = section.addTable(true);
        table.resetCells(2,2);
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

        //Load an image to InputStream
        InputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\company-logo.png");
        
        //Insert the image to the cell(0,0)
        DocPicture picture = table.get(0,0).addParagraph().appendPicture(inputStream);
        
        //Set the width and height of the image
        picture.setWidth(100);
        picture.setHeight(100);

        //Insert another image to the cell(1,1)
        inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\intro.png");
        picture = table.get(1,1).addParagraph().appendPicture(inputStream);
        picture.setWidth(100);
        picture.setHeight(100);

        //Save the document
        document.saveToFile("InsertImgToCell.docx");
    }
}

Insert Images to a Table in Word in Java