Example usage for java.awt.font TextAttribute BACKGROUND

List of usage examples for java.awt.font TextAttribute BACKGROUND

Introduction

In this page you can find the example usage for java.awt.font TextAttribute BACKGROUND.

Prototype

TextAttribute BACKGROUND

To view the source code for java.awt.font TextAttribute BACKGROUND.

Click Source Link

Document

Attribute key for the paint used to render the background of the text.

Usage

From source file:Main.java

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    AttributedString astr = new AttributedString("aString");
    astr.addAttribute(TextAttribute.FONT, new Font("", 1, 30), 1, 2);
    astr.addAttribute(TextAttribute.BACKGROUND, Color.red, 2, 3);

    TextLayout tl = new TextLayout(astr.getIterator(), g2d.getFontRenderContext());
    tl.draw(g2d, 10, 20);// w ww. j ava 2 s  . c  om
}

From source file:TextAttributesBackground.java

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    AttributedString as1 = new AttributedString("1234567890");
    as1.addAttribute(TextAttribute.BACKGROUND, Color.LIGHT_GRAY, 2, 9);
    g2d.drawString(as1.getIterator(), 15, 60);
}

From source file:BasicShapes.java

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;

    int x = 10, y = 10, start = 2, end = 4;

    AttributedString astr = new AttributedString("aString");
    astr.addAttribute(TextAttribute.FONT, new Font("", 1, 1), start, end);
    astr.addAttribute(TextAttribute.BACKGROUND, Color.red, start, end);

    // Draw mixed-style text
    TextLayout tl = new TextLayout(astr.getIterator(), g2d.getFontRenderContext());
    tl.draw(g2d, x, y);//from   ww w  .  j a  va2  s .c o m

}

From source file:com.qumasoft.guitools.compare.ContentRow.java

@Override
public void paint(Graphics g) {
    if ((getRowType() == ROWTYPE_REPLACE) && rowHadAnnotations) {
        Graphics2D g2 = (Graphics2D) g;

        String s = getText();//www  .  ja va  2  s  .  co m

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        if (s.length() > 0) {
            int index = 0;
            AttributedString attributedString = new AttributedString(s, getFont().getAttributes());
            try {
                for (byte rType : fileACharacterTypeArray) {
                    switch (rType) {
                    case ContentRow.ROWTYPE_DELETE:
                        attributedString.addAttribute(TextAttribute.STRIKETHROUGH, null, index, index + 1);
                        break;
                    case ContentRow.ROWTYPE_REPLACE:
                        attributedString.addAttribute(TextAttribute.BACKGROUND,
                                ColorManager.getReplaceCompareHiliteBackgroundColor(), index, index + 1);
                        break;
                    default:
                        break;
                    }
                    index++;
                }
                g2.drawString(attributedString.getIterator(), 0, getFont().getSize());
            } catch (java.lang.IllegalArgumentException e) {
                LOGGER.log(Level.WARNING, "bad replace indexes. begin index: [" + index + "] end index: ["
                        + index + "]. String length: [" + s.length() + "]");
            }
        } else {
            super.paint(g);
        }
    } else {
        super.paint(g);
    }
}

From source file:net.sf.jasperreports.engine.util.JEditorPaneHtmlMarkupProcessor.java

@Override
protected Map<Attribute, Object> getAttributes(AttributeSet attrSet) {
    Map<Attribute, Object> attrMap = new HashMap<Attribute, Object>();
    if (attrSet.isDefined(StyleConstants.FontFamily)) {
        attrMap.put(TextAttribute.FAMILY, StyleConstants.getFontFamily(attrSet));
    }/*  w  ww. ja v  a 2 s. co  m*/

    if (attrSet.isDefined(StyleConstants.Bold)) {
        attrMap.put(TextAttribute.WEIGHT,
                StyleConstants.isBold(attrSet) ? TextAttribute.WEIGHT_BOLD : TextAttribute.WEIGHT_REGULAR);
    }

    if (attrSet.isDefined(StyleConstants.Italic)) {
        attrMap.put(TextAttribute.POSTURE, StyleConstants.isItalic(attrSet) ? TextAttribute.POSTURE_OBLIQUE
                : TextAttribute.POSTURE_REGULAR);
    }

    if (attrSet.isDefined(StyleConstants.Underline)) {
        attrMap.put(TextAttribute.UNDERLINE,
                StyleConstants.isUnderline(attrSet) ? TextAttribute.UNDERLINE_ON : null);
    }

    if (attrSet.isDefined(StyleConstants.StrikeThrough)) {
        attrMap.put(TextAttribute.STRIKETHROUGH,
                StyleConstants.isStrikeThrough(attrSet) ? TextAttribute.STRIKETHROUGH_ON : null);
    }

    if (attrSet.isDefined(StyleConstants.FontSize)) {
        attrMap.put(TextAttribute.SIZE, StyleConstants.getFontSize(attrSet));
    }

    if (attrSet.isDefined(StyleConstants.Foreground)) {
        attrMap.put(TextAttribute.FOREGROUND, StyleConstants.getForeground(attrSet));
    }

    if (attrSet.isDefined(StyleConstants.Background)) {
        attrMap.put(TextAttribute.BACKGROUND, StyleConstants.getBackground(attrSet));
    }

    //FIXME: why StyleConstants.isSuperscript(attrSet) does return false
    if (attrSet.isDefined(StyleConstants.Superscript) && !StyleConstants.isSubscript(attrSet)) {
        attrMap.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER);
    }

    if (attrSet.isDefined(StyleConstants.Subscript) && StyleConstants.isSubscript(attrSet)) {
        attrMap.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB);
    }

    return attrMap;
}

