Mastering Docx4j: Full Control of Word Documents in Spring Boot 3

This article walks through using the Java‑based Docx4j library with Spring Boot 3.5.0 to create, style, insert images, generate tables, and read Word (docx) files, providing complete Maven dependencies, step‑by‑step code examples, and the resulting document screenshots.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Mastering Docx4j: Full Control of Word Documents in Spring Boot 3

Docx4j is an open‑source Java library designed for handling Microsoft Office Open XML formats such as .docx, .xlsx, and .pptx. The article demonstrates how to use Docx4j within a Spring Boot 3.5.0 project to perform common Word document operations.

1. Add Maven dependencies

<dependency>
  <groupId>org.docx4j</groupId>
  <artifactId>docx4j-core</artifactId>
  <version>11.5.8</version>
</dependency>
<dependency>
  <groupId>org.glassfish.jaxb</groupId>
  <artifactId>jaxb-runtime</artifactId>
  <version>4.0.6</version>
</dependency>
<dependency>
  <groupId>org.docx4j</groupId>
  <artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
  <version>11.5.8</version>
</dependency>

2. Create a document and add styled text

WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
mainDocumentPart.addStyledParagraphOfText("Title", "Spring Boot3实战案例200讲");
mainDocumentPart.addParagraphOfText("《Spring Boot3实战案例200讲》涵盖从基础环境搭建到高级特性应用,如响应式编程、集群限流、自定义Starter封装等,助力开发者快速掌握Spring Boot3核心技能,提升实战能力。");
File exportFile = new File("d:/Spring Boot3实战案例200讲.docx");
wordPackage.save(exportFile);

The generated document contains a title paragraph and a body paragraph, as shown in the screenshot:

Generated Word document preview
Generated Word document preview

3. Control paragraph styles

To apply bold, italic, and color styling, the article creates a RPr object and attaches it to a run:

ObjectFactory factory = Context.getWmlObjectFactory();
P p = factory.createP();
R r = factory.createR();
Text t = factory.createText();
t.setValue("作者:Pack_xg");
r.getContent().add(t);
RPr rpr = factory.createRPr();
BooleanDefaultTrue b = new BooleanDefaultTrue();
rpr.setB(b);
rpr.setI(b);
Color green = factory.createColor();
green.setVal("green");
rpr.setColor(green);
r.setRPr(rpr);
p.getContent().add(r);
mainDocumentPart.getContent().add(p);
wordPackage.save(new File("d:/Spring Boot3实战案例200讲.docx"));

The styled paragraph appears as shown:

Styled paragraph example
Styled paragraph example

4. Insert an image

// Add image
File image = new File("d:/images/4.png");
byte[] fileContent = Files.readAllBytes(image.toPath());
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordPackage, fileContent);
Inline inline = imagePart.createImageInline("她是寂寞的美女", "美女", 1, 2, false);
P imageParagraph = addImageToParagraph(inline);
mainDocumentPart.getContent().add(imageParagraph);

private static P addImageToParagraph(Inline inline) {
    ObjectFactory factory = new ObjectFactory();
    P p = factory.createP();
    R r = factory.createR();
    p.getContent().add(r);
    Drawing drawing = factory.createDrawing();
    r.getContent().add(drawing);
    drawing.getAnchorOrInline().add(inline);
    return p;
}

The resulting document shows the inserted picture:

Document with inserted image
Document with inserted image

5. Generate a table

int writableWidthTwips = wordPackage.getDocumentModel().getSections().get(0).getPageDimensions().getWritableWidthTwips();
int columnNumber = 3;
Tbl tbl = TblFactory.createTable(3, 3, writableWidthTwips / columnNumber);
List<Object> rows = tbl.getContent();
for (int i = 0; i < rows.size(); i++) {
    Tr tr = (Tr) rows.get(i);
    List<Object> cells = tr.getContent();
    for (int j = 0; j < cells.size(); j++) {
        Tc td = (Tc) cells.get(j);
        P p = factory.createP();
        R r = factory.createR();
        Text t = factory.createText();
        t.setValue("作者:Pack_xg - %s - %s".formatted(i, j));
        r.getContent().add(t);
        p.getContent().add(r);
        td.getContent().add(p);
    }
}
mainDocumentPart.getContent().add(tbl);

The final document contains the generated table:

Generated table in Word document
Generated table in Word document

6. Read content from a docx file

public static void read() throws Exception {
    File doc = new File("d:/Spring Boot3实战案例200讲.docx");
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(doc);
    MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();
    String textNodesXPath = "//w:t";
    List<Object> textNodes = mainDocumentPart.getJAXBNodesViaXPath(textNodesXPath, true);
    for (Object obj : textNodes) {
        Text text = (Text) ((JAXBElement) obj).getValue();
        System.out.println(text.getValue());
    }
}

Running the method prints all text nodes, as illustrated by the console screenshot:

Console output of extracted text
Console output of extracted text

7. Summary

The article provides a complete, hands‑on guide for using Docx4j in a Spring Boot environment, covering dependency setup, document creation, paragraph styling, image insertion, table generation, and content extraction, with concrete code snippets and visual verification of each step.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaMavenSpring BootWorddocx4jOpenXML
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.