org.apache.poi.xwpf.usermodel.XWPFParagraph Java Examples

The following examples show how to use org.apache.poi.xwpf.usermodel.XWPFParagraph. 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 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 #2
Source File: RawCopier.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Updates bookmarks for the given output {@link XWPFTable} according to its input {@link XWPFTable}.
 * 
 * @param bookmarkManager
 *            the {@link BookmarkManager}
 * @param outputTable
 *            the output {@link XWPFTable}
 * @param inputTable
 *            the input {@link XWPFTable}
 */
private void updateBookmarks(BookmarkManager bookmarkManager, final XWPFTable outputTable,
        final XWPFTable inputTable) {
    final List<XWPFTableRow> inputRows = inputTable.getRows();
    final List<XWPFTableRow> outputRows = outputTable.getRows();
    for (int rowIndex = 0; rowIndex < inputRows.size(); rowIndex++) {
        final XWPFTableRow inputRow = inputRows.get(rowIndex);
        final XWPFTableRow outputRow = outputRows.get(rowIndex);
        final List<XWPFTableCell> inputCells = inputRow.getTableCells();
        final List<XWPFTableCell> outputCells = outputRow.getTableCells();
        for (int cellIndex = 0; cellIndex < inputCells.size(); cellIndex++) {
            final XWPFTableCell inputCell = inputCells.get(cellIndex);
            final XWPFTableCell outputCell = outputCells.get(cellIndex);
            final List<IBodyElement> inputBodyElements = inputCell.getBodyElements();
            final List<IBodyElement> outputBodyElements = outputCell.getBodyElements();
            for (int bodyElementIndex = 0; bodyElementIndex < inputBodyElements.size(); bodyElementIndex++) {
                final IBodyElement inputBodyElement = inputBodyElements.get(bodyElementIndex);
                if (inputBodyElement instanceof XWPFParagraph) {
                    final IBodyElement outputBodyElement = outputBodyElements.get(bodyElementIndex);
                    updateBookmarks(bookmarkManager, ((XWPFParagraph) outputBodyElement).getCTP(),
                            ((XWPFParagraph) inputBodyElement).getCTP());
                }
            }
        }
    }
}
 
Example #3
Source File: M2DocUtils.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 #4
Source File: IfTemplateRenderTest.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
private void testParagraph(IBody document) {
    XWPFParagraph paragraph = document.getParagraphArray(0);
    assertEquals(paragraph.getText(), "Hi, poi-tl");

    paragraph = document.getParagraphArray(1);
    assertEquals(paragraph.getText(), "Hello, My perfect.");

    paragraph = document.getParagraphArray(2);
    assertEquals(paragraph.getText(), "UserName: Sayi");

    paragraph = document.getParagraphArray(3);
    assertEquals(paragraph.getText(), "Date: 2020-02-10");

    paragraph = document.getParagraphArray(4);
    assertEquals(paragraph.getText(), "Date: 2020-02-10");

    paragraph = document.getParagraphArray(5);
    assertEquals(paragraph.getText(), "I love this Game Date: 2020-02-10 and good game.");
}
 
Example #5
Source File: IndexRefRenderPolicy.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected T locate(XWPFTemplate template) {
    int positon = index();
    logger.info("Try locate the {} object at position of {}...",
            ClassUtils.getSimpleName(genericType), positon);
    Object t = null;
    NiceXWPFDocument doc = template.getXWPFDocument();
    if (XWPFChart.class.equals(genericType)) {
        t = doc.getCharts().get(positon);
    } else if (XWPFTable.class.equals(genericType)) {
        t = doc.getTables().get(positon);
    } else if (XWPFPictureData.class.equals(genericType)) {
        t = doc.getAllPictures().get(positon);
    } else if (XWPFPicture.class.equals(genericType)) {
        t = doc.getAllEmbeddedPictures().get(positon);
    } else if (XWPFParagraph.class.equals(genericType)) {
        t = doc.getParagraphs().get(positon);
    }
    return (T) t;
}
 
