I've been generating word document from HTML content.
using below code.
ordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(PageSizePaper.LETTER, false);
XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
XHTMLImporter.setRunFormatting(FormattingOption.CLASS_PLUS_OTHER);
NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
ndp.unmarshalDefaultNumbering();
wordMLPackage.getMainDocumentPart().getContent().addAll(XHTMLImporter.convert("<h3> SAMPLE HEADING</h3>", null));
File exportFile = new File(somepath/sample.docx);
wordMLPackage.save(exportFile);
Above code works fine and generate the Document, but the HTML <h3> SAMPLE HEADING</h3>
doesn't converted to MS word Heading 3 it shows as Normal text in document.
Later I'll generate Table of Content TOC using those headings using below code.
tocGenerator.generateToc( 1, "TOC \\o \"1-3\" \\h \\z \\u ", false);
However some how this code doesn't support normal text to generate TOC.
We need to change the Heading setting by using below code.
ImportXHTMLProperties.setProperty("docx4j-ImportXHTML.Element.Heading.MapToStyle", true);
Here the updated code which is working for the requirement.
// activating Headings property for MS Word Heading Mapping
ImportXHTMLProperties.setProperty("docx4j-ImportXHTML.Element.Heading.MapToStyle", true);
ordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(PageSizePaper.LETTER, false);
XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
XHTMLImporter.setRunFormatting(FormattingOption.CLASS_PLUS_OTHER);
NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
ndp.unmarshalDefaultNumbering();
wordMLPackage.getMainDocumentPart().getContent().addAll(XHTMLImporter.convert("<h3> SAMPLE HEADING</h3>", null));
File exportFile = new File(somepath/sample.docx);
// adding TOC - TABLE OF CONTENTS
TocGenerator tocGenerator = new TocGenerator(wordMLPackage);
tocGenerator.generateToc(0, "TOC \\o \"1-3\" \\h \\z \\u ", false);
wordMLPackage.save(exportFile);