Example usage for org.apache.poi.xwpf.usermodel XWPFRun setText

List of usage examples for org.apache.poi.xwpf.usermodel XWPFRun setText

Introduction

In this page you can find the example usage for org.apache.poi.xwpf.usermodel XWPFRun setText.

Prototype

public void setText(String value) 

Source Link

Document

Sets the text of this text run

Usage

From source file:org.obeonetwork.m2doc.generator.M2DocEvaluator.java

License:Open Source License

@Override
public IConstruct caseRepresentation(Representation representation) {
    XWPFRun imageRun = insertRun(representation.getStyleRun());
    IProvider provider = representation.getProvider();
    if (provider == null) {
        insertMessage(currentGeneratedParagraph, ValidationMessageLevel.ERROR,
                representation.getValidationMessages().get(0).getMessage());
    } else {/*  www  .  jav  a 2s.c om*/
        Map<String, Object> parameters;
        try {
            parameters = setupParametersMapForRepresentation(representation, provider);
            List<String> imagePaths = ((AbstractDiagramProvider) provider)
                    .getRepresentationImagePath(resourceSetForModels, parameters);
            usedProviders.add((AbstractDiagramProvider) provider);
            for (String imagePathStr : imagePaths) {
                URI imageURI = URI.createFileURI(imagePathStr);
                imageURI = imageURI.resolve(representation.eResource().getURI());

                imageRun.setText("");
                imageRun.getCTR().getInstrTextList().clear();

                final MImage image = new MImageImpl(uriConverter, imageURI);
                // get default image size if needed
                image.setConserveRatio(representation.getHeight() == 0 || representation.getWidth() == 0);
                if (representation.getHeight() != 0) {
                    image.setHeight(representation.getHeight());
                }
                if (representation.getWidth() != 0) {
                    image.setWidth(representation.getWidth());
                }
                insertMImage(imageRun, image);
            }
        } catch (IllegalArgumentException e) {
            insertMessage(currentGeneratedParagraph, ValidationMessageLevel.ERROR, e.getMessage());
        } catch (ProviderException e) {
            insertMessage(currentGeneratedParagraph, ValidationMessageLevel.ERROR,
                    "A problem occured while creating image from an diagram provider: " + e.getMessage());
        }

    }

    return representation;

}

From source file:org.obeonetwork.m2doc.generator.TableClientProcessor.java

License:Open Source License

/**
 * Create a table in a document./*  ww  w . j  a v  a  2  s . c  o m*/
 * 
 * @param tableRun
 *            the run after which the table must be created
 * @param first
 *            Whether it's the first table to insert or not
 * @param mtable
 *            The table description
 * @return The newly created table.
 */
private XWPFTable createTableInDocument(XWPFRun tableRun, boolean first, MTable mtable) {
    XWPFTable table;
    if (!first) {
        ((XWPFDocument) body).createParagraph();
    }
    if (showTitle() && mtable.getLabel() != null) {
        XWPFRun captionRun;
        if (first) {
            captionRun = tableRun;
            IRunBody runBody = captionRun.getParent();
            if (runBody instanceof XWPFParagraph) {
                ((XWPFParagraph) runBody).setSpacingAfter(0);
            }
        } else {
            XWPFParagraph captionParagraph = ((XWPFDocument) body).createParagraph();
            captionParagraph.setSpacingAfter(0);
            captionRun = captionParagraph.createRun();
        }
        captionRun.setText(mtable.getLabel());
        captionRun.setBold(true);
    }
    table = ((XWPFDocument) body).createTable();
    return table;
}

From source file:org.obeonetwork.m2doc.generator.TableClientProcessor.java

License:Open Source License

/**
 * Create a table in a table cell.//from  ww w .j a  v a  2s  . c  o m
 * 
 * @param tableRun
 *            The table run
 * @param first
 *            whether it's the 1st table created in this cell
 * @param mtable
 *            The table description
 * @param tcell
 *            The cell in which to create a new table
 * @return The newly creatted table, located in the given cell.
 */