Example #6
Source File: ParseWord07.java    From easypoi with Apache License 2.0 6 votes vote down vote up
/**
 * 根据条件改变值
 * 
 * @param map
 * @Author JueYue
 * @date 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 WordImageEntity) {// 如果是图片就设置为图片
        currentRun.setText("", 0);
        addAnImage((WordImageEntity) obj, currentRun);
    } else {
        currentText = obj.toString();
        currentRun.setText(currentText, 0);
    }
    for (int k = 0; k < runIndex.size(); k++) {
        paragraph.getRuns().get(runIndex.get(k)).setText("", 0);
    }
    runIndex.clear();
}
 
Example #7
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 #8
Source File: PDF2WordExample.java    From tutorials with MIT License 6 votes vote down vote up
private static void generateDocFromPDF(String filename) throws IOException {
	XWPFDocument doc = new XWPFDocument();

	String pdf = filename;
	PdfReader reader = new PdfReader(pdf);
	PdfReaderContentParser parser = new PdfReaderContentParser(reader);

	for (int i = 1; i <= reader.getNumberOfPages(); i++) {
		TextExtractionStrategy strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
		String text = strategy.getResultantText();
		XWPFParagraph p = doc.createParagraph();
		XWPFRun run = p.createRun();
		run.setText(text);
		run.addBreak(BreakType.PAGE);
	}
	FileOutputStream out = new FileOutputStream("src/output/pdf.docx");
	doc.write(out);
	out.close();
	reader.close();
	doc.close();
}
 
Example #9
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public XWPFParagraph caseLink(Link link) {
    XWPFParagraph currentParagraph = currentGeneratedParagraph;
    if (hasError(link)) {
        currentParagraph = insertQuerySyntaxMessages(currentParagraph, link, INVALID_LINK_STATEMENT);
    } else {
        final EvaluationResult nameResult = evaluator.eval(link.getName(), variablesStack.peek());
        if (nameResult.getDiagnostic().getSeverity() != Diagnostic.OK) {
            currentParagraph = insertQueryEvaluationMessages(currentParagraph, link, nameResult.getDiagnostic());
        } else {
            final EvaluationResult textResult = evaluator.eval(link.getText(), variablesStack.peek());
            if (nameResult.getDiagnostic().getSeverity() != Diagnostic.OK) {
                currentParagraph = insertQueryEvaluationMessages(currentParagraph, link,
                        textResult.getDiagnostic());
            } else {
                bookmarkManager.insertReference(currentParagraph, nameResult.getResult().toString(),
                        textResult.getResult().toString());
            }
        }
    }

    return currentParagraph;
}
 
Example #10
Source File: InlineIterableProcessor.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleIterable(IterableTemplate iterableTemplate, BodyContainer bodyContainer, Iterable<?> compute) {
    RunTemplate start = iterableTemplate.getStartMark();
    RunTemplate end = iterableTemplate.getEndMark();
    ParagraphContext parentContext = new XWPFParagraphContext(
            new XWPFParagraphWrapper((XWPFParagraph) start.getRun().getParent()));

    Integer startRunPos = start.getRunPos();
    Integer endRunPos = end.getRunPos();
    IterableContext context = new IterableContext(startRunPos, endRunPos);

    Iterator<?> iterator = compute.iterator();
    while (iterator.hasNext()) {
        next(iterableTemplate, parentContext, context, iterator.next());
    }

    // clear self iterable template
    for (int i = endRunPos - 1; i > startRunPos; i--) {
        parentContext.removeRun(i);
    }
}
 
Example #11
Source File: M2DocTestUtils.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new {@link DocumentTemplate} with the given {@link DocumentTemplate#getBody() body}. The body is linked to {@link XWPFRun}.
 * 
 * @param body
 *            the {@link Block}
 * @return a new {@link DocumentTemplate}
 */
@SuppressWarnings("resource")
public static DocumentTemplate createDocumentTemplate(Block body) {
    final DocumentTemplate res = TemplatePackage.eINSTANCE.getTemplateFactory().createDocumentTemplate();
    final Resource r = new XMIResourceImpl();
    r.getContents().add(res);

    final XWPFDocument document = new XWPFDocument();
    res.setDocument(document);
    res.setBody(body);

    final XWPFParagraph paragraph = document.createParagraph();

    linkRuns(paragraph, body);

    return res;
}
 
Example #12
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 #13
Source File: Issue149.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewMergeNew3() throws Exception {
    source = new NiceXWPFDocument();

    target = new NiceXWPFDocument();
    XWPFParagraph createParagraph = target.createParagraph();
    createParagraph.createRun();

    result = source.merge(target);

    assertEquals(result.getParagraphs().size(), 1);
    assertEquals(result.getParagraphArray(0).getText(), "");

    source.close();
    target.close();
    result.close();

}
 
