List of usage examples for org.apache.poi.xwpf.usermodel XWPFRun getText
public String getText(int pos)
From source file:com.deepoove.poi.resolver.TemplateResolver.java
License:Apache License
private static void calcRunPosInParagraph(List<XWPFRun> runs, List<Pair<RunEdge, RunEdge>> pairs) { int size = runs.size(), pos = 0, calc = 0; Pair<RunEdge, RunEdge> pair = pairs.get(pos); RunEdge leftEdge = pair.getLeft();/*from w w w. j a va 2 s . co m*/ RunEdge rightEdge = pair.getRight(); int leftInAll = leftEdge.getAllPos(); int rightInAll = rightEdge.getAllPos(); for (int i = 0; i < size; i++) { XWPFRun run = runs.get(i); String str = run.getText(0); if (null == str) { logger.warn("found the empty text run,may be produce bug:" + run); calc += run.toString().length(); continue; } logger.debug(str); if (str.length() + calc < leftInAll) { calc += str.length(); continue; } for (int j = 0; j < str.length(); j++) { if (calc + j == leftInAll) { leftEdge.setRunPos(i); leftEdge.setRunEdge(j); leftEdge.setText(str); } if (calc + j == rightInAll - 1) { rightEdge.setRunPos(i); rightEdge.setRunEdge(j); rightEdge.setText(str); if (pos == pairs.size() - 1) break; pair = pairs.get(++pos); leftEdge = pair.getLeft(); rightEdge = pair.getRight(); leftInAll = leftEdge.getAllPos(); rightInAll = rightEdge.getAllPos(); } } calc += str.length(); } }
From source file:com.deepoove.poi.resolver.TemplateResolver.java
License:Apache License
public static RunTemplate parseRun(XWPFRun run) { String text = null;//from w w w .j a v a 2s . c o m if (null == run || StringUtils.isBlank(text = run.getText(0))) return null; return (RunTemplate) parseTemplateFactory(text, run); }
From source file:com.qihang.winter.poi.word.parse.ParseWord07.java
License:Apache License
/** * ??//from w ww.j av a 2s . c om * * @author Zerrion * @date 2013-11-16 * @param paragraph * @param map */ private void parseThisParagraph(XWPFParagraph paragraph, Map<String, Object> map) throws Exception { XWPFRun run; XWPFRun currentRun = null;// run,?set,??? String currentText = "";// ?text String text; Boolean isfinde = false;// ???{{ List<Integer> runIndex = new ArrayList<Integer>();// ?run, for (int i = 0; i < paragraph.getRuns().size(); i++) { run = paragraph.getRuns().get(i); text = run.getText(0); if (StringUtils.isEmpty(text)) { continue; } // ""? if (isfinde) { currentText += text; if (currentText.indexOf("{{") == -1) { isfinde = false; runIndex.clear(); } else { runIndex.add(i); } if (currentText.indexOf("}}") != -1) { changeValues(paragraph, currentRun, currentText, runIndex, map); currentText = ""; isfinde = false; } } else if (text.indexOf("{") >= 0) {// ? currentText = text; isfinde = true; currentRun = run; } else { currentText = ""; } if (currentText.indexOf("}}") != -1) { changeValues(paragraph, currentRun, currentText, runIndex, map); isfinde = false; } } }
From source file:com.siemens.sw360.licenseinfo.outputGenerators.DocxUtils.java
License:Open Source License
private static void replaceParagraph(XWPFParagraph paragraph, String placeHolder, String replaceText) { for (XWPFRun r : paragraph.getRuns()) { String text = r.getText(r.getTextPosition()); if (text != null && text.contains(placeHolder)) { text = text.replace(placeHolder, replaceText); r.setText(text, 0);/*from w w w .j a v a 2 s. c o m*/ } } }
From source file:DocxProcess.DocxTemplateReplacer.java
private void replaceParagraph(XWPFParagraph p, Map<String, String> data) { String pText = p.getText(); // complete paragraph as string if (pText.contains("${")) { // if paragraph does not include our pattern, ignore TreeMap<Integer, XWPFRun> posRuns = getPosToRuns(p); Pattern pat = Pattern.compile("\\$\\{(.+?)\\}"); Matcher m = pat.matcher(pText); while (m.find()) { // for all patterns in the paragraph String g = m.group(1); // extract key start and end pos int s = m.start(1); int e = m.end(1); String key = g;/* ww w . j a va 2 s.c om*/ String x = data.get(key); if (x == null) x = ""; SortedMap<Integer, XWPFRun> range = posRuns.subMap(s - 2, true, e + 1, true); // get runs which contain the pattern boolean found1 = false; // found $ boolean found2 = false; // found { boolean found3 = false; // found } XWPFRun prevRun = null; // previous run handled in the loop XWPFRun found2Run = null; // run in which { was found int found2Pos = -1; // pos of { within above run for (XWPFRun r : range.values()) { if (r == prevRun) continue; // this run has already been handled if (found3) break; // done working on current key pattern prevRun = r; for (int k = 0;; k++) { // iterate over texts of run r if (found3) break; String txt = null; try { txt = r.getText(k); // note: should return null, but throws exception if the text does not exist } catch (Exception ex) { } if (txt == null) break; // no more texts in the run, exit loop if (txt.contains("$") && !found1) { // found $, replaceAll it with value from data map txt = txt.replaceFirst("\\$", x); found1 = true; } if (txt.contains("{") && !found2 && found1) { found2Run = r; // found { replaceAll it with empty string and remember location found2Pos = txt.indexOf('{'); txt = txt.replaceFirst("\\{", ""); found2 = true; } if (found1 && found2 && !found3) { // find } and set all chars between { and } to blank if (txt.contains("}")) { if (r == found2Run) { // complete pattern was within a single run txt = txt.substring(0, found2Pos) + txt.substring(txt.indexOf('}')); } else // pattern spread across multiple runs txt = txt.substring(txt.indexOf('}')); } else if (r == found2Run) // same run as { but no }, remove all text starting at { txt = txt.substring(0, found2Pos); else txt = ""; // run between { and }, set text to blank } if (txt.contains("}") && !found3) { txt = txt.replaceFirst("\\}", ""); found3 = true; } r.setText(txt, k); } } } // System.out.println(p.getText()); } }
From source file:javaapplication1.AnotherPOI.java
public static void replaceText(String findText, String replaceText) { try {//from ww w . j a v a 2 s.co m XWPFDocument doc = new XWPFDocument(OPCPackage.open("D:\\template.docx")); for (XWPFParagraph p : doc.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null && text.contains(findText)) { text = text.replace(findText, replaceText); r.setText(text, 0); } } } } for (XWPFTable tbl : doc.getTables()) { for (XWPFTableRow row : tbl.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph p : cell.getParagraphs()) { for (XWPFRun r : p.getRuns()) { String text = r.getText(0); if (text.contains(findText)) { text = text.replace(findText, replaceText); r.setText(text); } } } } } } doc.write(new FileOutputStream("D:\\result.docx")); } catch (IOException ex) { Logger.getLogger(AnotherPOI.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidFormatException ex) { Logger.getLogger(AnotherPOI.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:msoffice.WriteinTemplate.java
public static void main(String[] args) throws FileNotFoundException, InvalidFormatException, IOException { FileInputStream fis = new FileInputStream("H:\\OFICIOTEMPLATE.docx"); XWPFDocument doc = new XWPFDocument(fis); for (XWPFParagraph p : doc.getParagraphs()) { for (XWPFRun r : p.getRuns()) { //System.out.println(r); String text = r.getText(0); System.out.println(text); if (text.contains("unidad")) { text = text.replace("unidad", "CICTE/W-6.a/02.00"); r.setText(text, 0);/*from w w w . j av a2 s . c o m*/ System.out.println(text); } if (text.contains("#receptor#")) { text = text.replace("#receptor#", "Gral Brig Jefe del Servicio de Material de Guerra del Ejrcito"); r.setText(text, 0); System.out.println(text); } if (text.contains("#asunto#")) { text = text.replace("#asunto#", "Sobre artculo de MG (Armamento) y apoyo de elemento tcnico."); r.setText(text, 0); System.out.println(text); } if (text.contains("#referencia#")) { text = text.replace("#referencia#", "Oficio N289/CICTE del 01 julio de 2015."); r.setText(text, 0); System.out.println(text); } if (text.contains("#cuerpo#")) { text = text.replace("#cuerpo#", "Tengo el honor de dirigirme a Ud., para manifestarle que en relacin a la solicitud de prstamo de una (01) ametralladora BROWNING Cal .50 y la participacin del elemento tcnico Tco 2da MAM Pacheco Tejada Henry, para las pruebas del vehculo blindado OTORONGO, las cuales se han suspendido y sern reprogramadas.\n" + "Asimismo, se informar de manera oportuna la fecha de realizacin de las pruebas del vehculo blindado OTORONGO, para poder contar con artculo de MG (Armamento) y apoyo de elemento tcnico solicitado.\n" + "Hago propicia la oportunidad para expresarle a Ud. los sentimientos de mi especial consideracin y estima personal."); r.setText(text, 0); System.out.println(text); } } } doc.write(new FileOutputStream("output.docx")); }
From source file:org.eclipse.sw360.licenseinfo.outputGenerators.DocxUtils.java
License:Open Source License
private static void replaceParagraph(XWPFParagraph paragraph, String placeHolder, String replaceText) { for (XWPFRun run : paragraph.getRuns()) { String text = run.getText(run.getTextPosition()); if (text != null && text.contains(placeHolder)) { text = text.replace(placeHolder, replaceText); String[] split = text.split("\n"); run.setText(split[0], 0);/*from www . j a va 2 s .c om*/ for (int i = 1; i < split.length; i++) { run.addBreak(); run.setText(split[i]); } } } }
From source file:org.kino.server.api.contractgenerator.java
static private long replaceInParagraphs(Map<String, String> replacements, List<XWPFParagraph> xwpfParagraphs) { long count = 0; for (XWPFParagraph paragraph : xwpfParagraphs) { List<XWPFRun> runs = paragraph.getRuns(); for (Map.Entry<String, String> replPair : replacements.entrySet()) { String find = replPair.getKey(); String repl = replPair.getValue(); TextSegement found = paragraph.searchText(find, new PositionInParagraph()); if (found != null) { count++;/*from w w w . j a v a 2 s . c om*/ if (found.getBeginRun() == found.getEndRun()) { // whole search string is in one Run XWPFRun run = runs.get(found.getBeginRun()); String runText = run.getText(run.getTextPosition()); String replaced = runText.replace(find, repl); run.setText(replaced, 0); } else { // The search string spans over more than one Run // Put the Strings together StringBuilder b = new StringBuilder(); for (int runPos = found.getBeginRun(); runPos <= found.getEndRun(); runPos++) { XWPFRun run = runs.get(runPos); b.append(run.getText(run.getTextPosition())); } String connectedRuns = b.toString(); String replaced = connectedRuns.replace(find, repl); // The first Run receives the replaced String of all connected Runs XWPFRun partOne = runs.get(found.getBeginRun()); partOne.setText(replaced, 0); // Removing the text in the other Runs. for (int runPos = found.getBeginRun() + 1; runPos <= found.getEndRun(); runPos++) { XWPFRun partNext = runs.get(runPos); partNext.setText("", 0); } } } } } return count; }
From source file:org.obeonetwork.m2doc.parser.test.RunIteratorTests.java
License:Open Source License
@Test public void testNonEmptyDoc() throws InvalidFormatException, IOException { FileInputStream is = new FileInputStream("templates/RunIteratorTest.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();/*from w w w .j a v a 2 s.c om*/ 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()); }