Search code examples
javaapache-poidocxdocx4j

Converting a file with ".dotx" extension (template) to "docx" (Word File)


How to convert a ".dotx" Word template to a plain ".docx" using a POI APIs or Docx4j?


Solution

  • The need is changing the content type of /word/document.xml from application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml to application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml.

    Example using apache poi 4.0.1:

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    
    import org.apache.poi.xwpf.usermodel.*;
    
    public class WordReadDOTXSaveDOCX {
    
     public static void main(String[] args) throws Exception {
    
      XWPFDocument document = new XWPFDocument(new FileInputStream("StudentReport.dotx"));
      document.getPackage().replaceContentType(
       "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml",
       "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
    
      FileOutputStream out = new FileOutputStream("TheDocumentFromDOTXTemplate.docx");
      document.write(out);
      out.close();
      document.close();
     }
    }