Example #14
Source File: DynamicTableRenderPolicy.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
@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 #15
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public XWPFParagraph caseUserDoc(UserDoc userDoc) {
    XWPFParagraph currentParagraph = currentGeneratedParagraph;
    if (hasError(userDoc)) {
        currentParagraph = insertQuerySyntaxMessages(currentParagraph, userDoc, INVALID_USERDOC_STATEMENT);
    } else {
        final EvaluationResult queryResult = evaluator.eval(userDoc.getId(), variablesStack.peek());
        if (queryResult.getDiagnostic().getSeverity() != Diagnostic.OK) {
            currentParagraph = insertQueryEvaluationMessages(currentParagraph, userDoc,
                    queryResult.getDiagnostic());
        } else {
            if (queryResult.getResult() == null) {
                insertMessage(currentParagraph, ValidationMessageLevel.ERROR, "User doc id can't be null.");
            } else {
                final String id = queryResult.getResult().toString();
                currentParagraph = insertUserContent(currentParagraph, userDoc, id);
            }
        }
    }

    return currentParagraph;
}
 
Example #16
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public XWPFParagraph caseQuery(Query query) {
    XWPFParagraph currentParagraph = currentGeneratedParagraph;
    if (hasError(query)) {
        currentParagraph = insertQuerySyntaxMessages(currentParagraph, query, INVALID_QUERY_STATEMENT);
    } else {
        final EvaluationResult queryResult = evaluator.eval(query.getQuery(), variablesStack.peek());
        if (queryResult.getDiagnostic().getSeverity() != Diagnostic.OK) {
            currentParagraph = insertQueryEvaluationMessages(currentParagraph, query, queryResult.getDiagnostic());
        } else {
            final Object value = queryResult.getResult();
            final XWPFRun styleRun = query.getStyleRun();
            currentParagraph = insertObject(currentParagraph, value, styleRun);
        }
    }

    return currentParagraph;
}
 
Example #17
Source File: CellBodyContainnerTest.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void init() {
    XWPFTable xwpfTable = document.createTable();
    XWPFTableRow createRow = xwpfTable.createRow();
    cell = createRow.createCell();
    container = new CellBodyContainer(cell);

    // cell.addParagraph()有bug,不会更新bodyElements

    // p-t-p-t-p-t
    XWPFParagraph insertpos = cell.getParagraphArray(0);
    container.insertNewParagraph(insertpos.getCTP().newCursor());
    container.insertNewTable(insertpos.createRun(), 2, 2);
    paragraph = container.insertNewParagraph(insertpos.getCTP().newCursor());
    table = container.insertNewTable(insertpos.createRun(), 2, 2);
    container.insertNewParagraph(insertpos.getCTP().newCursor());
    container.insertNewTable(insertpos.createRun(), 2, 2);

    container.removeBodyElement(6);

}
 
Example #18
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Add End UserContent word Document Field.
 * 
 * @param paragraph
 *            the {@link XWPFParagraph} to modify
 * @param userDoc
 *            the {@link UserDoc} where add field
 * @param needNewParagraph
 *            need New Paragraph boolean
 * @return the current {@link XWPFParagraph}
 */
private XWPFParagraph addEndUserContentField(XWPFParagraph paragraph, UserDoc userDoc, boolean needNewParagraph) {
    final XWPFParagraph res;

    if (needNewParagraph) {
        final XWPFParagraph newParagraph = createNewParagraph(generatedDocument, paragraph);
        insertTag(newParagraph, TokenType.ENDUSERCONTENT.getValue());
        res = newParagraph;
    } else {
        insertTag(paragraph, TokenType.ENDUSERCONTENT.getValue());
        res = paragraph;
    }

    return res;
}
 
Example #19
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public XWPFParagraph caseCell(Cell cell) {
    final XWPFTableCell newCell = new XWPFTableCell(currentGeneratedRow.getCtRow().addNewTc(), currentGeneratedRow,
            generatedDocument);
    final CTTc ctCell = (CTTc) cell.getTableCell().getCTTc().copy();
    ctCell.getPList().clear();
    ctCell.getTblList().clear();
    ctCell.getSdtList().clear();
    newCell.getCTTc().set(ctCell);

    final IBody savedGeneratedDocument = generatedDocument;
    final XWPFParagraph savedGeneratedParagraph = currentGeneratedParagraph;
    final XWPFParagraph savedTemplateParagraph = currentTemplateParagraph;
    generatedDocument = newCell;
    try {
        doSwitch(cell.getBody());
    } finally {
        generatedDocument = savedGeneratedDocument;
        currentGeneratedParagraph = savedGeneratedParagraph;
        currentTemplateParagraph = savedTemplateParagraph;
    }

    // prevent cell with no paragraph
    if (newCell.getParagraphs().size() == 1) {
        final XWPFParagraph firstParagraph = newCell.getParagraphs().get(0);
        if (firstParagraph.getRuns().isEmpty()) {
            ctCell.addNewP();
            newCell.getCTTc().set(ctCell);
        }
    }

    return currentGeneratedParagraph;
}
 
