Pregunta

I'm trying to do an exact copy of one paragraph into another (I'm copying a template over to a new document for word-replacement). I'm doing this for paragraphs within a table cell, but I don't believe that is significant. The following code nearly works:

for (XWPFParagraph p : cell.getParagraphs()) {
    XWPFParagraph np = newCell.addParagraph();
    np.getCTP().set(p.getCTP());
}

The problem is, while np.getCTP().xmlText().equals(p.getCTP().xmlTest() is true, np.getText() is blank while p.getText() has the contents of the paragraph. It seems like my paragraph doesn't know about the underlying change I made to the XML. This results in my output document containing the placeholder text because my code can't seem to see the contents of the paragraph any more in order to perform the replacement.

How can I make a perfect copy of a paragraph including all contents and properties?

¿Fue útil?

Solución

This seems to be getting the job done. I'm not sure that the whole cloneRun() method couldn't be replaced by nr.getCTR().set(r.getCTR()); but this seems better safe than sorry.

public static void cloneParagraph(XWPFParagraph clone, XWPFParagraph source) {
    CTPPr pPr = clone.getCTP().isSetPPr() ? clone.getCTP().getPPr() : clone.getCTP().addNewPPr();
    pPr.set(source.getCTP().getPPr());
    for (XWPFRun r : source.getRuns()) {
        XWPFRun nr = clone.createRun();
        cloneRun(nr, r);
    }
}

public static void cloneRun(XWPFRun clone, XWPFRun source) {
    CTRPr rPr = clone.getCTR().isSetRPr() ? clone.getCTR().getRPr() : clone.getCTR().addNewRPr();
    rPr.set(source.getCTR().getRPr());
    clone.setText(source.getText(0));
}

Otros consejos

    public XWPFParagraph copyParagraph(int currentParagraphIndex)
    {
        List<XWPFParagraph> paragraphs = wordDocument.getParagraphs();

        //get whatever paragraph we're working with from the list
        XWPFParagraph paragraph = paragraphs.get(currentParagraphIndex);

        XmlCursor cursor = paragraph.getCTP().newCursor();
        //inserts a blank paragraph before the original one
        paragraph.getDocument().insertNewParagraph(cursor);

        //make a fully parsed copy of the old paragraph
        XWPFParagraph newParagraph = new XWPFParagraph((CTP) paragraph.getCTP().copy(),wordDocument);

        //update the document with our now paragraph replacing the blank one with our new one and cause the document to reparse it. 
        //Not sure why, but any modification to the new paragraph must be performed prior to setting it. 
        wordDocument.setParagraph(newParagraph,currentParagraphIndex);

        return newParagraph;
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top