docx4j Documentation

repository·VERSION_17_0_3·Indexed 25 days ago

https://github.com/plutext/docx4j

An open-source Java library for creating, editing, and saving OpenXML formats including docx, pptx, and xlsx using JAXB. Key capabilities include document generation, HTML and PDF export (via docx4j-export-FO, documents4j, or Microsoft Graph), and programmatic manipulation of Office documents. Supports Java 8 (v8), Java 11+ with JAXB 3.0 (v11.4.5), and Java 11+ with JAXB 4.0 (v17.0.0+). Provides a three-layered model consisting of the Open Packaging Layer, JAXB Content Tree Layer, and the Model Layer.

Tokens
5.4K
Snippets
8
Records
35
Agent score
82%

What's inside docx4j

  1. What is docx4j?

    VERSION_17_0_3

    docx4j is an open source (Apache v2) library for creating, editing, and saving OpenXML "packages", including docx, pptx, and xlsx. It uses JAXB to create the Java representation of these files.

    Key Capabilities:

    • Open, create, and programmatically manipulate docx, pptx, and xlsx files.
    • Document generation via variables, content control data binding, or MERGEFIELD.
    • CustomXML binding (supporting pictures, rich text, checkboxes, OpenDoPE extensions for repeats & conditionals, and XHTML importing).
    • Export to HTML.
    • Export to PDF (using one of three available strategies).
    • Produce/consume Word 2007's xmlPackage (pkg) format.
    • Apply transforms and common filters.
    • Font support including font substitution and use of embedded fonts.
  2. Compare docx to PDF conversion alternatives

    VERSION_17_0_3

    Depending on your requirements, you may choose an alternative to XSL FO for PDF conversion:

    • documents4j: Since version 8.2.0, you can use Microsoft Word to perform the conversion.
    • via-Microsoft-Graph: Since version 8.2.3, you can use java-docx-to-pdf-using-Microsoft-Graph to perform the conversion via the Microsoft Graph API.
  3. Understand the three-layered docx4j model

    VERSION_17_0_3

    docx4j organizes docx file representation into three distinct layers. Understanding these layers helps you decide where to implement custom logic and how to navigate the document structure:

    1. The Open Packaging Layer (org.docx4j.openpackaging): The lowest level. It represents the docx package itself and its constituent parts. Parts are typically subclasses of org.docx4j.openpackaging.parts.JaxbXmlPart.
    2. The JAXB Content Tree Layer (org.docx4j.wml, org.docx4j.dml, org.docx4j.docProps): The middle level. This layer contains the actual XML content trees. Most document parts (like MainDocumentPart, styles, and headers) use WordprocessingML (org.docx4j.wml), which may reference DrawingML (org.docx4j.dml). Property parts use org.docx4j.docProps.
    3. The Model Layer (org.docx4j.model): The highest level. This layer builds on the lower two and provides high-level functionality that spans multiple parts, such as headers/footers, list numbering, and images.

    Usage Pattern:

    • Use the lowest level to create, open, or save a package, add/remove parts, and access the JAXB content tree.
    • Use the middle and highest levels to manipulate the actual document content.
  4. Understand VML schema support in docx4j

    VERSION_17_0_3

    docx4j includes VML (Vector Markup Language) schemas primarily to handle embedded images when saving files as .docx from older Word formats (like Word 2003). The VML implementation in docx4j follows the ECMA 376 1st edition standard.

    The VML schema (vml.xsd) integrates with several other namespaces to support different Office applications, including:

    • WordprocessingML (wml.xsd)
    • Office Relationships (shared-relationshipReference.xsd)
    • Excel Spreadsheet Drawing (vml-spreadsheetDrawing.xsd)
    • PowerPoint Presentation Drawing (vml-presentationDrawing.xsd)
  5. Use Arimo variable or static fonts

    VERSION_17_0_3

    The Arimo font package provides two ways to use the font depending on your application's support for variable fonts:

    1. Variable Fonts: If your application supports variable fonts, use the files containing the wght axis. These files allow you to select intermediate styles between standard weights.

      • Arimo/Arimo-VariableFont_wght.ttf
      • Arimo/Arimo-Italic-VariableFont_wght.ttf
    2. Static Fonts: If your application does not support variable fonts, use the individual static files located in the static/ directory:

      • Arimo/static/Arimo-Regular.ttf
      • Arimo/static/Arimo-Medium.ttf
      • Arimo/static/Arimo-SemiBold.ttf
      • Arimo/static/Arimo-Bold.ttf
      • Arimo/static/Arimo-Italic.ttf
      • Arimo/static/Arimo-MediumItalic.ttf
      • Arimo/static/Arimo-SemiBoldItalic.ttf
      • Arimo/static/Arimo-BoldItalic.ttf
  6. Install Liberation Fonts

    VERSION_17_0_3

    Liberation Fonts provide document layout compatibility for fonts like Times New Roman, Arial, and Courier New. To install them, you must first build them from source using fontforge and python fonttools.

    1. Get the source

    $ git clone https://github.com/liberationfonts/liberation-fonts.git

    Or download the tar.gz file from the releases page and extract it:

    $ tar zxvf liberation-fonts-[VERSION].tar.gz

    2. Build from source

    Navigate to the directory and run make. The resulting binary font files will be located in the liberation-fonts-ttf-[VERSION] directory.

    $ cd liberation-fonts
    $ make

    3. System Installation (Fedora example)

    • User-wide: Copy the TTF files to ~/.fonts.
    • System-wide: Copy the TTF files to /usr/share/fonts/liberation.
    • Refresh cache: Run fc-cache to register the new fonts.
    $ git clone https://github.com/liberationfonts/liberation-fonts.git
    $ cd liberation-fonts
    $ make
  7. Use docx4j for JAXB 3.0 and Java 11+

    VERSION_17_0_3

    docx4j v11.4.5 uses Jakarta XML Binding API 3.0.

    Migration Note: Because this version uses jakarta.xml.bind instead of the older javax.xml.bind, you must perform a search-and-replace in your codebase to update all javax.xml.bind imports to jakarta.xml.bind. Maven will automatically handle the replacement of JAXB jars.

  8. Run docx4j-samples-documents4j-local without Maven

    VERSION_17_0_3

    To run the samples without Maven, you must manually ensure the following dependencies are in your classpath:

    1. The Documents4j local JAR files and the docx4j-documents4j-local JAR (included in the provided zip).
    2. docx4j and its dependencies (provided in the separate community zip).
    3. A JAXB implementation, such as docx4j-JAXB-ReferenceImpl or MOXy, unless your Java runtime already ships with JAXB.
  9. Use the JAXB Reference Implementation with docx4j

    VERSION_17_0_3

    By default, docx4j requires a JAXB implementation to function. If you want docx4j to use the official JAXB Reference Implementation (RI), you must add the docx4j-JAXB-ReferenceImpl JAR to your project's classpath.

    This implementation is automatically detected because the jaxb-runtime-4.0.5.jar (or similar versions) contains the service provider configuration in META-INF/services/jakarta.xml.bind.JAXBContextFactory pointing to org.glassfish.jaxb.runtime.v2.JAXBContextFactory.

  10. Migrate docx4j-diffx from Topologi to pso-diffx

    VERSION_17_0_3

    The docx4j-diffx module is migrating from a bundled, legacy version of Topologi Diff-X (com.topologi.diffx) to the actively maintained org.pageseeder.diffx:pso-diffx:1.3.4 dependency.

    Key Changes

    • Dependency: Replace com.topologi.diffx with org.pageseeder.diffx:pso-diffx:1.3.4 (Apache 2.0, Java 11+).
    • Namespace Change: The com.topologi namespace is being removed. The primary entry point Docx4jDriver is moving to org.docx4j.diff.Docx4jDriver.
    • API Evolution: The migration involves moving from the pre-2010 Topologi API (using DOMRecorder, EventSequence, etc.) to the modern pso-diffx pipeline API (using DOMLoader, Sequence, DiffHandler).

    Migration Strategy

    1. Establish a Safety Net: Build a golden-output corpus using the current code. Capture both the raw pre-XSLT diff XML (from Docx4jDriver.diff) and the final tracked-changes WML (from Differencer.toWML).
    2. Swap Dependency: Add the new dependency and remove the com/topologi tree.
    3. Rewrite Glue Code: Re-implement Docx4jDriver, EventSequenceComparator, and Differencer to use the new pso-diffx classes.
    4. Ensure Output Compatibility: Use org.docx4j.diff.LegacyDiffOutput (extending DefaultXMLDiffOutput) with useLegacyNamespaces = true to maintain compatibility with existing XSLTs that expect the http://www.topologi.com/2005/Diff-X namespace.
    5. Verify Granularity: Ensure DiffConfig settings for whitespace and granularity match the legacy behavior to avoid regression in diff quality.