Java Code Examples for org.apache.poi.xwpf.usermodel.XWPFRun#getParent()

The following examples show how to use org.apache.poi.xwpf.usermodel.XWPFRun#getParent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Inserts a run in the generated document. The new run is a copy from the specified run.
 * 
 * @param paragraph
 *            the {@link XWPFParagraph} to modify
 * @param srcRun
 *            the run to copy
 * @return the inserted {@link XWPFRun}
 */
private XWPFRun insertRun(XWPFParagraph paragraph, XWPFRun srcRun) {

    final XWPFParagraph newParagraph;
    if (srcRun.getParent() != currentTemplateParagraph || forceNewParagraph) {
        newParagraph = createNewParagraph(generatedDocument, (XWPFParagraph) srcRun.getParent());
        forceNewParagraph = false;
    } else {
        newParagraph = paragraph;
    }

    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 = newParagraph.getCTP().addNewHyperlink();
        newHyperlink.set(((XWPFHyperlinkRun) srcRun).getCTHyperlink());

        newRun = new XWPFHyperlinkRun(newHyperlink, srcRun.getCTR(), srcRun.getParent());
        newParagraph.addRun(newRun);
    } else {
        newRun = newParagraph.createRun();
        newRun.getCTR().set(srcRun.getCTR());
    }
    return newRun;
}
 
Example 2
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Inserts the given {@link MHyperLink}.
 * 
 * @param paragraph
 *            the {@link XWPFParagraph} to modify
 * @param run
 *            the {@link XWPFRun}
 * @param hyperLink
 *            the {@link MHyperLink}
 * @return the {@link XWPFParagraph} where the hyperling was inserted
 */
private XWPFParagraph insertMHyperLink(XWPFParagraph paragraph, XWPFRun run, MHyperLink hyperLink) {
    final XWPFRun linkRun = insertMText(paragraph, run, hyperLink);
    final XWPFParagraph res = (XWPFParagraph) linkRun.getParent();

    final String id = res.getBody().getPart().getPackagePart()
            .addExternalRelationship(hyperLink.getUrl(), XWPFRelation.HYPERLINK.getRelation()).getId();
    final CTHyperlink cLink = res.getCTP().addNewHyperlink();
    cLink.setId(id);

    if (hyperLink.getStyle() != null) {
        applyMStyle(linkRun, hyperLink.getStyle());
    }
    cLink.setRArray(new CTR[] {linkRun.getCTR() });
    res.removeRun(res.getRuns().indexOf(linkRun));

    return res;
}
 
Example 3
Source File: BookmarkManager.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Ends the bookmark with the given name.
 * 
 * @param result
 *            the {@link GenerationResult}
 * @param paragraph
 *            the current {@link XWPFParagraph}
 * @param name
 *            the bookmark name
 */
public void endBookmark(GenerationResult result, XWPFParagraph paragraph, String name) {
    final CTBookmark bookmark = startedBookmarks.remove(name);
    if (bookmark != null) {
        final CTMarkupRange range = paragraph.getCTP().addNewBookmarkEnd();
        range.setId(bookmarks.get(name).getId());
        // we remove the run created for error messages.
        final XWPFRun run = messagePositions.get(bookmark);
        final IRunBody parent = run.getParent();
        if (parent instanceof XWPFParagraph) {
            ((XWPFParagraph) parent).removeRun(((XWPFParagraph) parent).getRuns().indexOf(run));
        } else {
            throw new IllegalStateException("this should not happend");
        }
    } else if (bookmarks.containsKey(name)) {
        result.addMessage(M2DocUtils.appendMessageRun(paragraph, ValidationMessageLevel.ERROR,
                "Can't end already closed bookmark " + name));
    } else {
        result.addMessage(M2DocUtils.appendMessageRun(paragraph, ValidationMessageLevel.ERROR,
                "Can't end not existing bookmark " + name));
    }
}
 