private XWPFTable createTableInCell(XWPFRun tableRun, boolean first, MTable mtable, XWPFTableCell tcell) {
    XWPFTable table;
    if (showTitle() && mtable.getLabel() != null) {
        XWPFRun captionRun;
        if (first) {
            captionRun = tableRun;
            IRunBody runBody = captionRun.getParent();
            if (runBody instanceof XWPFParagraph) {
                ((XWPFParagraph) runBody).setSpacingAfter(0);
            }
        } else {
            XWPFParagraph captionParagraph = tcell.addParagraph();
            captionParagraph.setSpacingAfter(0);
            captionRun = captionParagraph.createRun();
        }
        captionRun.setText(mtable.getLabel());
        captionRun.setBold(true);
    }
    CTTbl ctTbl = tcell.getCTTc().addNewTbl();
    table = new XWPFTable(ctTbl, tcell);
    int tableRank = tcell.getTables().size();
    tcell.insertTable(tableRank, table);
    // A paragraph is mandatory at the end of a cell, so let's always add one.
    tcell.addParagraph();
    return table;
}

From source file:org.obeonetwork.m2doc.generator.TableClientProcessor.java

License:Open Source License

/**
 * 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.
 * /*from   w  ww .jav  a2 s . c o  m*/
 * @param cell
 *            Cell to fill in
 * @param text
 *            Text to set in the cell
 * @param style
 *            Style to use, can be <code>null</code>
 */
private void setCellContent(XWPFTableCell cell, String text, MStyle style) {
    XWPFParagraph cellParagraph = cell.getParagraphs().get(0);
    XWPFRun cellRun = cellParagraph.createRun();
    cellRun.setText(text);
    if (style != null) {
        cell.setColor(hexColor(style.getBackgroundColor()));
        applyTableClientStyle(cellRun, style);
    }
}

From source file:org.obeonetwork.m2doc.generator.TemplateProcessor.java

License:Open Source License

/**
 * Insert a new run for a fragment of text following a '\n' character.
 * //from  w  ww  .j av  a  2 s.  co  m
 * @param fragment
 *            the text fragment to insert
 * @param srcRun
 *            the run to copy the style from.
 * @return the generated run.
 */
private XWPFRun insertFragment(String fragment, XWPFRun srcRun) {
    XWPFRun generatedRun = currentGeneratedParagraph.createRun();
    generatedRun.getCTR().set(srcRun.getCTR().copy());
    generatedRun.getCTR().getInstrTextList().clear();
    generatedRun.setText(fragment);
    return generatedRun;
}

From source file:org.obeonetwork.m2doc.generator.TemplateProcessor.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from w w w  .j  a  va2 s.  c o  m*/
public AbstractConstruct caseRepetition(Repetition object) {
    // first evaluate the query
    @SuppressWarnings("restriction")
    EvaluationResult result = new QueryEvaluationEngine(queryEnvironment).eval(object.getQuery(),
            definitions.getCurrentDefinitions());
    if (result == null || result.getDiagnostic().getCode() == Diagnostic.ERROR) {
        // insert the tag runs as is.
        for (XWPFRun tagRun : object.getRuns()) {
            insertRun(tagRun);
        }
        // insert the error message.
        XWPFRun run = currentGeneratedParagraph.createRun();
        if (result != null) {
            run.setText(result.getDiagnostic().getMessage());
        } else {
            run.setText("couldn't evaluate expression");
        }
        if (result == null || result.getDiagnostic().getCode() == Diagnostic.ERROR) {
            run.setBold(true);
            run.setColor(ERROR_COLOR);
        }

        for (XWPFRun tagRun : object.getClosingRuns()) {
            insertRun(tagRun);
        }
    } else {
        List<Object> iteration = new ArrayList<Object>();
        if (result.getResult() instanceof Collection) {
            iteration.addAll((Collection<? extends Object>) result.getResult());
        } else {
            iteration.add(result.getResult());
        }
        for (Object val : iteration) {
            this.definitions.setValue(object.getIterationVar(), val);
            for (AbstractConstruct construct : object.getSubConstructs()) {
                doSwitch(construct);
            }
            // if the {gd:endfor} lies on a distinct paragraph, insert a new
            // paragraph there to take this into acount.
            int bodySize = object.getSubConstructs().size();
            if (bodySize > 0 && object.getSubConstructs().get(bodySize - 1).getRuns().size() > 0) {
                AbstractConstruct lastBodyPart = object.getSubConstructs().get(bodySize - 1);
                int runNumber = lastBodyPart.getRuns().size();
                XWPFRun lastRun = lastBodyPart.getRuns().get(runNumber - 1);
                int closingRunNumber = object.getClosingRuns().size();
                if (closingRunNumber > 0 && object.getClosingRuns().get(0).getParent() != lastRun.getParent()) {
                    forceNewParagraph = true;
                }
            }
        }
    }
    return object;

}

From source file:org.obeonetwork.m2doc.generator.TemplateProcessor.java

License:Open Source License

