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

The following examples show how to use org.apache.poi.xwpf.usermodel.XWPFRun#setText() . 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 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 2
Source File: BookMark.java    From frpMgr with MIT License 6 votes vote down vote up
/** 
 * Insert text into the Word document in the location indicated by this 
 * bookmark. 
 * 
 * @param bookmarkValue An instance of the String class that encapsulates 
 * the text to insert into the document. 
 * @param where A primitive int whose value indicates where the text ought 
 * to be inserted. There are three options controlled by constants; insert 
 * the text immediately in front of the bookmark (Bookmark.INSERT_BEFORE), 
 * insert text immediately after the bookmark (Bookmark.INSERT_AFTER) and 
 * replace any and all text that appears between the bookmark's square 
 * brackets (Bookmark.REPLACE). 
 */
public void insertTextAtBookMark(String bookmarkValue, int where) {

	//根据标签的类型,进行不同的操作
	if (this._isCell) {
		this.handleBookmarkedCells(bookmarkValue, where);
	} else {

		//普通标签,直接创建一个元素
		XWPFRun run = this._para.createRun();
		run.setText(bookmarkValue);
		switch (where) {
		case BookMark.INSERT_AFTER:
			this.insertAfterBookmark(run);
			break;
		case BookMark.INSERT_BEFORE:
			this.insertBeforeBookmark(run);
			break;
		case BookMark.REPLACE:
			this.replaceBookmark(run);
			break;
		}
	}
}
 
Example 3
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 4
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 5
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 6
Source File: TextRenderPolicy.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
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 7
Source File: SimpleTable.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
public static void createSimpleTable() throws Exception {
    @SuppressWarnings("resource")
XWPFDocument doc = new XWPFDocument();

    XWPFTable table = doc.createTable(3, 3);

    table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE");

    // table cells have a list of paragraphs; there is an initial
    // paragraph created when the cell is created. If you create a
    // paragraph in the document to put in the cell, it will also
    // appear in the document following the table, which is probably
    // not the desired result.
    XWPFParagraph p1 = table.getRow(0).getCell(0).getParagraphs().get(0);

    XWPFRun r1 = p1.createRun();
    r1.setBold(true);
    r1.setText("The quick brown fox");
    r1.setItalic(true);
    r1.setFontFamily("Courier");
    r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
    r1.setTextPosition(100);

    table.getRow(2).getCell(2).setText("only text");

    FileOutputStream out = new FileOutputStream("simpleTable.docx");
    doc.write(out);
    out.close();
}
 
Example 8
Source File: HeaderFooterBodyContainnerTest.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
@Test
void testClearPlaceholder2() {
    XWPFRun createRun = paragraph.createRun();
    createRun.setText("123");
    createRun = paragraph.createRun();
    createRun.setText("456");

    container.clearPlaceholder(createRun);

    assertEquals(header.getParagraphs().size(), 3);
}
 
Example 9
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 10
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 11
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 12
Source File: AbstractRenderPolicy.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * 对于不在当前标签位置的操作,需要清除标签
 * 
 * @param context
 * @param clearParagraph
 * 
 */
public static void clearPlaceholder(RenderContext<?> context, boolean clearParagraph) {
    XWPFRun run = context.getRun();
    if (clearParagraph) {
        BodyContainer bodyContainer = BodyContainerFactory.getBodyContainer(run);
        bodyContainer.clearPlaceholder(run);
    } else {
        run.setText("", 0);
    }
}
 
Example 13
Source File: CellBodyContainnerTest.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
@Test
void testClearPlaceholder2() {
    XWPFRun createRun = paragraph.createRun();
    createRun.setText("123");
    createRun = paragraph.createRun();
    createRun.setText("456");

    container.clearPlaceholder(createRun);

    assertEquals(cell.getParagraphs().size(), 3);
}
 
