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

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

Introduction

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

Prototype

@Internal
public CTR getCTR() 

Source Link

Document

Get the currently used CTR object

Usage

From source file:mj.ocraptor.extraction.tika.parser.microsoft.ooxml.XWPFWordExtractorDecorator.java

License:Apache License

private void extractParagraph(XWPFParagraph paragraph, XHTMLContentHandler xhtml)
        throws SAXException, XmlException, IOException {
    // If this paragraph is actually a whole new section, then
    // it could have its own headers and footers
    // Check and handle if so
    XWPFHeaderFooterPolicy headerFooterPolicy = null;
    if (paragraph.getCTP().getPPr() != null) {
        CTSectPr ctSectPr = paragraph.getCTP().getPPr().getSectPr();
        if (ctSectPr != null) {
            headerFooterPolicy = new XWPFHeaderFooterPolicy(document, ctSectPr);
            extractHeaders(xhtml, headerFooterPolicy);
        }//w  w  w . j  a  va2s .  c o  m
    }

    // Is this a paragraph, or a heading?
    String tag = "p";
    String styleClass = null;
    if (paragraph.getStyleID() != null) {
        XWPFStyle style = styles.getStyle(paragraph.getStyleID());

        if (style != null && style.getName() != null) {
            TagAndStyle tas = WordExtractor.buildParagraphTagAndStyle(style.getName(),
                    paragraph.getPartType() == BodyType.TABLECELL);
            tag = tas.getTag();
            styleClass = tas.getStyleClass();
        }
    }

    if (styleClass == null) {
        xhtml.startElement(tag);
    } else {
        xhtml.startElement(tag, "class", styleClass);
    }

    // Output placeholder for any embedded docs:

    // TODO: replace w/ XPath/XQuery:
    for (XWPFRun run : paragraph.getRuns()) {
        XmlCursor c = run.getCTR().newCursor();
        c.selectPath("./*");
        while (c.toNextSelection()) {
            XmlObject o = c.getObject();
            if (o instanceof CTObject) {
                XmlCursor c2 = o.newCursor();
                c2.selectPath("./*");
                while (c2.toNextSelection()) {
                    XmlObject o2 = c2.getObject();

                    XmlObject embedAtt = o2.selectAttribute(new QName("Type"));
                    if (embedAtt != null && embedAtt.getDomNode().getNodeValue().equals("Embed")) {
                        // Type is "Embed"
                        XmlObject relIDAtt = o2.selectAttribute(new QName(
                                "http://schemas.openxmlformats.org/officeDocument/2006/relationships", "id"));
                        if (relIDAtt != null) {
                            String relID = relIDAtt.getDomNode().getNodeValue();
                            AttributesImpl attributes = new AttributesImpl();
                            attributes.addAttribute("", "class", "class", "CDATA", "embedded");
                            attributes.addAttribute("", "id", "id", "CDATA", relID);
                            xhtml.startElement("div", attributes);
                            xhtml.endElement("div");
                        }
                    }
                }
                c2.dispose();
            }
        }

        c.dispose();
    }

    // Attach bookmarks for the paragraph
    // (In future, we might put them in the right place, for now
    // we just put them in the correct paragraph)
    for (CTBookmark bookmark : paragraph.getCTP().getBookmarkStartList()) {
        xhtml.startElement("a", "name", bookmark.getName());
        xhtml.endElement("a");
    }

    TmpFormatting fmtg = new TmpFormatting(false, false);

    // Do the iruns
    for (IRunElement run : paragraph.getIRuns()) {
        if (run instanceof XWPFSDT) {
            fmtg = closeStyleTags(xhtml, fmtg);
            processSDTRun((XWPFSDT) run, xhtml);
            // for now, we're ignoring formatting in sdt
            // if you hit an sdt reset to false
            fmtg.setBold(false);
            fmtg.setItalic(false);
        } else {
            fmtg = processRun((XWPFRun) run, paragraph, xhtml, fmtg);
        }
    }
    closeStyleTags(xhtml, fmtg);

    // Now do any comments for the paragraph
    XWPFCommentsDecorator comments = new XWPFCommentsDecorator(paragraph, null);
    String commentText = comments.getCommentText();
    if (commentText != null && commentText.length() > 0) {
        xhtml.characters(commentText);
    }

    String footnameText = paragraph.getFootnoteText();
    if (footnameText != null && footnameText.length() > 0) {
        xhtml.characters(footnameText + "\n");
    }

    // Also extract any paragraphs embedded in text boxes:
    for (XmlObject embeddedParagraph : paragraph.getCTP().selectPath(
            "declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' declare namespace wps='http://schemas.microsoft.com/office/word/2010/wordprocessingShape' .//*/wps:txbx/w:txbxContent/w:p")) {
        extractParagraph(new XWPFParagraph(CTP.Factory.parse(embeddedParagraph.xmlText()), paragraph.getBody()),
                xhtml);
    }

    // Finish this paragraph
    xhtml.endElement(tag);

    if (headerFooterPolicy != null) {
        extractFooters(xhtml, headerFooterPolicy);
    }
}