@Override
public AbstractConstruct caseConditionnal(Conditionnal object) {
    @SuppressWarnings("restriction")
    EvaluationResult result = new QueryEvaluationEngine(queryEnvironment).eval(object.getQuery(),
            definitions.getCurrentDefinitions());
    // XXX : result can be null here : check that before using it.
    if (result.getResult() instanceof Boolean) {
        if ((Boolean) result.getResult()) {
            for (AbstractConstruct construct : object.getSubConstructs()) {
                doSwitch(construct);/* ww  w.  j av  a2 s .  c o  m*/
            }
        } else if (object.getAlternative() != null) {
            doSwitch(object.getAlternative());
        } else if (object.getElse() != null) {
            for (AbstractConstruct construct : object.getElse().getSubConstructs()) {
                doSwitch(construct);
            }
        }
    } else {
        for (XWPFRun tagRun : object.getRuns()) {
            insertRun(tagRun);
        }
        XWPFRun run = currentGeneratedParagraph.createRun();
        run.setText(result.getDiagnostic().getMessage());
        if (result.getDiagnostic().getCode() == Diagnostic.ERROR) {
            run.setBold(true);
            run.setColor(ERROR_COLOR);
        }
        for (XWPFRun tagRun : object.getClosingRuns()) {
            insertRun(tagRun);
        }
    }
    return object;
}

From source file:org.obeonetwork.m2doc.generator.TemplateProcessor.java

License:Open Source License

@Override
public AbstractConstruct caseImage(Image object) {
    XWPFRun imageRun = insertRun(object.getStyleRun());
    imageRun.setText("");
    imageRun.getCTR().getInstrTextList().clear();
    String filePath;/*from w ww.j  ava2  s. c  om*/
    if ("".equals(this.rootProjectPath) || this.rootProjectPath == null) {
        filePath = object.getFileName();
    } else {
        filePath = this.rootProjectPath + "/" + object.getFileName();
    }
    try {
        int heigth = Units.toEMU(object.getHeight());
        int width = Units.toEMU(object.getWidth());
        imageRun.addPicture(new FileInputStream(filePath), getPictureType(object.getFileName()),
                object.getFileName(), width, heigth);
    } catch (InvalidFormatException e) {
        imageRun.setText("Picture in " + object.getFileName() + " has an invalid format.");
        imageRun.setBold(true);
        imageRun.setColor(ERROR_COLOR);
    } catch (FileNotFoundException e) {
        imageRun.setText("File " + filePath + " cannot be found.");
        imageRun.setBold(true);
        imageRun.setColor(ERROR_COLOR);
    } catch (IOException e) {
        imageRun.setText("An I/O Problem occured while reading file ");
        imageRun.setBold(true);
        imageRun.setColor(ERROR_COLOR);
    }
    return super.caseImage(object);
}

From source file:org.obeonetwork.m2doc.generator.TemplateValidationGenerator.java

License:Open Source License

/**
 * Insert all messages in a run next to the one of the given construct subject to the error.
 * /*from  w w w  .j a  v  a 2 s .c om*/
 * @param abstractConstruct
 *            the construct that may contains messages to insert into the produced document.
 */
protected void insertErrorMessages(AbstractConstruct abstractConstruct) {
    final List<TemplateValidationMessage> messages = abstractConstruct.getValidationMessages();
    final Map<XWPFRun, Integer> offsets = new HashMap<XWPFRun, Integer>();
    for (TemplateValidationMessage message : messages) {
        offsets.put(message.getLocation(), 0);
    }
    for (TemplateValidationMessage message : messages) {
        inError = inError || message.getLevel() == ValidationMessageLevel.ERROR;
        final int offset = offsets.get(message.getLocation());
        final int shift = addRunError(message, offset);
        offsets.put(message.getLocation(), offset + shift);
    }
    for (Entry<XWPFRun, Integer> entry : offsets.entrySet()) {
        if (entry.getValue() != 0) {
            // We insert a blank after the last error message
            final IRunBody parent = entry.getKey().getParent();
            if (parent instanceof XWPFParagraph) {
                XWPFRun newBlankRun = ((XWPFParagraph) parent).insertNewRun(entry.getValue() + 1);
                newBlankRun.setText(BLANK_SEPARATOR);
            }
        }
    }
}

From source file:org.obeonetwork.m2doc.generator.TemplateValidationGenerator.java

License:Open Source License

/**
 * Inserts the given {@link TemplateValidationMessage} in a run next to the one of the given construct subject to the message.
 * /*from w w  w  .j  av a 2s .c o  m*/
 * @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;
}