Example 14
Source File: TemplateValidationGenerator.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Inserts the given {@link TemplateValidationMessage} in a run next to the one of the given construct subject to the message.
 * 
 * @param message
 *            the {@link TemplateValidationMessage} to insert
 *            the error message to insert in a run
 * @param offset
 *            the offset in number of {@link XWPFRun} to insert after {@link TemplateValidationMessage#getLocation() message location}
 * @return the number of inserted {@link XWPFRun}
 */
private int addRunError(TemplateValidationMessage message, int offset) {
    int res = 0;

    if (message.getLocation().getParent() instanceof XWPFParagraph) {
        XWPFParagraph paragraph = (XWPFParagraph) message.getLocation().getParent();
        final int basePosition = paragraph.getRuns().indexOf(message.getLocation()) + offset;

        // separation run.
        res++;
        final String color = M2DocUtils.getColor(message.getLevel());
        XWPFRun newBlankRun = paragraph.insertNewRun(basePosition + res);
        newBlankRun.setText(BLANK_SEPARATOR);

        res++;
        final XWPFRun separationRun = paragraph.insertNewRun(basePosition + res);
        separationRun.setText(LOCATION_SEPARATOR);
        separationRun.setColor(color);
        separationRun.setFontSize(ERROR_MESSAGE_FONT_SIZE);
        final CTHighlight separationHighlight = separationRun.getCTR().getRPr().addNewHighlight();
        separationHighlight.setVal(STHighlightColor.LIGHT_GRAY);

        res++;
        final XWPFRun messageRun = paragraph.insertNewRun(basePosition + res);
        messageRun.setText(message.getMessage());
        messageRun.setColor(color);
        messageRun.setFontSize(ERROR_MESSAGE_FONT_SIZE);
        final CTHighlight messageHighlight = messageRun.getCTR().getRPr().addNewHighlight();
        messageHighlight.setVal(STHighlightColor.LIGHT_GRAY);
    }

    return res;
}
 
Example 15
Source File: ParseWord07.java    From jeasypoi with Apache License 2.0 5 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 16
Source File: Issue331.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
public void testinsertNewRunRun() throws FileNotFoundException, IOException {
    XWPFDocument doc = new XWPFDocument(new FileInputStream("src/test/resources/issue/331_hyper.docx"));
    XWPFParagraph createParagraph = doc.getParagraphArray(0);
    XWPFRun insertNewRun = createParagraph.insertNewRun(0);
    insertNewRun.setText("Hi");

    // FileOutputStream out = new FileOutputStream("out_tem.docx");
    // doc.write(out);
    // doc.close();
    // out.close();

}
 
Example 17
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 18
Source File: ETLWordDocumentGenerator.java    From WhiteRabbit with Apache License 2.0 4 votes vote down vote up
private static void addToParagraph(XWPFParagraph paragraph, String text) {
	XWPFRun run = paragraph.createRun();
	run.setText(text);
}
 
Example 19
Source File: XWPFParagraphWrapperTest.java    From poi-tl with Apache License 2.0 4 votes vote down vote up
@Test
public void testWrapper() throws FileNotFoundException, IOException {

    XWPFDocument doc = new XWPFDocument();
    XWPFParagraph paragraph = doc.createParagraph();

    XWPFParagraphWrapper wrapper = new XWPFParagraphWrapper(paragraph);
    XWPFRun hyperRun = wrapper.insertNewHyperLinkRun(0, "http:deepoove.com");
    hyperRun.setText("Deepoove0");

    XWPFRun newRun = wrapper.insertNewRun(0);
    newRun.setText("website0");
    newRun = wrapper.insertNewRun(0);
    newRun.setText("website1");
    newRun = wrapper.insertNewRun(0);
    newRun.setText("website2");

    hyperRun = wrapper.insertNewHyperLinkRun(0, "http:deepoove.com");
    hyperRun.setText("Deepoove1");

    XWPFFieldRun fieldRun = wrapper.insertNewField(0);
    CTSimpleField ctField = fieldRun.getCTField();
    ctField.setInstr(" CREATEDATE  \\* MERGEFORMAT ");
    fieldRun.setText("2019");

    assertEquals(paragraph.getRuns().size(), 6);

    for (int i = 6; i >= 0; i--) {
        wrapper.removeRun(i);
    }
    assertEquals(paragraph.getRuns().size(), 0);

    doc.close();

}
 
Example 20
Source File: M2DocUtils.java    From M2Doc with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Set the given message to the given {@link XWPFRun}.
 * 
 * @param run
 *            the {@link XWPFRun}
 * @param level
 *            the {@link ValidationMessageLevel}
 * @param message
 *            the message
 * @return the {@link TemplateValidationMessage}
 */
public static TemplateValidationMessage setRunMessage(XWPFRun run, ValidationMessageLevel level, String message) {
    run.setText(message);
    run.setBold(true);
    run.setColor(getColor(level));

    return new TemplateValidationMessage(level, message, run);
}