From source file:offishell.word.WordHeleper.java

License:MIT License

/**
 * <p>//  w ww  .  j  a va2  s.c om
 * Helper method to remove all comments from the specified paragraph.
 * </p>
 * 
 * @param paragraph A target paragraph.
 */
public static void clearComment(XWPFParagraph paragraph) {
    if (paragraph != null) {
        CTP pContext = paragraph.getCTP();

        for (int i = pContext.sizeOfCommentRangeStartArray() - 1; 0 <= i; i--) {
            pContext.removeCommentRangeStart(i);
        }

        for (int i = pContext.sizeOfCommentRangeEndArray() - 1; 0 <= i; i--) {
            pContext.removeCommentRangeEnd(i);
        }

        for (XWPFRun run : paragraph.getRuns()) {
            CTR rContext = run.getCTR();

            for (int i = rContext.sizeOfCommentReferenceArray() - 1; 0 <= i; i--) {
                rContext.removeCommentReference(i);
            }
        }
    }
}

From source file:offishell.word.WordHeleper.java

License:MIT License

/**
 * <p>/*  w  w w.  ja v  a  2 s.c  om*/
 * Helper method to clone {@link XWPFRun}.
 * </p>
 * 
 * @param in
 * @param out
 * @param model
 */
public static void copy(XWPFRun in, XWPFRun out, UnaryOperator<String> converter) {
    // copy
    out.setBold(in.isBold());
    out.setCapitalized(in.isCapitalized());
    out.setCharacterSpacing(in.getCharacterSpacing());
    out.setColor(in.getColor());
    out.setDoubleStrikethrough(in.isDoubleStrikeThrough());
    out.setEmbossed(in.isEmbossed());
    out.setFontFamily(in.getFontFamily());
    out.setFontSize(in.getFontSize());
    out.setImprinted(in.isImprinted());
    out.setItalic(in.isItalic());
    out.setKerning(in.getKerning());
    out.setShadow(in.isShadowed());
    out.setSmallCaps(in.isSmallCaps());
    out.setStrikeThrough(in.isStrikeThrough());
    out.setVerticalAlignment(out.getVerticalAlignment().toString());
    out.setTextPosition(in.getTextPosition());
    out.setUnderline(in.getUnderline());

    // copy context
    CTR inCTR = in.getCTR();
    CTRPr inPR = inCTR.getRPr();
    CTR outCTR = out.getCTR();
    CTRPr outPR = outCTR.isSetRPr() ? outCTR.getRPr() : outCTR.addNewRPr();
    outPR.set(inCTR.getRPr());
    out.setVerticalAlignment(
            inPR == null || inPR.getVertAlign() == null ? "baseline" : inPR.getVertAlign().toString());

    // // copy tab
    // CTEmpty[] tabs = inCTR.getTabArray();
    //
    // if (tabs.length != 0) {
    // out.addTab();
    // }
    outCTR.setAnnotationRefArray(inCTR.getAnnotationRefList().toArray(CTEmpty[]::new));
    outCTR.setBrArray(inCTR.getBrList().toArray(CTBr[]::new));
    outCTR.setCommentReferenceArray(inCTR.getCommentReferenceList().toArray(CTMarkup[]::new));
    outCTR.setContinuationSeparatorArray(inCTR.getContinuationSeparatorList().toArray(CTEmpty[]::new));
    outCTR.setCrArray(inCTR.getCrList().toArray(CTEmpty[]::new));
    outCTR.setDelInstrTextArray(inCTR.getDelInstrTextList().toArray(CTText[]::new));
    outCTR.setDrawingArray(inCTR.getDrawingList().toArray(CTDrawing[]::new));
    outCTR.setEndnoteRefArray(inCTR.getEndnoteRefList().toArray(CTEmpty[]::new));
    outCTR.setFldCharArray(inCTR.getFldCharList().toArray(CTFldChar[]::new));
    outCTR.setFootnoteRefArray(inCTR.getFootnoteRefList().toArray(CTEmpty[]::new));
    outCTR.setInstrTextArray(inCTR.getInstrTextList().toArray(CTText[]::new));
    outCTR.setLastRenderedPageBreakArray(inCTR.getLastRenderedPageBreakList().toArray(CTEmpty[]::new));
    outCTR.setObjectArray(inCTR.getObjectList().toArray(CTObject[]::new));
    outCTR.setPictArray(inCTR.getPictList().toArray(CTPicture[]::new));
    outCTR.setPtabArray(inCTR.getPtabList().toArray(CTPTab[]::new));
    outCTR.setSymArray(inCTR.getSymList().toArray(CTSym[]::new));
    outCTR.setTabArray(inCTR.getTabList().toArray(CTEmpty[]::new));

    // copy image
    for (XWPFPicture inPicture : in.getEmbeddedPictures()) {
        try {
            XWPFPictureData inData = inPicture.getPictureData();
            String outId = out.getDocument().addPictureData(new ByteArrayInputStream(inData.getData()),
                    inData.getPictureType());

            select(CTBlip.class, outCTR).to(blip -> blip.setEmbed(outId));
        } catch (Exception e) {
            throw I.quiet(e);
        }
    }

    // copy text
    write(out, converter.apply(in.text()));
}