Example 4
Source File: CellBodyContainer.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
@Override
public void clearPlaceholder(XWPFRun run) {
    IRunBody parent = run.getParent();
    run.setText("", 0);
    // 遇到不明确的单元格匹配问题, 可能丢失段落元素,<p>元素必须位于</tc>元素之前
    if (parent instanceof XWPFParagraph) {
        String paragraphText = ParagraphUtils.trimLine((XWPFParagraph) parent);
        if ("".equals(paragraphText)) {
            int pos = getPosOfParagraph((XWPFParagraph) parent);
            int lastPos = cell.getBodyElements().size() - 1;
            if (canRemoveParagraph(pos, lastPos)) {
                removeBodyElement(pos);
            }
        }
    }
}
 
Example 5
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Inserts a run in the generated document and set it's text to the specified replacement. The new run is a copy from the specified run.
 * 
 * @param paragraph
 *            the {@link XWPFParagraph} to modify
 * @param srcRun
 *            the run to copy
 * @param replacement
 *            the text to set
 * @return the inserted run
 */
private XWPFRun insertFieldRunReplacement(XWPFParagraph paragraph, XWPFRun srcRun, String replacement) {
    final XWPFParagraph newParagraph;
    if (srcRun.getParent() != currentTemplateParagraph || forceNewParagraph) {
        newParagraph = createNewParagraph(generatedDocument, (XWPFParagraph) srcRun.getParent());
        forceNewParagraph = false;
    } else {
        newParagraph = paragraph;
    }

    return insertString(newParagraph, srcRun, replacement);
}
 
Example 6
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Closes the generation of the given {@link Repetition}.
 * if the end of {@link Repetition} lies on a distinct paragraph, insert a new
 * paragraph there to take this into account.
 * 
 * @param repetition
 *            {@link Repetition} to close
 */
private void closingRepretition(Repetition repetition) {
    final int bodySize = repetition.getBody().getStatements().size();
    if (bodySize > 0 && repetition.getBody().getStatements().get(bodySize - 1).getRuns().size() > 0) {
        final IConstruct lastBodyPart = repetition.getBody().getStatements().get(bodySize - 1);
        final int runNumber = lastBodyPart.getRuns().size();
        final XWPFRun lastRun = lastBodyPart.getRuns().get(runNumber - 1);
        final int closingRunNumber = repetition.getClosingRuns().size();
        if (closingRunNumber > 0 && repetition.getClosingRuns().get(0).getParent() != lastRun.getParent()) {
            forceNewParagraph = true;
        }
    }
}
 
Example 7
Source File: BookmarkManager.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Starts a bookmark in the given {@link XWPFParagraph} with the given name.
 * 
 * @param result
 *            the {@link GenerationResult}
 * @param paragraph
 *            the current {@link XWPFParagraph}
 * @param name
 *            the bookmark name
 */
public void startBookmark(GenerationResult result, XWPFParagraph paragraph, String name) {
    if (bookmarks.containsKey(name)) {
        result.addMessage(M2DocUtils.appendMessageRun(paragraph, ValidationMessageLevel.ERROR,
                "Can't start duplicated bookmark " + name));
    } else {
        final CTBookmark bookmark = paragraph.getCTP().addNewBookmarkStart();
        // we create a new run for future error messages.
        messagePositions.put(bookmark, paragraph.createRun());
        bookmark.setName(name);
        final BigInteger id = getRandomID();
        bookmark.setId(id);
        bookmarks.put(name, bookmark);
        xmlObjectToName.put(bookmark, name);
        startedBookmarks.put(name, bookmark);
        Set<CTText> pendingRefs = pendingReferences.remove(name);
        if (pendingRefs != null) {
            for (CTText pendingRef : pendingRefs) {
                xmlObjectToName.remove(pendingRef);
                // we remove the run created for error messages.
                final XWPFRun run = messagePositions.get(pendingRef);
                final IRunBody parent = run.getParent();
                if (parent instanceof XWPFParagraph) {
                    ((XWPFParagraph) parent).removeRun(((XWPFParagraph) parent).getRuns().indexOf(run));
                } else {
                    throw new IllegalStateException("this should not happend");
                }
                pendingRef.setStringValue(String.format(REF_TAG, bookmark.getName()));
            }
        }
    }
}
 
