Embed an image into an OpenOffice.org writer document


There are two kinds of images in OpenOffice.org:

  • Linked images are saved outside of the document
  • Embedded images are saved inside the document

The second kind is the one you would use to get a stand-alone document.

The problem

When you set the image to the TextGraphicObject using a URL, the result is a linked image.

The solution

You can find different solutions to insert an embedded image to OpenOffice.org with Java:

The first seems to be outdated. I couldn’t create a “com.sun.star.drawing.BitmapTable”.
The second uses multiple GraphicObjectShapes to create the embedded image. I consider this as a dirty hack.

So I used another way to solve the problem. To use this, you need:

  • Access to the XComponentContext
  • A TextGraphicObject in your document (see the links above)
  • The image as byte[] or use another stream

The code:

Object bitmapTableObject = xComponentContext.getServiceManager()

XGraphicProvider xGraphicProvider = UnoRuntime.queryInterface(
XGraphicProvider.class, bitmapTableObject);

PropertyValue[] v = new PropertyValue[1];
v[0] = new PropertyValue();
v[0].Name = "InputStream";
v[0].Value = new ByteArrayToXInputStreamAdapter(imageAsByteArray);

XGraphic graphic = xGraphicProvider.queryGraphic(v);
if (graphic == null) {
LOGGER.error("Error loading the image");

XPropertySet xProps = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, textGraphicObject);

// Set the image
xProps.setPropertyValue("Graphic", graphic);
Short URL for this post: https://wp.me/p4nxik-8R
This entry was posted in Did you know? and tagged , , , . Bookmark the permalink.