Search code examples
javams-worddocxdocx4j

Docx4j export style from one .docx and use it in another .docx


I am creating new Word document with the code below:

Tidy tidy = new Tidy();
            tidy.setShowWarnings(true);
            tidy.setInputEncoding("UTF-8");
            tidy.setOutputEncoding("UTF-8");
            tidy.setXHTML(true);
            tidy.setMakeClean(true);
            tidy.setQuoteNbsp(false);

WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
            XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);

for (Value v : res.getRules()) {
                System.out.println(v.toString());
                ByteArrayOutputStream ou = new ByteArrayOutputStream();
                tidy.parse(new ByteArrayInputStream(v.toString().getBytes(StandardCharsets.UTF_8)), ou);
                wordMLPackage.getMainDocumentPart().getContent().clear();
                wordMLPackage.getMainDocumentPart().getContent().addAll(XHTMLImporter.convert(new String(ou.toByteArray()), null));
            }
            wordMLPackage.save(new java.io.File(System.getProperty("user.dir") + "/report.docx"));

What I want to do, is to use style from other .docx and append it to specific part of output that I save. Any ideas ? I've spent a lot of time on finding solution, but I haven't found anything useful.


Solution

  • First document. We want to import styles from it.

    WordprocessingMLPackage wordMLPackage2 = WordprocessingMLPackage
    .load(new java.io.File(System.getProperty("user.dir") + "/template.docx"));
    

    Second document

    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
    

    We import styles from first document and append them to the second document

    MainDocumentPart tempDocPart = wordMLPackage2.getMainDocumentPart();
    StyleDefinitionsPart sdp = tempDocPart.getStyleDefinitionsPart();
    Styles tempStyle = sdp.getJaxbElement();
    wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().setJaxbElement(tempStyle);
    

    And we can use specific style using its id

    wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Heading1", "Example");