org.apache.poi.xwpf.usermodel.XWPFRun Java Examples
The following examples show how to use
org.apache.poi.xwpf.usermodel.XWPFRun.
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: TocTest.java From poi-tl with Apache License 2.0 | 7 votes |
public static void main(String[] args) throws FileNotFoundException, IOException { XWPFDocument doc = new XWPFDocument(new FileInputStream("toc.docx")); XWPFStyles styles = doc.getStyles(); System.out.println(styles); XWPFParagraph p = doc.createParagraph(); XWPFRun run = p.createRun(); run.setText("Heading 1"); p.getCTP().addNewPPr(); p.getCTP().getPPr().addNewPStyle(); p.setStyle(HEADING1); XWPFParagraph tocPara = doc.createParagraph(); CTP ctP = tocPara.getCTP(); CTSimpleField toc = ctP.addNewFldSimple(); toc.setInstr("TOC \\h"); toc.setDirty(STOnOff.TRUE); System.out.println(doc.isEnforcedUpdateFields()); // doc.enforceUpdateFields(); // doc.createTOC(); doc.write(new FileOutputStream("CreateWordBookmark.docx")); doc.close(); }
Example #2
Source File: M2DocParser.java From M2Doc with Eclipse Public License 1.0 | 6 votes |
/** * Parse a bookmark construct. Bookmark are of the form * <code>{m:bookmark 'bookmark name'} runs {m:endbookmark}</code> * * @return the created object * @throws DocumentParserException * if something wrong happens during parsing. */ private Bookmark parseBookmark() throws DocumentParserException { // first read the tag that opens the bookmark final Bookmark bookmark = (Bookmark) EcoreUtil.create(TemplatePackage.Literals.BOOKMARK); String tagText = readTag(bookmark, bookmark.getRuns()).trim(); // remove the prefix tagText = tagText.substring(TokenType.BOOKMARK.getValue().length()).trim(); final AstResult result = queryParser.build(tagText); bookmark.setName(result); if (!result.getErrors().isEmpty()) { final XWPFRun lastRun = bookmark.getRuns().get(bookmark.getRuns().size() - 1); bookmark.getValidationMessages().addAll(getValidationMessage(result.getDiagnostic(), tagText, lastRun)); } // read up the tags until the "m:endbookmark" tag is encountered. final Block body = parseBlock(null, TokenType.ENDBOOKMARK); bookmark.setBody(body); if (getNextTokenType() != TokenType.EOF) { readTag(bookmark, bookmark.getClosingRuns()); } return bookmark; }
Example #3
Source File: M2DocValidator.java From M2Doc with Eclipse Public License 1.0 | 6 votes |
/** * Validates the {@link Repetition#getQuery() query}. * * @param repetition * the {@link Repetition} * @param run * the {@link XWPFRun} * @param types * the {@link Set} of {@link IType} for the {@link Repetition#getQuery() query} * @return the {@link ValidationMessageLevel} */ private ValidationMessageLevel validateRepetitionQueryType(Repetition repetition, final XWPFRun run, final Set<IType> types) { ValidationMessageLevel res = ValidationMessageLevel.OK; for (IType type : types) { if (!(type instanceof ICollectionType)) { res = ValidationMessageLevel.ERROR; repetition.getValidationMessages().add(new TemplateValidationMessage(res, String.format("The iteration variable types must be collections (%s).", types), run)); break; } } return res; }
Example #4
Source File: StyleUtils.java From poi-tl with Apache License 2.0 | 6 votes |
/** * 重复样式 * * @param destRun * 新建的run * @param srcRun * 原始run */ public static void styleRun(XWPFRun destRun, XWPFRun srcRun) { if (null == destRun || null == srcRun) return; CTR ctr = srcRun.getCTR(); if (ctr.isSetRPr() && ctr.getRPr().isSetRStyle()) { String val = ctr.getRPr().getRStyle().getVal(); if (StringUtils.isNotBlank(val)) { CTRPr pr = destRun.getCTR().isSetRPr() ? destRun.getCTR().getRPr() : destRun.getCTR().addNewRPr(); CTString rStyle = pr.isSetRStyle() ? pr.getRStyle() : pr.addNewRStyle(); rStyle.setVal(val); } } if (Boolean.TRUE.equals(srcRun.isBold())) destRun.setBold(srcRun.isBold()); destRun.setColor(srcRun.getColor()); // destRun.setCharacterSpacing(srcRun.getCharacterSpacing()); if (StringUtils.isNotBlank(srcRun.getFontFamily())) destRun.setFontFamily(srcRun.getFontFamily()); int fontSize = srcRun.getFontSize(); if (-1 != fontSize) destRun.setFontSize(fontSize); if (Boolean.TRUE.equals(srcRun.isItalic())) destRun.setItalic(srcRun.isItalic()); if (Boolean.TRUE.equals(srcRun.isStrikeThrough())) destRun.setStrikeThrough(srcRun.isStrikeThrough()); destRun.setUnderline(srcRun.getUnderline()); }
Example #5
Source File: BookMark.java From frpMgr with MIT License | 6 votes |
/** * Inserts some text into a Word document immediately in front of the * location of a bookmark. * * This case is slightly more straightforward than inserting after the * bookmark. For example, it is possible only to insert a new node in front * of an existing node. When inserting after the bookmark, then end node had * to be located whereas, in this case, the node is already known, it is the * CTBookmark itself. The only information that must be discovered is * whether there is a run immediately in front of the boookmarkStart tag and * whether that run is styled. If there is and if it is, then this style * must be cloned and applied the text which will be inserted into the * paragraph. * * @param run An instance of the XWPFRun class that encapsulates the text * that is to be inserted into the document following the bookmark. */ private void insertBeforeBookmark(XWPFRun run) { Node insertBeforeNode = null; Node childNode = null; Node styleNode = null; // Get the dom node from the bookmarkStart tag and look for another // node immediately preceding it. insertBeforeNode = this._ctBookmark.getDomNode(); childNode = insertBeforeNode.getPreviousSibling(); // If a node is found, try to get the styling from it. if (childNode != null) { styleNode = this.getStyleNode(childNode); // If that previous node was styled, then apply this style to the // text which will be inserted. if (styleNode != null) { run.getCTR().getDomNode().insertBefore(styleNode.cloneNode(true), run.getCTR().getDomNode().getFirstChild()); } } // Insert the text into the paragraph immediately in front of the // bookmarkStart tag. this._para.getCTP().getDomNode().insertBefore(run.getCTR().getDomNode(), insertBeforeNode); }
Example #6
Source File: MiniTableRenderPolicy.java From poi-tl with Apache License 2.0 | 6 votes |
public static void renderTable(XWPFRun run, MiniTableRenderData tableData) { // 1.计算行和列 int row = tableData.getRows().size(), col = 0; if (!tableData.isSetHeader()) { col = getMaxColumFromData(tableData.getRows()); } else { row++; col = tableData.getHeader().size(); } // 2.创建表格 BodyContainer bodyContainer = BodyContainerFactory.getBodyContainer(run); XWPFTable table = bodyContainer.insertNewTable(run, row, col); TableTools.initBasicTable(table, col, tableData.getWidth(), tableData.getStyle()); // 3.渲染数据 int startRow = 0; if (tableData.isSetHeader()) Helper.renderRow(table, startRow++, tableData.getHeader()); for (RowRenderData data : tableData.getRows()) { Helper.renderRow(table, startRow++, data); } }
Example #7
Source File: BookmarkManager.java From M2Doc with Eclipse Public License 1.0 | 6 votes |
/** * Marks dangling references. * * @param result * the {@link GenerationResult} * @return <code>true</code> if any dangling reference was found, <code>false</code> otherwise */ public boolean markDanglingReferences(GenerationResult result) { final boolean res = !pendingReferences.isEmpty(); if (res) { for (Entry<String, Set<CTText>> entry : pendingReferences.entrySet()) { for (CTText ref : entry.getValue()) { final XWPFRun refRun = messagePositions.remove(ref); result.addMessage(M2DocUtils.insertMessageAfter(refRun, ValidationMessageLevel.ERROR, "dangling reference for bookmark " + entry.getKey())); } } } return res; }
Example #8
Source File: DynamicTableRenderPolicy.java From poi-tl with Apache License 2.0 | 6 votes |
@Override public void render(ElementTemplate eleTemplate, Object data, XWPFTemplate template) { RunTemplate runTemplate = (RunTemplate) eleTemplate; XWPFRun run = runTemplate.getRun(); run.setText("", 0); try { if (!TableTools.isInsideTable(run)) { throw new IllegalStateException( "The template tag " + runTemplate.getSource() + " must be inside a table"); } XWPFTableCell cell = (XWPFTableCell) ((XWPFParagraph) run.getParent()).getBody(); XWPFTable table = cell.getTableRow().getTable(); render(table, data); } catch (Exception e) { throw new RenderException("dynamic table error:" + e.getMessage(), e); } }
Example #9
Source File: M2DocUtils.java From M2Doc with Eclipse Public License 1.0 | 6 votes |
/** * Gets or create the first {@link XWPFRun} of the given {@link XWPFDocument}. * * @param document * the {@link XWPFDocument} * @return the first {@link XWPFRun} of the given {@link XWPFDocument} or the created one if none existed */ public static XWPFRun getOrCreateFirstRun(XWPFDocument document) { final XWPFRun res; final XWPFParagraph paragraph; if (!document.getParagraphs().isEmpty()) { paragraph = document.getParagraphs().get(0); } else { paragraph = document.createParagraph(); } if (!paragraph.getRuns().isEmpty()) { res = paragraph.getRuns().get(0); } else { res = paragraph.createRun(); } return res; }
Example #10
Source File: RunIteratorTests.java From M2Doc with Eclipse Public License 1.0 | 6 votes |
@Test public void testNonEmptyDoc() throws InvalidFormatException, IOException { try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx"); OPCPackage oPackage = OPCPackage.open(is); XWPFDocument document = new XWPFDocument(oPackage);) { TokenIterator iterator = new TokenIterator(document); XWPFRun run = iterator.next().getRun(); assertEquals("P1Run1 ", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals("P1Run2", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals(" P1Run3", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals("P2Run1 ", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals("P2Run2", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals(" ", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals("P2Run3", run.getText(run.getTextPosition())); run = iterator.next().getRun(); assertEquals("", run.getText(run.getTextPosition())); assertTrue(!iterator.hasNext()); } }
Example #11
Source File: M2DocEvaluator.java From M2Doc with Eclipse Public License 1.0 | 6 votes |
/** * Inserts the given {@link MText}. * * @param paragraph * the {@link XWPFParagraph} to modify * @param run * the {@link XWPFRun} * @param text * the {@link MText} * @return the last inserted XWPFRun */ private XWPFRun insertMText(XWPFParagraph paragraph, XWPFRun run, MText text) { final XWPFRun res; if (text.getText() != null) { final XWPFRun textRun = insertFieldRunReplacement(paragraph, run, text.getText()); if (text.getStyle() != null) { applyMStyle(textRun, text.getStyle()); } res = textRun; } else { res = run; } return res; }
Example #12
Source File: TextRenderPolicy.java From poi-tl with Apache License 2.0 | 6 votes |
public static void renderTextRun(XWPFRun run, Object data) { XWPFRun textRun = run; if (data instanceof HyperLinkTextRenderData) { textRun = createHyperLinkRun(run, data); } TextRenderData wrapperData = wrapper(data); String text = null == wrapperData.getText() ? "" : wrapperData.getText(); StyleUtils.styleRun(textRun, wrapperData.getStyle()); String[] split = text.split(REGEX_LINE_CHARACTOR, -1); if (split.length > 0) { textRun.setText(split[0], 0); boolean lineAtTable = split.length > 1 && !(data instanceof HyperLinkTextRenderData) && TableTools.isInsideTable(run); for (int i = 1; i < split.length; i++) { if (lineAtTable) { textRun.addBreak(BreakType.TEXT_WRAPPING); } else { textRun.addCarriageReturn(); } textRun.setText(split[i]); } } }
Example #13
Source File: CommentImpl.java From M2Doc with Eclipse Public License 1.0 | 6 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case TemplatePackage.COMMENT__STYLE_RUN: setStyleRun((XWPFRun) newValue); return; case TemplatePackage.COMMENT__RUNS: getRuns().clear(); getRuns().addAll((Collection<? extends XWPFRun>) newValue); return; case TemplatePackage.COMMENT__CLOSING_RUNS: getClosingRuns().clear(); getClosingRuns().addAll((Collection<? extends XWPFRun>) newValue); return; case TemplatePackage.COMMENT__VALIDATION_MESSAGES: getValidationMessages().clear(); getValidationMessages().addAll((Collection<? extends TemplateValidationMessage>) newValue); return; case TemplatePackage.COMMENT__TEXT: setText((String) newValue); return; } super.eSet(featureID, newValue); }
Example #14
Source File: UserContentImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<XWPFRun> getClosingRuns() { if (closingRuns == null) { closingRuns = new EDataTypeUniqueEList<XWPFRun>(XWPFRun.class, this, TemplatePackage.USER_CONTENT__CLOSING_RUNS); } return closingRuns; }
Example #15
Source File: UserContentImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<XWPFRun> getRuns() { if (runs == null) { runs = new EDataTypeUniqueEList<XWPFRun>(XWPFRun.class, this, TemplatePackage.USER_CONTENT__RUNS); } return runs; }
Example #16
Source File: LetImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<XWPFRun> getRuns() { if (runs == null) { runs = new EDataTypeUniqueEList<XWPFRun>(XWPFRun.class, this, TemplatePackage.LET__RUNS); } return runs; }
Example #17
Source File: TemplateImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case TemplatePackage.TEMPLATE__STYLE_RUN: setStyleRun((XWPFRun) newValue); return; case TemplatePackage.TEMPLATE__RUNS: getRuns().clear(); getRuns().addAll((Collection<? extends XWPFRun>) newValue); return; case TemplatePackage.TEMPLATE__CLOSING_RUNS: getClosingRuns().clear(); getClosingRuns().addAll((Collection<? extends XWPFRun>) newValue); return; case TemplatePackage.TEMPLATE__VALIDATION_MESSAGES: getValidationMessages().clear(); getValidationMessages().addAll((Collection<? extends TemplateValidationMessage>) newValue); return; case TemplatePackage.TEMPLATE__NAME: setName((String) newValue); return; case TemplatePackage.TEMPLATE__PARAMETERS: getParameters().clear(); getParameters().addAll((Collection<? extends Parameter>) newValue); return; case TemplatePackage.TEMPLATE__BODY: setBody((Block) newValue); return; case TemplatePackage.TEMPLATE__DOCUMENT_TEMPLATE: setDocumentTemplate((DocumentTemplate) newValue); return; } super.eSet(featureID, newValue); }
Example #18
Source File: TableImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<XWPFRun> getRuns() { if (runs == null) { runs = new EDataTypeUniqueEList<XWPFRun>(XWPFRun.class, this, TemplatePackage.TABLE__RUNS); } return runs; }
Example #19
Source File: M2DocEvaluator.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * Apply the given style to the given run. Background color is not taken into account here since it does not apply to runs. * * @param run * The run to style * @param style * The style to apply, can be <code>null</code> */ private void applyMStyle(XWPFRun run, MStyle style) { if (style.getFontSize() != -1) { run.setFontSize(style.getFontSize()); } if (style.getFontName() != null) { run.setFontFamily(style.getFontName()); } if (style.getFontModifiers() != -1) { run.setBold((style.getFontModifiers() & MStyle.FONT_BOLD) != 0); run.setItalic((style.getFontModifiers() & MStyle.FONT_ITALIC) != 0); if ((style.getFontModifiers() & MStyle.FONT_UNDERLINE) != 0) { run.setUnderline(UnderlinePatterns.SINGLE); } run.setStrikeThrough((style.getFontModifiers() & MStyle.FONT_STRIKE_THROUGH) != 0); } if (style.getForegroundColor() != null) { run.setColor(hexColor(style.getForegroundColor())); } if (style.getBackgroundColor() != null) { final CTRPr ctrpr; if (run.getCTR().getRPr() != null) { ctrpr = run.getCTR().getRPr(); } else { ctrpr = run.getCTR().addNewRPr(); } final CTShd ctshd; if (ctrpr.getShd() != null) { ctshd = ctrpr.getShd(); } else { ctshd = ctrpr.addNewShd(); } ctshd.setVal(STShd.CLEAR); ctshd.setColor("auto"); ctshd.setFill(hexColor(style.getBackgroundColor())); } }
Example #20
Source File: CommentImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public void setStyleRun(XWPFRun newStyleRun) { XWPFRun oldStyleRun = styleRun; styleRun = newStyleRun; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TemplatePackage.COMMENT__STYLE_RUN, oldStyleRun, styleRun)); }
Example #21
Source File: QueryImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<XWPFRun> getRuns() { if (runs == null) { runs = new EDataTypeUniqueEList<XWPFRun>(XWPFRun.class, this, TemplatePackage.QUERY__RUNS); } return runs; }
Example #22
Source File: BlockImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<XWPFRun> getClosingRuns() { if (closingRuns == null) { closingRuns = new EDataTypeUniqueEList<XWPFRun>(XWPFRun.class, this, TemplatePackage.BLOCK__CLOSING_RUNS); } return closingRuns; }
Example #23
Source File: BlockImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<XWPFRun> getRuns() { if (runs == null) { runs = new EDataTypeUniqueEList<XWPFRun>(XWPFRun.class, this, TemplatePackage.BLOCK__RUNS); } return runs; }
Example #24
Source File: BlockImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public void setStyleRun(XWPFRun newStyleRun) { XWPFRun oldStyleRun = styleRun; styleRun = newStyleRun; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TemplatePackage.BLOCK__STYLE_RUN, oldStyleRun, styleRun)); }
Example #25
Source File: StaticFragmentImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<XWPFRun> getClosingRuns() { if (closingRuns == null) { closingRuns = new EDataTypeUniqueEList<XWPFRun>(XWPFRun.class, this, TemplatePackage.STATIC_FRAGMENT__CLOSING_RUNS); } return closingRuns; }
Example #26
Source File: TemplateResolver.java From poi-tl with Apache License 2.0 | 5 votes |
@Override public List<MetaTemplate> resolveBodyElements(List<IBodyElement> bodyElements) { List<MetaTemplate> metaTemplates = new ArrayList<>(); if (null == bodyElements) return metaTemplates; // current iterable templates state Deque<BlockTemplate> stack = new LinkedList<BlockTemplate>(); for (IBodyElement element : bodyElements) { if (element == null) continue; if (element.getElementType() == BodyElementType.PARAGRAPH) { XWPFParagraph paragraph = (XWPFParagraph) element; RunningRunParagraph runningRun = new RunningRunParagraph(paragraph, templatePattern); List<XWPFRun> refactorRuns = runningRun.refactorRun(); if (null == refactorRuns) continue; Collections.reverse(refactorRuns); resolveXWPFRuns(refactorRuns, metaTemplates, stack); } else if (element.getElementType() == BodyElementType.TABLE) { XWPFTable table = (XWPFTable) element; List<XWPFTableRow> rows = table.getRows(); if (null == rows) continue; for (XWPFTableRow row : rows) { List<XWPFTableCell> cells = row.getTableCells(); if (null == cells) continue; cells.forEach(cell -> { List<MetaTemplate> visitBodyElements = resolveBodyElements(cell.getBodyElements()); if (stack.isEmpty()) { metaTemplates.addAll(visitBodyElements); } else { stack.peek().getTemplates().addAll(visitBodyElements); } }); } } } checkStack(stack); return metaTemplates; }
Example #27
Source File: RepetitionImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<XWPFRun> getClosingRuns() { if (closingRuns == null) { closingRuns = new EDataTypeUniqueEList<XWPFRun>(XWPFRun.class, this, TemplatePackage.REPETITION__CLOSING_RUNS); } return closingRuns; }
Example #28
Source File: RepetitionImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<XWPFRun> getRuns() { if (runs == null) { runs = new EDataTypeUniqueEList<XWPFRun>(XWPFRun.class, this, TemplatePackage.REPETITION__RUNS); } return runs; }
Example #29
Source File: FieldUtils.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * Returns <code>true</code> when the specified run is a field end run and <code>false</code> otherwise. * * @param run * the concerned run * @return <code>true</code> for field end. */ public boolean isFieldEnd(XWPFRun run) { if (run.getCTR().getFldCharList().size() > 0) { CTFldChar fldChar = run.getCTR().getFldCharList().get(0); return STFldCharType.END.equals(fldChar.getFldCharType()); } else { return false; } }
Example #30
Source File: QueryImpl.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public EList<XWPFRun> getClosingRuns() { if (closingRuns == null) { closingRuns = new EDataTypeUniqueEList<XWPFRun>(XWPFRun.class, this, TemplatePackage.QUERY__CLOSING_RUNS); } return closingRuns; }