Tables can be added to Word documents to help display data, and in the same way, images can be inserted to tables to support data or to make the whole table more eye-catching. In this article, I'm going to demonstrate how to insert images to table cells in a Word document using Free Spire.Doc for Java.
Import JAR Dependency (2 methods)
● Download the Free Spire.Doc for Java and unzip it, then add the Spire.Doc.jar file to your Java application as dependency.
● Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
Sample Code
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\\logo1.jpg");
//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\\logo2.jpg");
picture = table.get(1,1).addParagraph().appendPicture(inputStream);
picture.setWidth(100);
picture.setHeight(100);
//Save the document
document.saveToFile("InsertImgToCell.docx");
}
}
Top comments (0)