Example 8
Source File: M2DocUtils.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Inserts a new message {@link XWPFRun} after the given {@link XWPFRun}.
 * 
 * @param run
 *            the {@link XWPFRun} used as reference.
 * @param level
 *            the {@link ValidationMessageLevel}
 * @param message
 *            the message
 * @return the created {@link XWPFRun}
 */
public static TemplateValidationMessage insertMessageAfter(XWPFRun run, ValidationMessageLevel level,
        String message) {
    final IRunBody parent = run.getParent();
    if (parent instanceof XWPFParagraph) {
        final XWPFParagraph paragraph = (XWPFParagraph) parent;
        final XWPFRun newRun = paragraph.insertNewRun(paragraph.getRuns().indexOf(run));
        setRunMessage(newRun, level, message);
        return new TemplateValidationMessage(level, message, newRun);
    } else {
        throw new IllegalStateException("this should not happend");
    }
}
 
Example 9
Source File: BookmarkRenderPolicy.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
@Override
public void doRender(RenderContext<Object> context) throws Exception {
    Helper.renderTextRun(context.getRun(), context.getData());

    XWPFRun run = context.getRun();
    XWPFParagraphWrapper wapper = new XWPFParagraphWrapper((XWPFParagraph) run.getParent());
    CTBookmark bookmarkStart = wapper.insertNewBookmark(run);

    Object renderData = context.getData();
    TextRenderData data = renderData instanceof TextRenderData ? (TextRenderData) renderData
            : new TextRenderData(renderData.toString());

    String text = null == data.getText() ? "" : data.getText();
    bookmarkStart.setName(text);
}
 
Example 10
Source File: TextRenderPolicy.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
private static XWPFRun createHyperLinkRun(XWPFRun run, Object data) {
    XWPFParagraphWrapper paragraph = new XWPFParagraphWrapper((XWPFParagraph) run.getParent());
    XWPFRun hyperLinkRun = paragraph.insertNewHyperLinkRun(run, ((HyperLinkTextRenderData) data).getUrl());
    StyleUtils.styleRun(hyperLinkRun, run);
    run.setText("", 0);
    return hyperLinkRun;
}
 
Example 11
Source File: TOCRenderPolicy.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
@Override
public void render(ElementTemplate eleTemplate, Object data, XWPFTemplate template) {
    XWPFRun run = ((RunTemplate) eleTemplate).getRun();
    run.setText("", 0);

    XWPFParagraph tocPara = (XWPFParagraph) run.getParent();
    CTP ctP = tocPara.getCTP();

    CTSimpleField toc = ctP.addNewFldSimple();
    toc.setInstr("TOC \\o");
    toc.setDirty(STOnOff.TRUE);
}
 
Example 12
Source File: BodyContainer.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
default void clearPlaceholder(XWPFRun run) {
    IRunBody parent = run.getParent();
    run.setText("", 0);
    if (parent instanceof XWPFParagraph) {
        String paragraphText = ParagraphUtils.trimLine((XWPFParagraph) parent);
        if ("".equals(paragraphText)) {
            int pos = getPosOfParagraph((XWPFParagraph) parent);
            removeBodyElement(pos);
        }
    }
}
 
Example 13
Source File: IterableTemplate.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
public IterableTemplate buildIfInline() {
    XWPFRun startRun = startMark.getRun();
    XWPFRun endRun = endMark.getRun();

    if (startRun.getParent() == endRun.getParent()) {
        InlineIterableTemplate instance = new InlineIterableTemplate(startMark);
        instance.endMark = endMark;
        instance.templates = templates;
        return instance;
    }
    return this;
}
 
Example 14
Source File: JSONRenderPolicy.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
@Override
public void doRender(RenderContext<String> context) throws Exception {
    XWPFRun run = context.getRun();
    String data = context.getData();
    JsonNode jsonNode = objectMapper.readTree(data);
    List<TextRenderData> codes = convert(jsonNode, 1);

    XWPFParagraph paragraph = (XWPFParagraph) run.getParent();
    codes.forEach(code -> {
        XWPFRun span = paragraph.createRun();
        StyleUtils.styleRun(span, run);
        TextRenderPolicy.Helper.renderTextRun(span, code);
    });

}