Skip to content

Instantly share code, notes, and snippets.

This code can be used to insert picture in Word Document using Java. For more details refer to the article: https://kb.aspose.com/words/java/how-to-insert-picture-in-word-using-java/
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.HeaderFooterType;
import com.aspose.words.License;
import com.aspose.words.Shape;
public class InsertPictureInWordDocumentUsingJava
{
public static void main(String[] args) throws Exception { //main function for InsertPictureInWordDocumentUsingJava class
// Initialize a license to avoid trial version watermark in the output Word file after adding image
License license = new License();
license.setLicense("Aspose.Words.lic");
// Load input Word DOCX document
Document AddImagesToWordDOC = new Document("input.docx");
// Initialize DocumentBuilder class object to add image
DocumentBuilder imageWriter = new DocumentBuilder(AddImagesToWordDOC);
// Move the cursor to the Primary Header
imageWriter.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
// Insert a picture in Word document header
Shape headerImage = imageWriter.insertImage("SampleImage.jpg");
// Set Image Size in Header section
headerImage.setWidth(1 * 72); // equals to one inch
headerImage.setHeight(1 * 72);
// Move cursor to last Paragraph in Document
imageWriter.moveTo(AddImagesToWordDOC.getLastSection().getBody().getLastParagraph());
// Add the picture to Word Document and Link it with the file
Shape imageAsLinkToFile = imageWriter.insertImage("SampleImage.jpg");
imageAsLinkToFile.getImageData().setSourceFullName("SampleImage.jpg");
// Save output DOCX file after inserting image
AddImagesToWordDOC.save("Word with Embedded and Linked Images.docx");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment