How to Insert Images into a Word Document in Java

How to Insert Images into a Word Document in Java

Aspose.Words FOSS for Java inserts pictures into a Word document with DocumentBuilder.insertImage. This guide creates a PNG with ImageIO, inserts it three ways, saves the document and reads the pictures back, with the library from Maven Central.

Step-by-Step Guide

Step 1: Install the Package

Add the package to your build. The library needs Java 8 or later.

<dependency>
  <groupId>org.aspose</groupId>
  <artifactId>aspose-words-foss</artifactId>
  <version>26.3.0</version>
</dependency>

Step 2: Import the Classes

All classes are in the com.aspose.words package, so the example starts with import com.aspose.words.*;.


Step 3: Create the Image

The example writes a 120 by 60 pixel PNG with ImageIO.write, so that no image file is needed. It was run with -Djava.awt.headless=true on Java 8, 17 and 21.


Step 4: Insert It and Set the Size

builder.insertImage("logo.png") returned a Shape of 90 by 45 points, insertImage(in, 60, 30) with an InputStream returned 60 by 30 points, and a floating picture was inserted with page-relative positions and WrapType.SQUARE. setAlternativeText sets the alternative text.

import com.aspose.words.*;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;

BufferedImage logo = new BufferedImage(120, 60, BufferedImage.TYPE_INT_RGB);
Graphics2D g = logo.createGraphics();
g.setColor(new Color(30, 90, 160));
g.fillRect(0, 0, 120, 60);
g.setColor(Color.WHITE);
g.fillRect(10, 10, 40, 40);
g.dispose();
ImageIO.write(logo, "png", new File("logo.png"));

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.writeln("From a file, natural size:");
Shape natural = builder.insertImage("logo.png");
natural.setAlternativeText("Company logo");
builder.writeln();

builder.writeln("From a stream, scaled to 60 x 30 points:");
InputStream in = new FileInputStream("logo.png");
Shape small = builder.insertImage(in, 60, 30);
in.close();
builder.writeln();

builder.writeln("Floating, positioned on the page:");
Shape floating = builder.insertImage("logo.png", RelativeHorizontalPosition.PAGE, 300,
        RelativeVerticalPosition.PAGE, 400, 90, 45, WrapType.SQUARE);
System.out.println("natural: " + natural.getWidth() + " x " + natural.getHeight() + " points, inline " + natural.isInline());
System.out.println("small: " + small.getWidth() + " x " + small.getHeight() + " points, inline " + small.isInline());
System.out.println("floating: inline " + floating.isInline() + ", wrap square " + (floating.getWrapType() == WrapType.SQUARE)
        + ", left " + floating.getLeft() + ", top " + floating.getTop());
doc.save("logos.docx");

Document reloaded = new Document("logos.docx");
NodeCollection shapes = reloaded.getChildNodes(NodeType.SHAPE, true);
System.out.println("Shapes after reload: " + shapes.getCount());
for (int i = 0; i < shapes.getCount(); i++) {
    Shape shape = (Shape) shapes.get(i);
    ImageData data = shape.getImageData();
    System.out.println(i + ": has image " + shape.hasImage()
            + ", type " + ImageType.getName(data.getImageType())
            + ", " + data.getImageSize().getWidthPixels() + " x " + data.getImageSize().getHeightPixels() + " pixels"
            + ", shown " + shape.getWidth() + " x " + shape.getHeight() + " points"
            + ", inline " + shape.isInline()
            + ", alt '" + shape.getAlternativeText() + "'");
}

The program printed:

natural: 90.0 x 45.0 points, inline true
small: 60.0 x 30.0 points, inline true
floating: inline false, wrap square true, left 300.0, top 400.0
Shapes after reload: 3
0: has image true, type PNG, 120 x 60 pixels, shown 90.0 x 45.0 points, inline true, alt 'Company logo'
1: has image true, type PNG, 120 x 60 pixels, shown 60.0 x 30.0 points, inline true, alt ''
2: has image true, type PNG, 120 x 60 pixels, shown 90.0 x 45.0 points, inline false, alt ''

Step 5: Find, Export and Resize the Pictures

getChildNodes(NodeType.SHAPE, true) returns every shape, so check hasImage. getImageData().save(name) wrote a file identical to the one that was inserted, and setWidth(120) changed a 300 by 75 point picture to 120 by 30 points because the aspect ratio is locked for a new picture.

import com.aspose.words.*;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Files;
import java.util.Arrays;
import javax.imageio.ImageIO;

// Build a document with two pictures: a wide PNG and a square JPEG.
String[] names = {"banner.png", "badge.jpg"};
int[] widths = {400, 64};
int[] heights = {100, 64};
Document source = new Document();
DocumentBuilder builder = new DocumentBuilder(source);
for (int i = 0; i < names.length; i++) {
    BufferedImage img = new BufferedImage(widths[i], heights[i], BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();
    g.setColor(i == 0 ? new Color(200, 80, 20) : new Color(20, 120, 60));
    g.fillRect(0, 0, widths[i], heights[i]);
    g.dispose();
    ImageIO.write(img, i == 0 ? "png" : "jpg", new File(names[i]));
    builder.insertImage(names[i]);
    builder.writeln();
}
source.save("gallery.docx");

// Reload, list every picture, export it and shrink the wide ones to 120 points.
Document doc = new Document("gallery.docx");
NodeCollection shapes = doc.getChildNodes(NodeType.SHAPE, true);
for (int i = 0; i < shapes.getCount(); i++) {
    Shape shape = (Shape) shapes.get(i);
    if (!shape.hasImage()) {
        continue;
    }
    ImageData data = shape.getImageData();
    String type = ImageType.getName(data.getImageType());
    String exported = "exported-" + i + "." + type.toLowerCase();
    data.save(exported);
    boolean identical = Arrays.equals(Files.readAllBytes(new File(exported).toPath()),
            Files.readAllBytes(new File(names[i]).toPath()));
    System.out.println(type + ": " + data.getImageSize().getWidthPixels() + " x " + data.getImageSize().getHeightPixels()
            + " pixels, shown " + shape.getWidth() + " x " + shape.getHeight() + " points, exported file identical: " + identical);
    if (shape.getWidth() > 120) {
        shape.setWidth(120);
    }
}
doc.save("gallery-small.docx");

Document resized = new Document("gallery-small.docx");
NodeCollection after = resized.getChildNodes(NodeType.SHAPE, true);
for (int i = 0; i < after.getCount(); i++) {
    Shape shape = (Shape) after.get(i);
    System.out.println("after resize " + i + ": " + shape.getWidth() + " x " + shape.getHeight() + " points");
}

The program printed:

PNG: 400 x 100 pixels, shown 300.0 x 75.0 points, exported file identical: true
JPEG: 64 x 64 pixels, shown 48.0 x 48.0 points, exported file identical: true
after resize 0: 120.0 x 30.0 points
after resize 1: 48.0 x 48.0 points

Step 6: Handle SVG Files

insertImage throws UnsupportedOperationException with the message FOSS for an SVG file and adds no shape. Catch it and insert a PNG instead.

import com.aspose.words.*;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.imageio.ImageIO;

String svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"50\">"
        + "<rect width=\"100\" height=\"50\" fill=\"#1e5aa0\"/></svg>";
Writer writer = new OutputStreamWriter(new FileOutputStream("logo.svg"), "UTF-8");
writer.write(svg);
writer.close();

// A raster copy of the same drawing, to fall back to.
BufferedImage raster = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D g = raster.createGraphics();
g.setColor(new Color(0x1e5aa0));
g.fillRect(0, 0, 200, 100);
g.dispose();
ImageIO.write(raster, "png", new File("logo-fallback.png"));

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Logo:");

Shape logo;
try {
    logo = builder.insertImage("logo.svg");
    System.out.println("SVG inserted");
} catch (UnsupportedOperationException e) {
    System.out.println("SVG rejected: " + e.getMessage());
    System.out.println("Pictures in the document after the failed call: "
            + doc.getChildNodes(NodeType.SHAPE, true).getCount());
    logo = builder.insertImage("logo-fallback.png", 100, 50);
}
System.out.println("Inserted " + ImageType.getName(logo.getImageData().getImageType())
        + ", " + logo.getWidth() + " x " + logo.getHeight() + " points");
doc.save("logo.docx");

Document reloaded = new Document("logo.docx");
NodeCollection shapes = reloaded.getChildNodes(NodeType.SHAPE, true);
System.out.println("Pictures after reload: " + shapes.getCount());

The program printed:

SVG rejected: FOSS
Pictures in the document after the failed call: 0
Inserted PNG, 100.0 x 50.0 points
Pictures after reload: 1

Common Issues and Fixes

insertImage throws UnsupportedOperationException with the message FOSS. The file is an SVG, which this edition rejects. In a test on Java 8, 17 and 21 the overloads for a file name, a stream and a byte array all threw it. Convert the drawing to PNG or JPEG before you insert it.

insertImage throws FileNotFoundException. The message was Can't find file: missing.png. for a file that does not exist. Check the file name and the working directory of the process.

Bytes that are not an image throw a CantCreateBitmapException. In a test, 10 arbitrary bytes passed to insertImage(byte[]) threw com.aspose.CantCreateBitmapException with the message Could not create the bitmap with the specified parameters. Possible lack of system resources.: Parameter is not valid. FileFormat =0, and the document had no shape afterwards.

The size of the picture is not what I expected. The width and height are in points, and the size follows the pixel size and the resolution of the image: a 120 by 60 pixel PNG at 96 dpi became 90 by 45 points.

Document.save throws NullPointerException after a failed insert. insertImage(new byte[0]) throws NullPointerException but leaves a shape without data in the document, and a later save threw NullPointerException on Java 8, 17 and 21. Check that the array is not empty first.

The compiler reports an unreported exception. The Document constructors, Document.save and some other methods declare throws Exception. Declare it on the calling method or catch it.

Frequently Asked Questions

Which image formats did you test?

PNG, JPEG and GIF files written with ImageIO; the reloaded pictures reported the types PNG, JPEG and GIF. SVG is rejected.

How do I read the pixel size of a picture?

shape.getImageData().getImageSize() has getWidthPixels and getHeightPixels, and getWidthPoints and getHeightPoints for points.

Where does the alternative text go in the file?

In a test the saved DOCX stored it in the descr attribute of the picture’s wp:docPr element.

See Also