Example #20
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Inserts the {@link UserContent}.
 * 
 * @param paragraph
 *            the {@link XWPFParagraph} to modify
 * @param userDoc
 *            the source {@link UserDoc}
 * @param id
 *            the ID
 * @return the current {@link XWPFParagraph}
 */
private XWPFParagraph insertUserContent(XWPFParagraph paragraph, UserDoc userDoc, final String id) {
    XWPFParagraph currentParagraph = paragraph;
    // Tag UserContent with evaluated id
    currentParagraph = addStartUserDocField(currentParagraph, userDoc, id);
    // manage user Doc Id Uniqueness
    manageUserDocIdUniqueness(currentParagraph, id, userDoc);
    // Copy userdoc content
    UserContent userContent = userContentManager.consumeUserContent(id);
    boolean needNewParagraphBeforeEndTag = true;
    if (userContent == null) {
        currentParagraph = doSwitch(userDoc.getBody());
    } else {
        try {
            currentParagraph = copier.copyUserContent(userContent, currentParagraph);
            needNewParagraphBeforeEndTag = copier.needNewParagraph();
            // CHECKSTYLE:OFF
        } catch (Exception e) {
            // CHECKSTYLE:ON
            insertMessage(currentParagraph, ValidationMessageLevel.ERROR,
                    UserContentManager.USERDOC_COPY_ERROR + e.getMessage());
        }
    }

    if (currentParagraph == null) {
        currentParagraph = createNewParagraph(generatedDocument,
                (XWPFParagraph) userDoc.getRuns().get(0).getParent());
        needNewParagraphBeforeEndTag = false;
    }

    if (!currentParagraph.getCTP().xmlText()
            .contains("<w:instrText>" + TokenType.ENDUSERCONTENT.getValue() + "</w:instrText>")) {
        // Tag m:enduserContent
        currentParagraph = addEndUserContentField(currentParagraph, userDoc, needNewParagraphBeforeEndTag);
    }

    return currentParagraph;
}
 
Example #21
Source File: XWPFParagraphWrapper.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private List<XWPFRun> getRuns() {
    try {
        Field runsField = XWPFParagraph.class.getDeclaredField("runs");
        runsField.setAccessible(true);
        return (List<XWPFRun>) runsField.get(paragraph);
    } catch (Exception e) {
        throw new ReflectionException("runs", XWPFParagraph.class, e);
    }
}
 
Example #22
Source File: TocTest.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
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 #23
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public XWPFParagraph doSwitch(EObject eObject) {
    if (!monitor.isCanceled()) {
        return super.doSwitch(eObject);
    }
    return null;

}
 
Example #24
Source File: ETLWordDocumentGenerator.java    From WhiteRabbit with Apache License 2.0 5 votes vote down vote up
private static void addSourceTablesAppendix(CustomXWPFDocument document, ETL etl) {
	XWPFParagraph paragraph = document.createParagraph();
	XWPFRun run = paragraph.createRun();
	run.addBreak(BreakType.PAGE);
	run.setText("Appendix: source tables");
	run.setFontSize(18);
	
	for (Table sourceTable : etl.getSourceDatabase().getTables()) {
		paragraph = document.createParagraph();
		run = paragraph.createRun();
		run.setText("Table: " + sourceTable.getName());
		run.setFontSize(14);
		
		createDocumentParagraph(document, sourceTable.getComment());
		
		XWPFTable table = document.createTable(sourceTable.getFields().size() + 1, 4);
		// table.setWidth(2000);
		XWPFTableRow header = table.getRow(0);
		setTextAndHeaderShading(header.getCell(0), "Field");
		setTextAndHeaderShading(header.getCell(1), "Type");
		setTextAndHeaderShading(header.getCell(2), "Most freq. value");
		setTextAndHeaderShading(header.getCell(3), "Comment");
		int rowNr = 1;
		for (Field sourceField : sourceTable.getFields()) {
			XWPFTableRow row = table.getRow(rowNr++);
			row.getCell(0).setText(sourceField.getName());
			row.getCell(1).setText(sourceField.getType());
			row.getCell(2).setText(sourceField.getValueCounts().getMostFrequentValue());
			createCellParagraph(row.getCell(3), sourceField.getComment().trim());
		}
		
	}
	
	run.setFontSize(18);
}
 
