Example usage for org.apache.poi.xwpf.usermodel XWPFRun setText

List of usage examples for org.apache.poi.xwpf.usermodel XWPFRun setText

Introduction

In this page you can find the example usage for org.apache.poi.xwpf.usermodel XWPFRun setText.

Prototype

public void setText(String value, int pos) 

Source Link

Document

Sets the text of this text run in the

Usage

From source file:b01.officeLink.ExtendedWordDocument.java

License:Apache License

private void replaceInRun(XWPFRun run, String replaceWith) {
    boolean firstSet = true;

    String remainingFragment = replaceWith;
    while (remainingFragment.contains("\n")) {
        int indexOfEnter = remainingFragment.indexOf("\n");
        String firstPart = remainingFragment.substring(0, indexOfEnter);
        remainingFragment = remainingFragment.substring(indexOfEnter + 1, remainingFragment.length());
        if (firstSet) {
            run.setText(firstPart, 0);
            firstSet = false;//from w w w  . java2 s.c  o  m
        } else {
            run.setText(firstPart);//,0
        }
        run.addBreak();
    }
    if (!Utils.isStringEmpty(remainingFragment) || firstSet) {
        if (firstSet) {
            run.setText(remainingFragment, 0);
        } else {
            run.setText(remainingFragment);
        }
    }
}

From source file:b01.officeLink.ExtendedWordDocument.java

License:Apache License

public boolean replaceInParagraph(XWPFParagraph para, String toReplace, String replaceWith) {
    boolean didReplace = false;

    if (para != null && toReplace != null && replaceWith != null) {
        //        setOrientation(para);

        List<XWPFRun> runs = para.getRuns();
        TextSegement found = para.searchText(toReplace, new PositionInParagraph());
        if (found != null) {
            if (found.getBeginRun() == found.getEndRun()) {
                // whole search string is in one Run
                XWPFRun run = runs.get(found.getBeginRun());
                String runText = run.getText(run.getTextPosition());

                //Support of Enter to transform it to a line break
                //------------------------------------------------
                String replaced = runText.replace(toReplace, replaceWith);
                replaceInRun(run, replaced);
                //------------------------------------------------
                //            run.setText(replaced, 0);
                //------------------------------------------------

                didReplace = true;//from  w w  w  .ja  v a 2  s.c o m
            } else {
                // The search string spans over more than one Run
                // Put the Strings together
                StringBuilder b = new StringBuilder();
                for (int runPos = found.getBeginRun(); runPos <= found.getEndRun(); runPos++) {
                    XWPFRun run = runs.get(runPos);
                    b.append(run.getText(run.getTextPosition()));
                }
                String connectedRuns = b.toString();
                String replaced = connectedRuns.replace(toReplace, replaceWith);

                // The first Run receives the replaced String of all connected Runs
                XWPFRun partOne = runs.get(found.getBeginRun());
                //Support of Enter to transform it to a line break
                //------------------------------------------------
                replaceInRun(partOne, replaced);//replaceWith
                //partOne.setText(replaced, 0);
                //------------------------------------------------

                // Removing the text in the other Runs.
                for (int runPos = found.getBeginRun() + 1; runPos <= found.getEndRun(); runPos++) {
                    XWPFRun partNext = runs.get(runPos);
                    partNext.setText("", 0);
                }
                didReplace = true;
            }
        }
    }
    return didReplace;
}

From source file:biz.webgate.dominoext.poi.component.kernel.DocumentProcessor.java

License:Apache License

public int processBookmarks2Run(XWPFRun runCurrent, List<IDocumentBookmark> arrBookmarks) {
    String strText = runCurrent.getText(0);
    if (strText != null) {
        for (IDocumentBookmark bmCurrent : arrBookmarks) {
            String strValue = bmCurrent.getValue();
            strValue = strValue == null ? "" : strValue;
            if (bmCurrent.getName() != null) {
                strText = strText.replaceAll("<<" + bmCurrent.getName() + ">>", strValue);
            }//from w w  w  . j  a  va2 s .co m
        }
    }
    runCurrent.setText(strText, 0);
    return 1;
}