From source file:net.sf.jasperreports.engine.util.JRStyledTextParser.java

/**
 *
 *///from  w w  w .j ava2 s .  com
private void parseStyle(JRStyledText styledText, Node parentNode) throws SAXException {
    NodeList nodeList = parentNode.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.TEXT_NODE) {
            styledText.append(node.getNodeValue());
        } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_style.equals(node.getNodeName())) {
            NamedNodeMap nodeAttrs = node.getAttributes();

            Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>();

            if (nodeAttrs.getNamedItem(ATTRIBUTE_fontName) != null) {
                styleAttrs.put(TextAttribute.FAMILY, nodeAttrs.getNamedItem(ATTRIBUTE_fontName).getNodeValue());
            }

            if (nodeAttrs.getNamedItem(ATTRIBUTE_isBold) != null) {
                styleAttrs.put(TextAttribute.WEIGHT,
                        Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isBold).getNodeValue())
                                ? TextAttribute.WEIGHT_BOLD
                                : TextAttribute.WEIGHT_REGULAR);
            }

            if (nodeAttrs.getNamedItem(ATTRIBUTE_isItalic) != null) {
                styleAttrs.put(TextAttribute.POSTURE,
                        Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isItalic).getNodeValue())
                                ? TextAttribute.POSTURE_OBLIQUE
                                : TextAttribute.POSTURE_REGULAR);
            }

            if (nodeAttrs.getNamedItem(ATTRIBUTE_isUnderline) != null) {
                styleAttrs.put(TextAttribute.UNDERLINE,
                        Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isUnderline).getNodeValue())
                                ? TextAttribute.UNDERLINE_ON
                                : null);
            }

            if (nodeAttrs.getNamedItem(ATTRIBUTE_isStrikeThrough) != null) {
                styleAttrs.put(TextAttribute.STRIKETHROUGH,
                        Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isStrikeThrough).getNodeValue())
                                ? TextAttribute.STRIKETHROUGH_ON
                                : null);
            }

            if (nodeAttrs.getNamedItem(ATTRIBUTE_size) != null) {
                styleAttrs.put(TextAttribute.SIZE,
                        Float.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_size).getNodeValue()));
            }

            if (nodeAttrs.getNamedItem(ATTRIBUTE_pdfFontName) != null) {
                styleAttrs.put(JRTextAttribute.PDF_FONT_NAME,
                        nodeAttrs.getNamedItem(ATTRIBUTE_pdfFontName).getNodeValue());
            }

            if (nodeAttrs.getNamedItem(ATTRIBUTE_pdfEncoding) != null) {
                styleAttrs.put(JRTextAttribute.PDF_ENCODING,
                        nodeAttrs.getNamedItem(ATTRIBUTE_pdfEncoding).getNodeValue());
            }

            if (nodeAttrs.getNamedItem(ATTRIBUTE_isPdfEmbedded) != null) {
                styleAttrs.put(JRTextAttribute.IS_PDF_EMBEDDED,
                        Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isPdfEmbedded).getNodeValue()));
            }

            if (nodeAttrs.getNamedItem(ATTRIBUTE_forecolor) != null) {
                Color color = JRColorUtil.getColor(nodeAttrs.getNamedItem(ATTRIBUTE_forecolor).getNodeValue(),
                        Color.black);
                styleAttrs.put(TextAttribute.FOREGROUND, color);
            }

            if (nodeAttrs.getNamedItem(ATTRIBUTE_backcolor) != null) {
                Color color = JRColorUtil.getColor(nodeAttrs.getNamedItem(ATTRIBUTE_backcolor).getNodeValue(),
                        Color.black);
                styleAttrs.put(TextAttribute.BACKGROUND, color);
            }

            int startIndex = styledText.length();

            parseStyle(styledText, node);

            styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length()));
        } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_bold.equalsIgnoreCase(node.getNodeName())) {
            Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>();
            styleAttrs.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);

            int startIndex = styledText.length();

            parseStyle(styledText, node);

            styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length()));
        } else if (node.getNodeType() == Node.ELEMENT_NODE
                && NODE_italic.equalsIgnoreCase(node.getNodeName())) {
            Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>();
            styleAttrs.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);

            int startIndex = styledText.length();

            parseStyle(styledText, node);

            styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length()));
        } else if (node.getNodeType() == Node.ELEMENT_NODE
                && NODE_underline.equalsIgnoreCase(node.getNodeName())) {
            Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>();
            styleAttrs.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);

            int startIndex = styledText.length();

            parseStyle(styledText, node);

            styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length()));
        } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_sup.equalsIgnoreCase(node.getNodeName())) {
            Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>();
            styleAttrs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER);

            int startIndex = styledText.length();

            parseStyle(styledText, node);

            styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length()));
        } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_sub.equalsIgnoreCase(node.getNodeName())) {
            Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>();
            styleAttrs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB);

            int startIndex = styledText.length();

            parseStyle(styledText, node);

            styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length()));
        } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_font.equalsIgnoreCase(node.getNodeName())) {
            NamedNodeMap nodeAttrs = node.getAttributes();

            Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>();

            if (nodeAttrs.getNamedItem(ATTRIBUTE_size) != null) {
                styleAttrs.put(TextAttribute.SIZE,
                        Float.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_size).getNodeValue()));
            }

            if (nodeAttrs.getNamedItem(ATTRIBUTE_color) != null) {
                Color color = JRColorUtil.getColor(nodeAttrs.getNamedItem(ATTRIBUTE_color).getNodeValue(),
                        Color.black);
                styleAttrs.put(TextAttribute.FOREGROUND, color);
            }

            if (nodeAttrs.getNamedItem(ATTRIBUTE_fontFace) != null) {
                String fontFaces = nodeAttrs.getNamedItem(ATTRIBUTE_fontFace).getNodeValue();

                StringTokenizer t = new StringTokenizer(fontFaces, ",");
                while (t.hasMoreTokens()) {
                    String face = t.nextToken().trim();
                    if (AVAILABLE_FONT_FACE_NAMES.contains(face)) {
                        styleAttrs.put(TextAttribute.FAMILY, face);
                        break;
                    }
                }
            }

            int startIndex = styledText.length();

            parseStyle(styledText, node);

            styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length()));

        } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_br.equalsIgnoreCase(node.getNodeName())) {
            styledText.append("\n");

            int startIndex = styledText.length();
            resizeRuns(styledText.getRuns(), startIndex, 1);

            parseStyle(styledText, node);
            styledText.addRun(
                    new JRStyledText.Run(new HashMap<Attribute, Object>(), startIndex, styledText.length()));

            if (startIndex < styledText.length()) {
                styledText.append("\n");
                resizeRuns(styledText.getRuns(), startIndex, 1);
            }
        } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_li.equalsIgnoreCase(node.getNodeName())) {
            String tmpText = styledText.getText();
            if (tmpText.length() > 0 && !tmpText.endsWith("\n")) {
                styledText.append("\n");
            }
            styledText.append(" \u2022 ");

            int startIndex = styledText.length();
            resizeRuns(styledText.getRuns(), startIndex, 1);
            parseStyle(styledText, node);
            styledText.addRun(
                    new JRStyledText.Run(new HashMap<Attribute, Object>(), startIndex, styledText.length()));

            // if the text in the next node does not start with a '\n', or 
            // if the next node is not a <li /> one, we have to append a new line
            Node nextNode = node.getNextSibling();
            String textContent = getFirstTextOccurence(nextNode);
            if (nextNode != null && !((nextNode.getNodeType() == Node.ELEMENT_NODE
                    && NODE_li.equalsIgnoreCase(nextNode.getNodeName())
                    || (textContent != null && textContent.startsWith("\n"))))) {
                styledText.append("\n");
                resizeRuns(styledText.getRuns(), startIndex, 1);
            }
        } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_a.equalsIgnoreCase(node.getNodeName())) {
            if (hyperlink == null) {
                NamedNodeMap nodeAttrs = node.getAttributes();

                Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>();

                hyperlink = new JRBasePrintHyperlink();
                hyperlink.setHyperlinkType(HyperlinkTypeEnum.REFERENCE);
                styleAttrs.put(JRTextAttribute.HYPERLINK, hyperlink);

                if (nodeAttrs.getNamedItem(ATTRIBUTE_href) != null) {
                    hyperlink.setHyperlinkReference(nodeAttrs.getNamedItem(ATTRIBUTE_href).getNodeValue());
                }

                if (nodeAttrs.getNamedItem(ATTRIBUTE_type) != null) {
                    hyperlink.setLinkType(nodeAttrs.getNamedItem(ATTRIBUTE_type).getNodeValue());
                }

                if (nodeAttrs.getNamedItem(ATTRIBUTE_target) != null) {
                    hyperlink.setLinkTarget(nodeAttrs.getNamedItem(ATTRIBUTE_target).getNodeValue());
                }

                int startIndex = styledText.length();

                parseStyle(styledText, node);

                styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length()));

                hyperlink = null;
            } else {
                throw new SAXException("Hyperlink <a> tags cannot be nested.");
            }
        } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_param.equalsIgnoreCase(node.getNodeName())) {
            if (hyperlink == null) {
                throw new SAXException("Hyperlink <param> tags must appear inside an <a> tag only.");
            } else {
                NamedNodeMap nodeAttrs = node.getAttributes();

                JRPrintHyperlinkParameter parameter = new JRPrintHyperlinkParameter();

                if (nodeAttrs.getNamedItem(ATTRIBUTE_name) != null) {
                    parameter.setName(nodeAttrs.getNamedItem(ATTRIBUTE_name).getNodeValue());
                }

                if (nodeAttrs.getNamedItem(ATTRIBUTE_valueClass) != null) {
                    parameter.setValueClass(nodeAttrs.getNamedItem(ATTRIBUTE_valueClass).getNodeValue());
                }

                String strValue = node.getTextContent();
                if (strValue != null) {
                    Object value = JRValueStringUtils.deserialize(parameter.getValueClass(), strValue);
                    parameter.setValue(value);
                }

                hyperlink.addHyperlinkParameter(parameter);
            }
        } else if (node.getNodeType() == Node.ELEMENT_NODE) {
            String nodeName = "<" + node.getNodeName() + ">";
            throw new SAXException("Tag " + nodeName + " is not a valid styled text tag.");
        }
    }
}

