How to copy paragraphs include character styles to new document in apache poi?

Tags: , , ,



I’m trying to copy a certain number of paragraphs from an ms word file into a new one with Apache Poi. Although I copy paragraph styles without problem but I can’t transfer inline character styles to new file, how to get and apply character styles to new new doc?

        FileInputStream in = new FileInputStream("oldDoc.docx");
        XWPFDocument doc = new XWPFDocument(in);
        XWPFDocument newDoc = new XWPFDocument();

        // Copy styles from old to new doc
        XWPFStyles newStyles = newDoc.createStyles();
        newStyles.setStyles(doc.getStyle());

        List<XWPFParagraph> paragraphs = doc.getParagraphs();

        for (int p = 0; p < paragraphs.size(); p++) {
            XWPFParagraph oldPar = paragraphs.get(p);
            XWPFParagraph newPar = newDoc.createParagraph();
            // Apply paragraph style
            newPar.setStyle(oldPar.getStyle());

            XWPFRun run = newPar.createRun();
            run.setText(oldPar.getText());
        }

        FileOutputStream outNewDoc = new FileOutputStream("newDoc.docx");
        newDoc.write(outNewDoc);
        in.close();
        outNewDoc.close();

Answer

try {
    FileInputStream in = new FileInputStream("in.docx");
    XWPFDocument oldDoc = new XWPFDocument(in);
    XWPFDocument newDoc = new XWPFDocument();
    
    // Copy styles from template to new doc
    XWPFStyles newXStyles = newDoc.createStyles();
    newXStyles.setStyles(oldDoc.getStyle());

    List<XWPFParagraph> oldDocParagraphs = oldDoc.getParagraphs();
    for (XWPFParagraph oldPar : oldDocParagraphs) {
        // Create new paragraph and set it style of old paragraph
        XWPFParagraph newPar = newDoc.createParagraph();
        newPar.setStyle(oldPar.getStyle());
        // Loop in runs of old paragraphs.
        for (XWPFRun oldRun : oldPar.getRuns()) { // Paragrafın sitillere göre parçalanmış stringleri
            // Create a run for the new paragraph
            XWPFRun newParRun = newPar.createRun();
            // Set old run's text of old paragraph to the run of new paragraph
            String runText = oldRun.text();
            newParRun.setText(runText);
            // Set old run's style of old paragraph to the run of new paragraph
            CTRPr oldCTRPr = oldRun.getCTR().getRPr();
            if (oldCTRPr != null) {
                if (oldCTRPr.sizeOfRStyleArray() != 0){
                    String carStyle = oldRun.getStyle();
                    newParRun.setStyle(carStyle);
                }
            }
            // Add the new run to the new paragraph
            newPar.addRun(newParRun);
        }
        // Write to file and close.
        FileOutputStream out = new FileOutputStream("out.docx");
        newDoc.write(out);
        out.close();
    }
} catch (IOException | XmlException e) {
    e.printStackTrace();
}


Source: stackoverflow