From source file:ch.admin.searchreplace.SearchReplace.java

License:Apache License

/**
 * Called to perform the search and replace operation. This method will begin with the first character run in
 * the first paragraph of text and process each. through to the end of the document. The process is essentially
 * this; * Get a paragraph from the document. * Get the runs of text from that paragraph. * Enumerate through
 * the keys in the search text/replacement term Hashtable and check to see whether the search tearm (the key)
 * can be found in the run. If it can be found, replace the search term with it's associated replacement text
 * and write the results back into the run. * Store the Word document away agin following processing. Note that
 * there is currently no provision made for writing the resulting document away under a different file name.
 * This would be a trivial change to make however.
 * //from  w ww  .ja va  2 s  .c  o m
 * @throws java.io.FileNotFoundException Thrown if a problem occurs in the underlying file system whilst trying
 *             to open a FileOutputStream attached to the Word document.
 * @throws java.io.IOException Thrown if a problem occurs in the underlying file system whilst trying to store
 *             the Word document away.
 */
public void searchReplace() throws FileNotFoundException, IOException {

    // Recover an Iterator to step through the XWPFParagraph objects
    // 'contained' with the Word document.
    Iterator<XWPFParagraph> parasIter = this.doc.getParagraphsIterator();
    Iterator<XWPFRun> runsIter = null;
    Enumeration<String> srchTermEnum = null;
    XWPFParagraph para = null;
    XWPFRun run = null;
    List<XWPFRun> runsList = null;
    String searchTerm = null;
    String runText = null;
    String replacementText = null;
    OutputStream os = null;

    // Step through the XWPFParagraph object one at a time.
    while (parasIter.hasNext()) {
        para = parasIter.next();

        // Recover a List of XWPFRun objects from the XWPFParagraph and an
        // Iterator from this List.
        runsList = para.getRuns();
        runsIter = runsList.iterator();

        // Use the Iterator to step through the XWPFRun objects.
        while (runsIter.hasNext()) {

            // Get a run and it's text
            run = runsIter.next();
            runText = run.getText(0);

            // Recover an Enumeration object 'containing' the set of
            // search terms and then step through these terms looking
            // for match in the run's text
            srchTermEnum = this.srTerms.keys();
            while (srchTermEnum.hasMoreElements()) {
                searchTerm = srchTermEnum.nextElement();

                // If a match is found, use the replacement text to substitute
                // for the search term and update the runs text.
                if (runText.contains(searchTerm)) {
                    replacementText = this.srTerms.get(searchTerm);

                    // Note the use of the replaceAll() method here. It will,
                    // obviously, replace all occurrences of the search term
                    // with the replacement text. This may not be what is
                    // required but is easy to modify by changing the logic
                    // slightly and using the replaceFirst() or replace()
                    // methods.
                    runText = runText.replaceAll(searchTerm, replacementText);
                    run.setText(runText, 0);
                }
            }
        }
    }
    os = new FileOutputStream(this.sourceFile);
    this.doc.write(os);
}

From source file:ch.admin.searchreplace.SearchReplaceTerms.java

License:Apache License

/**
 * Konsolidiert die Runs eines Paragraphen in einen. Ansonsten koennen Texte nicht sauber 
 * ersetzt werden, bzw. werden nicht gefunden, weil ueber mehrere Runs verteilt.
 * @param para Paragraph//from  w  ww . j  a  v a  2 s.c o  m
 * @return Konsolidierter Run
 */
private static XWPFRun consolidateRuns(XWPFParagraph para) {
    StringBuffer text = new StringBuffer();
    int count = 0;
    for (XWPFRun r : para.getRuns()) {
        text.append(r.getText(0));
        count++;
    }
    for (int i = count - 1; i >= 1; i--)
        para.removeRun(i);
    if (count == 0)
        return (null);

    XWPFRun r = para.getRuns().get(0);
    r.setText(text.toString(), 0);
    return (r);
}