From source file:net.sf.jasperreports.engine.export.JRXhtmlExporter.java

/**
 *
 */// w  w  w. j a va 2 s .c o m
protected void exportStyledTextRun(Map<Attribute, Object> attributes, String text, String tooltip,
        Locale locale, LineSpacingEnum lineSpacing, Float lineSpacingSize, float lineSpacingFactor,
        Color backcolor) throws IOException {
    boolean isBold = TextAttribute.WEIGHT_BOLD.equals(attributes.get(TextAttribute.WEIGHT));
    boolean isItalic = TextAttribute.POSTURE_OBLIQUE.equals(attributes.get(TextAttribute.POSTURE));

    String fontFamilyAttr = (String) attributes.get(TextAttribute.FAMILY);//FIXMENOW reuse this font lookup code everywhere
    String fontFamily = fontFamilyAttr;

    FontInfo fontInfo = FontUtil.getInstance(jasperReportsContext).getFontInfo(fontFamilyAttr, locale);
    if (fontInfo != null) {
        //fontName found in font extensions
        FontFamily family = fontInfo.getFontFamily();
        String exportFont = family.getExportFont(getExporterKey());
        if (exportFont == null) {
            HtmlResourceHandler fontHandler = getExporterOutput().getFontHandler() == null ? getFontHandler()
                    : getExporterOutput().getFontHandler();
            HtmlResourceHandler resourceHandler = getExporterOutput().getResourceHandler() == null
                    ? getResourceHandler()
                    : getExporterOutput().getResourceHandler();
            if (fontHandler != null && resourceHandler != null) {
                HtmlFont htmlFont = HtmlFont.getInstance(locale, fontInfo, isBold, isItalic);

                if (htmlFont != null) {
                    if (!fontsToProcess.containsKey(htmlFont.getId())) {
                        fontsToProcess.put(htmlFont.getId(), htmlFont);

                        HtmlFontUtil.handleFont(resourceHandler, htmlFont);
                    }

                    fontFamily = htmlFont.getId();
                }
            }
        } else {
            fontFamily = exportFont;
        }
    }

    boolean localHyperlink = false;
    JRPrintHyperlink hyperlink = (JRPrintHyperlink) attributes.get(JRTextAttribute.HYPERLINK);
    if (!hyperlinkStarted && hyperlink != null) {
        startHyperlink(hyperlink);
        localHyperlink = true;
    }

    writer.write("<span style=\"font-family: ");
    writer.write(fontFamily);
    writer.write("; ");

    Color forecolor = (Color) attributes.get(TextAttribute.FOREGROUND);
    if (!hyperlinkStarted || !Color.black.equals(forecolor)) {
        writer.write("color: ");
        writer.write(JRColorUtil.getCssColor(forecolor));
        writer.write("; ");
    }

    Color runBackcolor = (Color) attributes.get(TextAttribute.BACKGROUND);
    if (runBackcolor != null && !runBackcolor.equals(backcolor)) {
        writer.write("background-color: ");
        writer.write(JRColorUtil.getCssColor(runBackcolor));
        writer.write("; ");
    }

    writer.write("font-size: ");
    writer.write(toSizeUnit((Float) attributes.get(TextAttribute.SIZE)));
    writer.write(";");

    switch (lineSpacing) {
    case SINGLE:
    default: {
        if (lineSpacingFactor == 0) {
            writer.write(" line-height: 1; *line-height: normal;");
        } else {
            writer.write(" line-height: " + lineSpacingFactor + ";");
        }
        break;
    }
    case ONE_AND_HALF: {
        if (lineSpacingFactor == 0) {
            writer.write(" line-height: 1.5;");
        } else {
            writer.write(" line-height: " + lineSpacingFactor + ";");
        }
        break;
    }
    case DOUBLE: {
        if (lineSpacingFactor == 0) {
            writer.write(" line-height: 2.0;");
        } else {
            writer.write(" line-height: " + lineSpacingFactor + ";");
        }
        break;
    }
    case PROPORTIONAL: {
        if (lineSpacingSize != null) {
            writer.write(" line-height: " + lineSpacingSize.floatValue() + ";");
        }
        break;
    }
    case AT_LEAST:
    case FIXED: {
        if (lineSpacingSize != null) {
            writer.write(" line-height: " + lineSpacingSize.floatValue() + "px;");
        }
        break;
    }
    }

    /*
    if (!horizontalAlignment.equals(CSS_TEXT_ALIGN_LEFT))
    {
       writer.write(" text-align: ");
       writer.write(horizontalAlignment);
       writer.write(";");
    }
    */

    if (isBold) {
        writer.write(" font-weight: bold;");
    }
    if (isItalic) {
        writer.write(" font-style: italic;");
    }
    if (TextAttribute.UNDERLINE_ON.equals(attributes.get(TextAttribute.UNDERLINE))) {
        writer.write(" text-decoration: underline;");
    }
    if (TextAttribute.STRIKETHROUGH_ON.equals(attributes.get(TextAttribute.STRIKETHROUGH))) {
        writer.write(" text-decoration: line-through;");
    }

    if (TextAttribute.SUPERSCRIPT_SUPER.equals(attributes.get(TextAttribute.SUPERSCRIPT))) {
        writer.write(" vertical-align: super;");
    } else if (TextAttribute.SUPERSCRIPT_SUB.equals(attributes.get(TextAttribute.SUPERSCRIPT))) {
        writer.write(" vertical-align: sub;");
    }

    writer.write("\"");

    if (tooltip != null) {
        writer.write(" title=\"");
        writer.write(JRStringUtil.xmlEncode(tooltip));
        writer.write("\"");
    }

    writer.write(">");

    writer.write(JRStringUtil.htmlEncode(text));

    writer.write("</span>");

    if (localHyperlink) {
        endHyperlink();
    }
}