From source file:org.apache.tika.parser.microsoft.ooxml.XWPFWordExtractorDecorator.java

License:Apache License

private void extractParagraph(XWPFParagraph paragraph, XWPFListManager listManager, XHTMLContentHandler xhtml)
        throws SAXException, XmlException, IOException {
    // If this paragraph is actually a whole new section, then
    //  it could have its own headers and footers
    // Check and handle if so
    XWPFHeaderFooterPolicy headerFooterPolicy = null;
    if (paragraph.getCTP().getPPr() != null) {
        CTSectPr ctSectPr = paragraph.getCTP().getPPr().getSectPr();
        if (ctSectPr != null) {
            headerFooterPolicy = new XWPFHeaderFooterPolicy(document, ctSectPr);
            extractHeaders(xhtml, headerFooterPolicy, listManager);
        }/*w ww .j a  v  a  2 s. com*/
    }

    // Is this a paragraph, or a heading?
    String tag = "p";
    String styleClass = null;
    if (paragraph.getStyleID() != null) {
        XWPFStyle style = styles.getStyle(paragraph.getStyleID());

        if (style != null && style.getName() != null) {
            TagAndStyle tas = WordExtractor.buildParagraphTagAndStyle(style.getName(),
                    paragraph.getPartType() == BodyType.TABLECELL);
            tag = tas.getTag();
            styleClass = tas.getStyleClass();
        }
    }

    if (styleClass == null) {
        xhtml.startElement(tag);
    } else {
        xhtml.startElement(tag, "class", styleClass);
    }

    writeParagraphNumber(paragraph, listManager, xhtml);
    // Output placeholder for any embedded docs:

    // TODO: replace w/ XPath/XQuery:
    for (XWPFRun run : paragraph.getRuns()) {
        XmlCursor c = run.getCTR().newCursor();
        c.selectPath("./*");
        while (c.toNextSelection()) {
            XmlObject o = c.getObject();
            if (o instanceof CTObject) {
                XmlCursor c2 = o.newCursor();
                c2.selectPath("./*");
                while (c2.toNextSelection()) {
                    XmlObject o2 = c2.getObject();

                    XmlObject embedAtt = o2.selectAttribute(new QName("Type"));
                    if (embedAtt != null && embedAtt.getDomNode().getNodeValue().equals("Embed")) {
                        // Type is "Embed"
                        XmlObject relIDAtt = o2.selectAttribute(new QName(
                                "http://schemas.openxmlformats.org/officeDocument/2006/relationships", "id"));
                        if (relIDAtt != null) {
                            String relID = relIDAtt.getDomNode().getNodeValue();
                            AttributesImpl attributes = new AttributesImpl();
                            attributes.addAttribute("", "class", "class", "CDATA", "embedded");
                            attributes.addAttribute("", "id", "id", "CDATA", relID);
                            xhtml.startElement("div", attributes);
                            xhtml.endElement("div");
                        }
                    }
                }
                c2.dispose();
            }
        }

        c.dispose();
    }

    // Attach bookmarks for the paragraph
    // (In future, we might put them in the right place, for now
    //  we just put them in the correct paragraph)
    for (int i = 0; i < paragraph.getCTP().sizeOfBookmarkStartArray(); i++) {
        CTBookmark bookmark = paragraph.getCTP().getBookmarkStartArray(i);
        xhtml.startElement("a", "name", bookmark.getName());
        xhtml.endElement("a");
    }

    TmpFormatting fmtg = new TmpFormatting(false, false);

    // Do the iruns
    for (IRunElement run : paragraph.getIRuns()) {
        if (run instanceof XWPFSDT) {
            fmtg = closeStyleTags(xhtml, fmtg);
            processSDTRun((XWPFSDT) run, xhtml);
            //for now, we're ignoring formatting in sdt
            //if you hit an sdt reset to false
            fmtg.setBold(false);
            fmtg.setItalic(false);
        } else {
            fmtg = processRun((XWPFRun) run, paragraph, xhtml, fmtg);
        }
    }
    closeStyleTags(xhtml, fmtg);

    // Now do any comments for the paragraph
    XWPFCommentsDecorator comments = new XWPFCommentsDecorator(paragraph, null);
    String commentText = comments.getCommentText();
    if (commentText != null && commentText.length() > 0) {
        xhtml.characters(commentText);
    }

    String footnameText = paragraph.getFootnoteText();
    if (footnameText != null && footnameText.length() > 0) {
        xhtml.characters(footnameText + "\n");
    }

    // Also extract any paragraphs embedded in text boxes:
    for (XmlObject embeddedParagraph : paragraph.getCTP().selectPath(
            "declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' declare namespace wps='http://schemas.microsoft.com/office/word/2010/wordprocessingShape' .//*/wps:txbx/w:txbxContent/w:p")) {
        extractParagraph(new XWPFParagraph(CTP.Factory.parse(embeddedParagraph.xmlText()), paragraph.getBody()),
                listManager, xhtml);
    }

    // Finish this paragraph
    xhtml.endElement(tag);

    if (headerFooterPolicy != null) {
        extractFooters(xhtml, headerFooterPolicy, listManager);
    }
}

