How to Set Custom Properties on a Word Document in Java

How to Set Custom Properties on a Word Document in Java

Aspose.Words FOSS for Java stores custom properties in a Word document with CustomDocumentProperties. This guide adds three properties, saves the file, reads them back and removes one, 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: Add the Properties

doc.getCustomDocumentProperties().add(name, value) creates a property. The example adds a string (Project), an int (Revision) and a boolean (Approved).


Step 4: Save, Reload and Read

Save the document and open it again. getCount returned 3 and get(name).getValue() returned Atlas, 3 and true.

import com.aspose.words.*;

Document doc = new Document();
CustomDocumentProperties custom = doc.getCustomDocumentProperties();
custom.add("Project", "Atlas");
custom.add("Revision", 3);
custom.add("Approved", true);
doc.save("custom.docx");

Document reloaded = new Document("custom.docx");
CustomDocumentProperties saved = reloaded.getCustomDocumentProperties();
System.out.println("Custom properties: " + saved.getCount());
System.out.println("Project = " + saved.get("Project").getValue());
System.out.println("Revision = " + saved.get("Revision").getValue());
System.out.println("Approved = " + saved.get("Approved").getValue());

saved.remove("Revision");
System.out.println("Contains Revision: " + saved.contains("Revision"));

The program printed:

Custom properties: 3
Project = Atlas
Revision = 3
Approved = true
Contains Revision: false

Step 5: Remove a Property

remove(name) deletes a property; contains(name) then returned false.

Common Issues and Fixes

The property you expect is not returned. The name is not in the collection. Check it with contains 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

Can I read the built-in title and author?

Yes, through Document.getBuiltInDocumentProperties, for example getTitle and getAuthor.

Which value types are supported?

String, int, boolean, double and date overloads of add. A date read back after a save was shifted by the JVM time zone offset in tests on Java 8, 17 and 21, so compare dates after a reload or use -Duser.timezone=UTC.

See Also