From source file:net.sf.jasperreports.engine.export.JRRtfExporter.java

/**
 * Draw a text box//from ww  w . java2s .  c om
 * @param text JasperReports text object (JRPrintText)
 * @throws JRException
 */
public void exportText(JRPrintText text) throws IOException, JRException {

    // use styled text
    JRStyledText styledText = getStyledText(text);
    if (styledText == null) {
        return;
    }

    int width = text.getWidth();
    int height = text.getHeight();

    int textHeight = (int) text.getTextHeight();

    if (textHeight <= 0) {
        if (height <= 0) {
            throw new JRException(EXCEPTION_MESSAGE_KEY_INVALID_TEXT_HEIGHT, (Object[]) null);
        }
        textHeight = height;
    }

    /*   */
    startElement(text);

    // padding for the text
    int topPadding = text.getLineBox().getTopPadding();
    int leftPadding = text.getLineBox().getLeftPadding();
    int bottomPadding = text.getLineBox().getBottomPadding();
    int rightPadding = text.getLineBox().getRightPadding();

    String rotation = null;

    switch (text.getRotationValue()) {
    case LEFT: {
        switch (text.getVerticalTextAlign()) {
        case BOTTOM: {
            leftPadding = Math.max(leftPadding, width - rightPadding - textHeight);
            break;
        }
        case MIDDLE: {
            leftPadding = Math.max(leftPadding, (width - rightPadding - textHeight) / 2);
            break;
        }
        case TOP:
        case JUSTIFIED:
        default: {
        }
        }
        rotation = "{\\sp{\\sn txflTextFlow}{\\sv 2}}";
        break;
    }
    case RIGHT: {
        switch (text.getVerticalTextAlign()) {
        case BOTTOM: {
            rightPadding = Math.max(rightPadding, width - leftPadding - textHeight);
            break;
        }
        case MIDDLE: {
            rightPadding = Math.max(rightPadding, (width - leftPadding - textHeight) / 2);
            break;
        }
        case TOP:
        case JUSTIFIED:
        default: {
        }
        }
        rotation = "{\\sp{\\sn txflTextFlow}{\\sv 3}}";
        break;
    }
    case UPSIDE_DOWN: {
        switch (text.getVerticalTextAlign()) {
        case TOP: {
            topPadding = Math.max(topPadding, height - bottomPadding - textHeight);
            break;
        }
        case MIDDLE: {
            topPadding = Math.max(topPadding, (height - bottomPadding - textHeight) / 2);
            break;
        }
        case BOTTOM:
        case JUSTIFIED:
        default: {
        }
        }
        rotation = "";
        break;
    }
    case NONE:
    default: {
        switch (text.getVerticalTextAlign()) {
        case BOTTOM: {
            topPadding = Math.max(topPadding, height - bottomPadding - textHeight);
            break;
        }
        case MIDDLE: {
            topPadding = Math.max(topPadding, (height - bottomPadding - textHeight) / 2);
            break;
        }
        case TOP:
        case JUSTIFIED:
        default: {
        }
        }
        rotation = "";
    }
    }

    contentWriter.write(rotation);
    contentWriter.write("{\\sp{\\sn dyTextTop}{\\sv ");
    contentWriter.write(String.valueOf(LengthUtil.emu(topPadding)));
    contentWriter.write("}}");
    contentWriter.write("{\\sp{\\sn dxTextLeft}{\\sv ");
    contentWriter.write(String.valueOf(LengthUtil.emu(leftPadding)));
    contentWriter.write("}}");
    contentWriter.write("{\\sp{\\sn dyTextBottom}{\\sv ");
    contentWriter.write(String.valueOf(LengthUtil.emu(bottomPadding)));
    contentWriter.write("}}");
    contentWriter.write("{\\sp{\\sn dxTextRight}{\\sv ");
    contentWriter.write(String.valueOf(LengthUtil.emu(rightPadding)));
    contentWriter.write("}}");
    contentWriter.write("{\\sp{\\sn fLine}{\\sv 0}}");
    contentWriter.write("{\\shptxt{\\pard ");

    contentWriter.write("\\fi" + LengthUtil.twip(text.getParagraph().getFirstLineIndent()) + " ");
    contentWriter.write("\\li" + LengthUtil.twip(text.getParagraph().getLeftIndent()) + " ");
    contentWriter.write("\\ri" + LengthUtil.twip(text.getParagraph().getRightIndent()) + " ");
    contentWriter.write("\\sb" + LengthUtil.twip(text.getParagraph().getSpacingBefore()) + " ");
    contentWriter.write("\\sa" + LengthUtil.twip(text.getParagraph().getSpacingAfter()) + " ");

    TabStop[] tabStops = text.getParagraph().getTabStops();
    if (tabStops != null && tabStops.length > 0) {
        for (int i = 0; i < tabStops.length; i++) {
            TabStop tabStop = tabStops[i];

            String tabStopAlign = "";

            switch (tabStop.getAlignment()) {
            case CENTER:
                tabStopAlign = "\\tqc";
                break;
            case RIGHT:
                tabStopAlign = "\\tqr";
                break;
            case LEFT:
            default:
                tabStopAlign = "";
                break;
            }

            contentWriter.write(tabStopAlign + "\\tx" + LengthUtil.twip(tabStop.getPosition()) + " ");
        }
    }

    //      JRFont font = text;
    if (text.getRunDirectionValue() == RunDirectionEnum.RTL) {
        contentWriter.write("\\rtlch");
    }
    //      writer.write("\\f");
    //      writer.write(String.valueOf(getFontIndex(font)));
    //      writer.write("\\cf");
    //      writer.write(String.valueOf(getColorIndex(text.getForecolor())));
    contentWriter.write("\\cb");
    contentWriter.write(String.valueOf(getColorIndex(text.getBackcolor())));
    contentWriter.write(" ");

    //      if (font.isBold())
    //         writer.write("\\b");
    //      if (font.isItalic())
    //         writer.write("\\i");
    //      if (font.isStrikeThrough())
    //         writer.write("\\strike");
    //      if (font.isUnderline())
    //         writer.write("\\ul");
    //      writer.write("\\fs");
    //      writer.write(String.valueOf(font.getFontSize() * 2));

    switch (text.getHorizontalTextAlign()) {
    case LEFT:
        contentWriter.write("\\ql");
        break;
    case CENTER:
        contentWriter.write("\\qc");
        break;
    case RIGHT:
        contentWriter.write("\\qr");
        break;
    case JUSTIFIED:
        contentWriter.write("\\qj");
        break;
    default:
        contentWriter.write("\\ql");
        break;
    }

    switch (text.getParagraph().getLineSpacing()) {
    case AT_LEAST: {
        contentWriter.write("\\sl" + LengthUtil.twip(text.getParagraph().getLineSpacingSize()));
        contentWriter.write(" \\slmult0 ");
        break;
    }
    case FIXED: {
        contentWriter.write("\\sl-" + LengthUtil.twip(text.getParagraph().getLineSpacingSize()));
        contentWriter.write(" \\slmult0 ");
        break;
    }
    case PROPORTIONAL: {
        contentWriter.write("\\sl" + (int) (text.getParagraph().getLineSpacingSize() * LINE_SPACING_FACTOR));
        contentWriter.write(" \\slmult1 ");
        break;
    }
    case DOUBLE: {
        contentWriter.write("\\sl" + (int) (2f * LINE_SPACING_FACTOR));
        contentWriter.write(" \\slmult1 ");
        break;
    }
    case ONE_AND_HALF: {
        contentWriter.write("\\sl" + (int) (1.5f * LINE_SPACING_FACTOR));
        contentWriter.write(" \\slmult1 ");
        break;
    }
    case SINGLE:
    default: {
        contentWriter.write("\\sl" + (int) (1f * LINE_SPACING_FACTOR));
        contentWriter.write(" \\slmult1 ");
        break;
    }
    }

    if (text.getAnchorName() != null) {
        writeAnchor(text.getAnchorName());
    }

    boolean startedHyperlink = exportHyperlink(text);

    // add parameters in case of styled text element
    String plainText = styledText.getText();
    int runLimit = 0;

    AttributedCharacterIterator iterator = styledText.getAttributedString().getIterator();
    while (runLimit < styledText.length() && (runLimit = iterator.getRunLimit()) <= styledText.length()) {

        Map<Attribute, Object> styledTextAttributes = iterator.getAttributes();
        JRFont styleFont = new JRBaseFont(styledTextAttributes);
        Color styleForeground = (Color) styledTextAttributes.get(TextAttribute.FOREGROUND);
        Color styleBackground = (Color) styledTextAttributes.get(TextAttribute.BACKGROUND);

        contentWriter.write("\\f");
        contentWriter.write(String.valueOf(getFontIndex(styleFont, getTextLocale(text))));
        contentWriter.write("\\fs");
        contentWriter.write(String.valueOf((int) (2 * styleFont.getFontsize())));

        if (styleFont.isBold()) {
            contentWriter.write("\\b");
        }
        if (styleFont.isItalic()) {
            contentWriter.write("\\i");
        }
        if (styleFont.isUnderline()) {
            contentWriter.write("\\ul");
        }
        if (styleFont.isStrikeThrough()) {
            contentWriter.write("\\strike");
        }

        if (TextAttribute.SUPERSCRIPT_SUPER.equals(styledTextAttributes.get(TextAttribute.SUPERSCRIPT))) {
            contentWriter.write("\\super");
        } else if (TextAttribute.SUPERSCRIPT_SUB.equals(styledTextAttributes.get(TextAttribute.SUPERSCRIPT))) {
            contentWriter.write("\\sub");
        }

        if (!(null == styleBackground || styleBackground.equals(text.getBackcolor()))) {
            contentWriter.write("\\highlight");
            contentWriter.write(String.valueOf(getColorIndex(styleBackground)));
        }
        contentWriter.write("\\cf");
        contentWriter.write(String.valueOf(getColorIndex(styleForeground)));
        contentWriter.write(" ");

        contentWriter.write(handleUnicodeText(plainText.substring(iterator.getIndex(), runLimit)));

        // reset all styles in the paragraph
        contentWriter.write("\\plain");

        iterator.setIndex(runLimit);
    }

    endHyperlink(startedHyperlink);

    contentWriter.write("\\par}}");

    /*   */
    finishElement();

    exportBox(text.getLineBox(), text.getX() + getOffsetX(), text.getY() + getOffsetY(), width, height);
}

