Insert Image into Word Document in Java

This article is going to demonstrate how to insert image into a Word document using Spire.Doc for Java.

In Spire.Doc for Java, the appendPicture() method in Paragraph class is used for appending images to Word paragraph. When appending an image, we can customize the image settings like width and height. The image can be from a local file, a byte array or a stream.

import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;
import com.spire.doc.fields.DocPicture;

import java.awt.*;

public class InsertImage {
    public static void main(String[] args){
        //Create a Document object
        Document doc = new Document();
        //Add a section
        Section section = doc.addSection();

        //Add a paragraph to the section
        Paragraph paragraph1 = section.addParagraph();
        //Set paragraph text
        paragraph1.setText("Insert Image Demo by Spire.Doc for Java");

        //Add another paragraph to the section
        Paragraph paragraph2 = section.addParagraph();
        //Append an image from local file to the paragraph
        DocPicture picture = paragraph2.appendPicture("C:\\Users\\Administrator\\Desktop\\Hydrangeas.jpg");
        //Set image width
        picture.setWidth(300f);
        //Set image height
        picture.setHeight(250f);

        //Apply style to paragraph 1
        ParagraphStyle style = new ParagraphStyle(doc);
        style.setName("titleStyle");
        style.getCharacterFormat().setBold(true);
        style.getCharacterFormat().setTextColor(Color.BLUE);
        style.getCharacterFormat().setFontName("Arial");
        style.getCharacterFormat().setFontSize(18f);
        doc.getStyles().add(style);
        paragraph1.applyStyle("titleStyle");

        //Set horizontal alignment for paragraph 1 and paragraph 2
        paragraph1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        paragraph2.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        
        //Set space after paragraph 1
        paragraph1.getFormat().setAfterSpacing(15f);
        
        //Save the Document object
        doc.saveToFile("InsertImage.docx", FileFormat.Docx_2013);
    }
}

Output:

Insert Image into Word Document in Java