From source file:org.articleEditor.insertContent.DocumentUpdater1.java

License:Apache License

DocumentPosition createRun(XWPFParagraph paragraph) {
    XWPFRun run = paragraph.createRun();
    DocumentPosition position = new DocumentPosition();
    position.run = run;/*from w w  w  . j a va2 s . co m*/
    position.text = run.getCTR().addNewT();
    return position;
}

From source file:org.articleEditor.insertContent.DocumentUpdater1.java

License:Apache License

DocumentPosition searchRun(XWPFRun run, int offset) throws BadLocationException {
    for (XWPFPicture picture : run.getEmbeddedPictures()) {
        // currentOffset++;
    }//from   ww w  .  ja  v  a 2  s . co  m
    List<CTText> texts = run.getCTR().getTList();
    int textIndex = 0;
    for (CTText text : texts) {
        String textValue = text.getStringValue();
        int textLength = textValue.length();
        if (currentOffset + textLength >= offset) {// || (currentOffset + textLength == offset && !textValue.endsWith("\n"))) {
            DocumentPosition position = new DocumentPosition();
            position.run = run;
            position.text = text;
            position.offsetInText = offset - currentOffset;
            position.positionInRun = textIndex;
            return position;
        } else {
            currentOffset += textLength;
        }
        textIndex++;
    }
    return null;
}

From source file:org.articleEditor.insertContent.POIDocxReader.java

License:Apache License

protected void processRun(XWPFRun run) throws BadLocationException {
    charAttrs = new SimpleAttributeSet();

    if (run.getFontSize() > 0) {
        int size = run.getFontSize();
        StyleConstants.setFontSize(charAttrs, size);
    }/*w  w w. j  av a 2s  .  com*/
    StyleConstants.setBold(charAttrs, run.isBold());
    StyleConstants.setItalic(charAttrs, run.isItalic());
    StyleConstants.setStrikeThrough(charAttrs, run.isStrike());
    boolean underlined = run.getUnderline() != UnderlinePatterns.NONE;
    StyleConstants.setUnderline(charAttrs, underlined);
    VerticalAlign verticalAlignment = run.getSubscript();
    if (verticalAlignment == VerticalAlign.SUBSCRIPT) {
        StyleConstants.setSubscript(parAttrs, true);
    } else if (verticalAlignment == VerticalAlign.SUPERSCRIPT) {
        StyleConstants.setSuperscript(parAttrs, true);
    } else {
        StyleConstants.setSubscript(parAttrs, false);
        StyleConstants.setSuperscript(parAttrs, false);
    }
    if (run.getFontFamily() != null) {
        StyleConstants.setFontFamily(charAttrs, run.getFontFamily());
    }
    if (run.getColor() != null) {
        String name = run.getColor();
        if (!name.toLowerCase().equals("auto")) {
            Color color = Color.decode("#" + name);
            StyleConstants.setForeground(charAttrs, color);
        }
    }

    // Not working
    if (run.getCTR().getRPr() != null && run.getCTR().getRPr().getHighlight() != null) {
        STHighlightColor.Enum colorEnum = run.getCTR().getRPr().getHighlight().getVal();
        Color color = decodeHighlightName(colorEnum);
        StyleConstants.setBackground(charAttrs, color);
    }

    for (XWPFPicture picture : run.getEmbeddedPictures()) {
        processPicture(picture);
    }
    String text = run.toString();
    document.insertString(currentOffset, text, charAttrs);
    currentOffset += text.length();
}