From source file:net.sf.jasperreports.engine.export.ooxml.JRDocxExporter.java

/**
 *
 *//*  w  ww  . j a  v  a  2 s.  c  o m*/
protected void exportStyledText(JRStyle style, JRStyledText styledText, Locale locale, boolean hiddenText,
        boolean startedHyperlink, boolean isNewLineJustified) {
    Color elementBackcolor = null;
    Map<AttributedCharacterIterator.Attribute, Object> globalAttributes = styledText.getGlobalAttributes();
    if (globalAttributes != null) {
        elementBackcolor = (Color) styledText.getGlobalAttributes().get(TextAttribute.BACKGROUND);
    }

    String text = styledText.getText();

    int runLimit = 0;

    AttributedCharacterIterator iterator = styledText.getAttributedString().getIterator();

    while (runLimit < styledText.length() && (runLimit = iterator.getRunLimit()) <= styledText.length()) {
        Map<Attribute, Object> attributes = iterator.getAttributes();

        boolean localHyperlink = false;

        if (!startedHyperlink) {
            JRPrintHyperlink hyperlink = (JRPrintHyperlink) attributes.get(JRTextAttribute.HYPERLINK);
            if (hyperlink != null) {
                localHyperlink = startHyperlink(hyperlink, true);
            }
        }

        runHelper.export(style, iterator.getAttributes(), text.substring(iterator.getIndex(), runLimit), locale,
                hiddenText, invalidCharReplacement, elementBackcolor, isNewLineJustified);

        if (localHyperlink) {
            endHyperlink(true);
        }

        iterator.setIndex(runLimit);
    }
}

