Last active
November 26, 2021 16:19
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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