From source file:ch.admin.searchreplace.SearchReplaceTerms.java

License:Apache License

/**
 * @param srTerms/* ww  w . java  2  s  .  com*/
 * @param r
 */
private static void searchReplace(HashMap<String, String> srTerms, XWPFRun r) {
    String text = r.getText(0);
    System.out.println(text);
    for (Map.Entry<String, String> sr : srTerms.entrySet()) {
        if (text.contains(sr.getKey())) {
            text = text.replace(sr.getKey(), sr.getValue());
            r.setText(text, 0);
        }
        // Vergleich mit 1. Buchstaben in Kleinbuchstaben
        String search2 = sr.getKey().substring(0, 1).toLowerCase() + sr.getKey().substring(1);
        if (text.contains(search2)) {
            text = text.replace(search2,
                    sr.getValue().substring(0, 1).toLowerCase() + sr.getValue().substring(1));
            r.setText(text, 0);
        }
    }
}

From source file:cn.afterturn.easypoi.util.PoiPublicUtil.java

License:Apache License

/**
 * ???/*from w w w  .j  a va  2 s  .com*/
 * @param currentRun
 * @param currentText
 */
public static void setWordText(XWPFRun currentRun, String currentText) {
    if (StringUtils.isNotEmpty(currentText)) {
        String[] tempArr = currentText.split("\r\n");
        for (int i = 0, le = tempArr.length - 1; i < le; i++) {
            currentRun.setText(tempArr[i], i);
            currentRun.addBreak();
        }
        currentRun.setText(tempArr[tempArr.length - 1], tempArr.length - 1);
    }
}

From source file:cn.afterturn.easypoi.word.parse.ParseWord07.java

License:Apache License

/**
 * ???//from  w w  w .j  a  va2  s.c o  m
 *
 * @param map
 * @author JueYue
 * 2013-11-16
 */
private void changeValues(XWPFParagraph paragraph, XWPFRun currentRun, String currentText,
        List<Integer> runIndex, Map<String, Object> map) throws Exception {
    Object obj = PoiPublicUtil.getRealValue(currentText, map);
    if (obj instanceof ImageEntity) {// 
        currentRun.setText("", 0);
        ExcelMapParse.addAnImage((ImageEntity) obj, currentRun);
    } else {
        currentText = obj.toString();
        PoiPublicUtil.setWordText(currentRun, currentText);
    }
    for (int k = 0; k < runIndex.size(); k++) {
        paragraph.getRuns().get(runIndex.get(k)).setText("", 0);
    }
    runIndex.clear();
}

From source file:colina.angel.controller.CreadorController.java

public void changeText(XWPFParagraph paragraph, String newText) {
    List<XWPFRun> runs = paragraph.getRuns();
    for (int i = runs.size() - 1; i > 0; i--) {
        paragraph.removeRun(i);//from ww w  . j a v  a2  s.  co m
    }
    XWPFRun run = runs.get(0);
    run.setText(newText, 0);

}

From source file:com.altar.worddocreader.WordDocReaderMain.java

public static XWPFDocument replaceText(XWPFDocument doc, HashMap<String, String> keys) throws Exception {
    String txt = "";
    int txtPosition = 0;
    String key = "";
    String val = "";
    for (XWPFParagraph p : doc.getParagraphs()) { //Dkmandaki her bir paragraf okumas yaplyor.
        for (XWPFRun run : p.getRuns()) { //paragraf iindeki satrlar okunuyor.
            txtPosition = run.getTextPosition();
            txt = run.getText(txtPosition);
            for (Map.Entry<String, String> entry : keys.entrySet()) { //keymap iinde gnderilen alanlar keymap'teki deerleri ile deitiriliyor.
                key = entry.getKey();//from w ww.j a va 2  s  . co m
                val = entry.getValue();
                if (txt != null && txt.indexOf(key) > -1) {
                    txt = txt.replace(key, val);
                    run.setText(txt, 0);
                }
            }
        }
    }

    return doc;

}