From source file:org.joeffice.wordprocessor.DocumentTreeTopComponent.java

License:Apache License

public void buildRun(DefaultMutableTreeNode root, XWPFRun run) {
    List<CTText> texts = run.getCTR().getTList();
    for (CTText text : texts) {
        String nodeText = run.getClass().getSimpleName() + ":" + currentOffset;
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(nodeText);
        root.add(node);/*from w  ww. jav  a 2  s.  c  o  m*/
        buildCTText(node, text);
    }
}

From source file:org.obeonetwork.m2doc.generator.BookmarkManager.java

License:Open Source License

/**
 * Inserts a reference to the given {@link CTBookmark} with the given text in the given {@link XWPFParagraph}.
 * /*w w  w . ja  va 2 s.c o m*/
 * @param paragraph
 *            the {@link XWPFParagraph}
 * @param name
 *            the bookmark name
 * @param text
 *            the text
 * @return the {@link CTText} corresponding to the reference.
 */
private CTText insertPendingReference(XWPFParagraph paragraph, String name, String text) {
    final byte[] id = getReferenceID(name);
    final XWPFRun beginRun = paragraph.createRun();
    beginRun.getCTR().setRsidR(id);
    beginRun.getCTR().addNewFldChar().setFldCharType(STFldCharType.BEGIN);

    final XWPFRun preservedRun = paragraph.createRun();
    preservedRun.getCTR().setRsidR(id);
    final CTText pgcttext = preservedRun.getCTR().addNewInstrText();
    pgcttext.setSpace(Space.PRESERVE);

    final XWPFRun separateRun = paragraph.createRun();
    separateRun.getCTR().setRsidR(id);
    separateRun.getCTR().addNewFldChar().setFldCharType(STFldCharType.SEPARATE);

    final XWPFRun textRun = paragraph.createRun();
    textRun.getCTR().setRsidR(id);
    textRun.getCTR().addNewRPr().addNewNoProof();
    textRun.setText(text);
    textRun.setBold(true);

    final XWPFRun endRun = paragraph.createRun();
    endRun.getCTR().setRsidR(id);
    endRun.getCTR().addNewFldChar().setFldCharType(STFldCharType.END);

    return pgcttext;
}

From source file:org.obeonetwork.m2doc.generator.M2DocEvaluator.java

License:Open Source License

/**
 * Inserts a run in the generated document. The new run is a copy from the specified run.
 * //from   w w  w.  j a  v a 2 s .co m
 * @param srcRun
 *            the run to copy
 * @return the inserted run.
 */
private XWPFRun insertRun(XWPFRun srcRun) {
    if (srcRun.getParent() != currentTemplateParagraph || forceNewParagraph) {
        createNewParagraph((XWPFParagraph) srcRun.getParent());
        forceNewParagraph = false;
    }
    XWPFRun newRun = null;
    if (srcRun instanceof XWPFHyperlinkRun) {
        // Hyperlinks meta information is saved in the paragraph and not in the run. So we have to update the paragrapah with a copy of
        // the hyperlink to insert.
        CTHyperlink newHyperlink = currentGeneratedParagraph.getCTP().addNewHyperlink();
        newHyperlink.set(((XWPFHyperlinkRun) srcRun).getCTHyperlink());

        newRun = new XWPFHyperlinkRun(newHyperlink, srcRun.getCTR(), srcRun.getParent());
        currentGeneratedParagraph.addRun(newRun);
    } else {
        newRun = currentGeneratedParagraph.createRun();
        newRun.getCTR().set(srcRun.getCTR());
    }
    return newRun;
}