From source file:net.sf.jasperreports.engine.export.JRHtmlExporter.java

/**
 *
 *///from  w  ww  . j a v  a  2  s.  c  om
protected void exportStyledTextRun(Map<Attribute, Object> attributes, String text, String tooltip,
        Locale locale, LineSpacingEnum lineSpacing, Float lineSpacingSize, float lineSpacingFactor,
        Color backcolor) throws IOException {
    boolean isBold = TextAttribute.WEIGHT_BOLD.equals(attributes.get(TextAttribute.WEIGHT));
    boolean isItalic = TextAttribute.POSTURE_OBLIQUE.equals(attributes.get(TextAttribute.POSTURE));

    String fontFamilyAttr = (String) attributes.get(TextAttribute.FAMILY);
    String fontFamily = fontFamilyAttr;

    FontInfo fontInfo = FontUtil.getInstance(jasperReportsContext).getFontInfo(fontFamilyAttr, locale);
    if (fontInfo != null) {
        //fontName found in font extensions
        FontFamily family = fontInfo.getFontFamily();
        String exportFont = family.getExportFont(getExporterKey());
        if (exportFont == null) {
            HtmlResourceHandler fontHandler = getExporterOutput().getFontHandler() == null ? getFontHandler()
                    : getExporterOutput().getFontHandler();
            HtmlResourceHandler resourceHandler = getExporterOutput().getResourceHandler() == null
                    ? getResourceHandler()
                    : getExporterOutput().getResourceHandler();
            if (fontHandler != null && resourceHandler != null) {
                HtmlFont htmlFont = HtmlFont.getInstance(locale, fontInfo, isBold, isItalic);

                if (htmlFont != null) {
                    if (!fontsToProcess.containsKey(htmlFont.getId())) {
                        fontsToProcess.put(htmlFont.getId(), htmlFont);

                        HtmlFontUtil.handleFont(resourceHandler, htmlFont);
                    }

                    fontFamily = htmlFont.getId();
                }
            }
        } else {
            fontFamily = exportFont;
        }
    }

    boolean localHyperlink = false;
    JRPrintHyperlink hyperlink = (JRPrintHyperlink) attributes.get(JRTextAttribute.HYPERLINK);
    if (!hyperlinkStarted && hyperlink != null) {
        startHyperlink(hyperlink);
        localHyperlink = true;
    }

    writer.write("<span style=\"font-family: ");
    writer.write(fontFamily);
    writer.write("; ");

    Color forecolor = (Color) attributes.get(TextAttribute.FOREGROUND);
    if (!hyperlinkStarted || !Color.black.equals(forecolor)) {
        writer.write("color: ");
        writer.write(JRColorUtil.getCssColor(forecolor));
        writer.write("; ");
    }

    Color runBackcolor = (Color) attributes.get(TextAttribute.BACKGROUND);
    if (runBackcolor != null && !runBackcolor.equals(backcolor)) {
        writer.write("background-color: ");
        writer.write(JRColorUtil.getCssColor(runBackcolor));
        writer.write("; ");
    }

    writer.write("font-size: ");
    writer.write(toSizeUnit((Float) attributes.get(TextAttribute.SIZE)));
    writer.write(";");

    switch (lineSpacing) {
    case SINGLE:
    default: {
        if (lineSpacingFactor == 0) {
            writer.write(" line-height: 1; *line-height: normal;");
        } else {
            writer.write(" line-height: " + lineSpacingFactor + ";");
        }
        break;
    }
    case ONE_AND_HALF: {
        if (lineSpacingFactor == 0) {
            writer.write(" line-height: 1.5;");
        } else {
            writer.write(" line-height: " + lineSpacingFactor + ";");
        }
        break;
    }
    case DOUBLE: {
        if (lineSpacingFactor == 0) {
            writer.write(" line-height: 2.0;");
        } else {
            writer.write(" line-height: " + lineSpacingFactor + ";");
        }
        break;
    }
    case PROPORTIONAL: {
        if (lineSpacingSize != null) {
            writer.write(" line-height: " + lineSpacingSize.floatValue() + ";");
        }
        break;
    }
    case AT_LEAST:
    case FIXED: {
        if (lineSpacingSize != null) {
            writer.write(" line-height: " + lineSpacingSize.floatValue() + "px;");
        }
        break;
    }
    }

    /*
    if (!horizontalAlignment.equals(CSS_TEXT_ALIGN_LEFT))
    {
       writer.write(" text-align: ");
       writer.write(horizontalAlignment);
       writer.write(";");
    }
    */

    if (isBold) {
        writer.write(" font-weight: bold;");
    }
    if (isItalic) {
        writer.write(" font-style: italic;");
    }
    if (TextAttribute.UNDERLINE_ON.equals(attributes.get(TextAttribute.UNDERLINE))) {
        writer.write(" text-decoration: underline;");
    }
    if (TextAttribute.STRIKETHROUGH_ON.equals(attributes.get(TextAttribute.STRIKETHROUGH))) {
        writer.write(" text-decoration: line-through;");
    }

    if (TextAttribute.SUPERSCRIPT_SUPER.equals(attributes.get(TextAttribute.SUPERSCRIPT))) {
        writer.write(" vertical-align: super;");
    } else if (TextAttribute.SUPERSCRIPT_SUB.equals(attributes.get(TextAttribute.SUPERSCRIPT))) {
        writer.write(" vertical-align: sub;");
    }

    writer.write("\"");

    if (tooltip != null) {
        writer.write(" title=\"");
        writer.write(JRStringUtil.xmlEncode(tooltip));
        writer.write("\"");
    }

    writer.write(">");

    writer.write(JRStringUtil.htmlEncode(text));

    writer.write("</span>");

    if (localHyperlink) {
        endHyperlink();
    }
}