Example #25
Source File: M2DocEvaluator.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create a new run in the cell's paragraph and set this run's text, and apply the given style to the cell and its paragraph.
 * 
 * @param cell
 *            Cell to fill in
 * @param mCell
 *            the cell to read data from
 */
private void setCellContent(XWPFTableCell cell, MCell mCell) {
    XWPFParagraph cellParagraph = cell.getParagraphs().get(0);
    XWPFRun cellRun = cellParagraph.createRun();
    if (mCell != null) {
        final MElement contents = mCell.getContents();
        if (mCell.getVAlignment() != null) {
            cell.setVerticalAlignment(getVAglignment(mCell.getVAlignment()));
        }
        if (contents != null) {
            final IBody savedGeneratedDocument = generatedDocument;
            final XWPFParagraph savedGeneratedParagraph = currentGeneratedParagraph;
            final XWPFParagraph savedTemplateParagraph = currentTemplateParagraph;
            generatedDocument = cell;
            currentGeneratedParagraph = cellParagraph;
            currentTemplateParagraph = cellParagraph;
            try {
                insertObject(cellParagraph, contents, cellRun);
            } finally {
                generatedDocument = savedGeneratedDocument;
                currentGeneratedParagraph = savedGeneratedParagraph;
                currentTemplateParagraph = savedTemplateParagraph;
            }
            cellParagraph.removeRun(cellParagraph.getRuns().indexOf(cellRun));
        }
        final Color backGroundColor = mCell.getBackgroundColor();
        if (backGroundColor != null) {
            cell.setColor(hexColor(backGroundColor));
        }
    }
}
 
Example #26
Source File: Issue149.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
@Test
public void testOldMergeOld() throws Exception {
    source = new NiceXWPFDocument();
    FileOutputStream out = new FileOutputStream("out_149temp.docx");
    source.write(out);
    source.close();
    out.close();
    source.close();

    source = new NiceXWPFDocument(new FileInputStream("out_149temp.docx"));
    target = new NiceXWPFDocument(new FileInputStream(resource));
    result = source.merge(target);

    XWPFParagraph paragraph = result.getParagraphArray(0);
    assertEquals(paragraph.getText(), "{{title}}");
    paragraph = result.getParagraphArray(1);
    assertEquals(paragraph.getText(), "{{+students}}");
    paragraph = result.getParagraphArray(2);
    assertEquals(paragraph.getText(), "{{+teachers}}");

    source.close();
    target.close();
    result.close();

    new File("out_149temp.docx").deleteOnExit();

}
 
Example #27
Source File: BookMark.java    From frpMgr with MIT License 5 votes vote down vote up
/**
 * 构造函数
 * @param ctBookmark
 * @param para
 */
public BookMark(CTBookmark ctBookmark, XWPFParagraph para) {
	this._ctBookmark = ctBookmark;
	this._para = para;
	this._bookmarkName = ctBookmark.getName();
	this._tableCell = null;
	this._isCell = false;
}
 
Example #28
Source File: WordDocxListParser.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
public void addPara(XWPFParagraph para){
    BigInteger numID=para.getNumID();
    if (numID!=null){
        if (!map.containsKey(""+numID.intValue()))
            map.put(""+numID.intValue(), new ArrayList<>());
        map.get(""+numID.intValue()).add(para);
        index.put(para, ""+numID.intValue());
    }
}
 
Example #29
Source File: HeaderFooterBodyContainer.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void setParagraph(XWPFParagraph p, int paraPos) {
    List<XWPFParagraph> paragraphs = (List<XWPFParagraph>) ReflectionUtils.getValue("paragraphs", headerFooter);
    paragraphs.set(paraPos, p);
    CTHdrFtr ctTc = headerFooter._getHdrFtr();
    ctTc.setPArray(paraPos, p.getCTP());

}
 
Example #30
Source File: RunningRunParagraph.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
public RunningRunParagraph(XWPFParagraph paragraph, Pattern pattern) {
    this.paragraph = paragraph;
    this.runs = paragraph.getRuns();
    if (null == runs || runs.isEmpty()) return;

    Matcher matcher = pattern.matcher(paragraph.getText());
    if (matcher.find()) {
        refactorParagraph();
    }

    buildRunEdge(pattern);
}