Search code examples
javadocx4j

Unable to open the generated docx4j document other than MS-Word Application


Below is Code for generating the Document using docx4j. I am able to open the generated document only in MS-Word Application.

When I mail the generated document, receiver is unable to view the document.

 private static void documentGenerator(String html, File file) throws Docx4JException, JAXBException {
//Word Processing Package
WordprocessingMLPackage wordMLPackage = getWordMLPackage();
NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
ndp.unmarshalDefaultNumbering();
AlternativeFormatInputPart inputPart = new AlternativeFormatInputPart(AltChunkType.Xhtml);
inputPart.setContentType(new ContentType("text/html"));
inputPart.setBinaryData(html.getBytes());
Relationship altChunkRel = wordMLPackage.getMainDocumentPart().addTargetPart(inputPart);
// .. the bit in document body
CTAltChunk ac = Context.getWmlObjectFactory().createCTAltChunk();
ac.setId(altChunkRel.getId());
wordMLPackage.getMainDocumentPart().addObject(ac);
// .. content type
wordMLPackage.getContentTypeManager().addDefaultContentType("html", "text/html");
//Saving the Document
wordMLPackage.save(file);
}

Solution

  • I used XhtmlImporter to generate the document,then the compatibility problem is resolved.

    Below is Code Snippet

    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
    NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
    wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
    ndp.unmarshalDefaultNumbering();
    AlternativeFormatInputPart inputPart = new AlternativeFormatInputPart(AltChunkType.Xhtml);
    inputPart.setContentType(new ContentType("text/html"));
    inputPart.setBinaryData(html.getBytes());
    Relationship altChunkRel = wordMLPackage.getMainDocumentPart().addTargetPart(inputPart);
    // .. the bit in document body
    CTAltChunk ac = Context.getWmlObjectFactory().createCTAltChunk();
    ac.setId(altChunkRel.getId());
    wordMLPackage.getMainDocumentPart().addObject(ac);
    // .. content type
    wordMLPackage.getContentTypeManager().addDefaultContentType("html", "text/html");
    //Saving the Document
    wordMLPackage.save(file);