Package java.text

Examples of java.text.AttributedString$AttributedStringIterator


                                                      Map m,
                                                      int[] indexMap,
                                                      boolean preserve,
                                                      boolean stripfirst,
                                                      boolean striplast) {
        AttributedString as = null;
        StringBuffer sb = new StringBuffer();
        if (preserve) {
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                switch (c) {
                case 10:
                case 13:
                case '\t':
                    sb.append(' ');
                    break;
                default:
                    sb.append(c);
                }
                indexMap[i] = i;
            }
        } else {
            boolean space = false;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                switch (c) {
                case 10:
                case 13:
                    break; // should break, newlines are not whitespace
                case ' ':
                case '\t':
                    if (!space) {
                        sb.append(' ');
                        indexMap[sb.length()-1] = i;
                        space = true;
                    }
                    break;
                default:
                    sb.append(c);
                    indexMap[sb.length()-1] = i;
                    space = false;
                }
            }
            if (stripfirst) {
                while (sb.length() > 0) {
                    if (sb.charAt(0) == ' ') {
                        sb.deleteCharAt(0);
                        System.arraycopy(indexMap, 1, indexMap, 0, sb.length());
                    } else {
                        break;
                    }
                }
            }
            if (striplast) {
                int len;
                while ((len = sb.length()) > 0) {
                    if (sb.charAt(len - 1) == ' ') {
                        sb.deleteCharAt(len - 1);
                    } else {
                        break;
                    }
                }
            }
            for (int i=sb.length(); i<indexMap.length; ++i) {
                indexMap[i] = -1;
            }
        }
        if (sb.length() > 0) {
            as = new AttributedString(sb.toString(), m);
        } else if (stripfirst && striplast) {
            as = new AttributedString(" ", m);
        }
        return as;
    }
View Full Code Here


         } catch (Exception e) {
                       fail("Unexpected exception: " + e);
         }
       }
       public void testBidiConstructor_Iterator() {
               AttributedString paragraph = new AttributedString("text");
         bd = new Bidi(paragraph.getIterator());
         try {
             assertTrue(4 == bd.getRunLimit(1));
         } catch (Exception e) {
                       fail("Unexpected exception: " + e);
         }
View Full Code Here

    step.compute(logicalPageBox);

    RenderNode[] elementsByNodeType = MatchFactory.findElementsByNodeType(p, LayoutNodeTypes.TYPE_NODE_COMPLEX_TEXT);
    assertContainsImage(elementsByNodeType);
    RenderableComplexText t = (RenderableComplexText) elementsByNodeType[0];
    AttributedString attributedString = t.getRichText().getAttributedString();
    assertEquals(TextAttribute.RUN_DIRECTION_RTL, attributedString.getIterator().getAttribute(TextAttribute.RUN_DIRECTION));

  }
View Full Code Here

    this.attributedString = createText();
  }

  private AttributedString createText()
  {
    AttributedString str = new AttributedString(text);
    str.addAttribute(TextAttribute.RUN_DIRECTION, TextDirection.RTL.equals(runDirection));
    int startPosition = 0;
    for (final StyledChunk chunk : styleChunks)
    {
      int length = chunk.getText().length();
      int endIndex = startPosition + length;
      str.addAttributes(chunk.getAttributes(), startPosition, endIndex);
      startPosition = endIndex;
    }
    return str;
  }
View Full Code Here

      }
      return -1;
  }

    public static double getColumnWidth(XSSFSheet sheet, int column, boolean useMergedCells){
        AttributedString str;
        TextLayout layout;
        /**
         * Excel measures columns in units of 1/256th of a character width
         * but the docs say nothing about what particular character is used.
         * '0' looks to be a good choice.
         */
        char defaultChar = '0';

        /**
         * This is the multiple that the font height is scaled by when determining the
         * boundary of rotated text.
         */
        double fontHeightMultiple = 2.0;

        FontRenderContext frc = new FontRenderContext(null, true, true);

        XSSFWorkbook wb = sheet.getWorkbook();
        XSSFFont defaultFont = wb.getFontAt((short) 0);

        str = new AttributedString("" + defaultChar);
        copyAttributes(defaultFont, str, 0, 1);
        layout = new TextLayout(str.getIterator(), frc);
        int defaultCharWidth = (int)layout.getAdvance();

        double width = -1;
        rows:
        for (Iterator it = sheet.rowIterator(); it.hasNext();) {
            XSSFRow row = (XSSFRow) it.next();
            XSSFCell cell = row.getCell(column);

            if (cell == null) {
                continue;
            }

            int colspan = 1;
            for (int i = 0 ; i < sheet.getNumMergedRegions(); i++) {
                CellRangeAddress region = sheet.getMergedRegion(i);
                if (containsCell(region, row.getRowNum(), column)) {
                    if (!useMergedCells) {
                        // If we're not using merged cells, skip this one and move on to the next.
                        continue rows;
                    }
                    cell = row.getCell(region.getFirstColumn());
                    colspan = 1 + region.getLastColumn() - region.getFirstColumn();
                }
            }

            XSSFCellStyle style = cell.getCellStyle();
            int cellType = cell.getCellType();
            if(cellType == XSSFCell.CELL_TYPE_FORMULA) cellType = cell.getCachedFormulaResultType();
            XSSFFont font = wb.getFontAt(style.getFontIndex());

            if (cellType == XSSFCell.CELL_TYPE_STRING) {
                XSSFRichTextString rt = cell.getRichStringCellValue();
                String[] lines = rt.getString().split("\\n");
                for (int i = 0; i < lines.length; i++) {
                    String txt = lines[i] + defaultChar;
                    str = new AttributedString(txt);
                    copyAttributes(font, str, 0, txt.length());

                    if (rt.numFormattingRuns() > 0) {
                        int pos = 0;
                        for (int j = 0; j < rt.numFormattingRuns(); j++) {
                            XSSFFont fnt = rt.getFontOfFormattingRun(j);
                            if (fnt != null) {
                                int len = rt.getLengthOfFormattingRun(j);
                                if(len > 0) { //ignore degenerate zero-length runs
                                    copyAttributes(fnt, str, pos, pos + len);
                                    pos += len;
                                }
                            }
                        }
                    }

                    layout = new TextLayout(str.getIterator(), frc);
                    if(style.getRotation() != 0){
                        /*
                         * Transform the text using a scale so that it's height is increased by a multiple of the leading,
                         * and then rotate the text before computing the bounds. The scale results in some whitespace around
                         * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
                         * is added by the standard Excel autosize.
                         */
                        AffineTransform trans = new AffineTransform();
                        trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
                        trans.concatenate(
                        AffineTransform.getScaleInstance(1, fontHeightMultiple)
                        );
                        width = Math.max(width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
                    } else {
                        width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
                    }
                }
            } else {
                String sval = null;
                if (cellType == XSSFCell.CELL_TYPE_NUMERIC) {
                    String dfmt = style.getDataFormatString();
                    String format = dfmt == null ? null : dfmt.replaceAll("\"", "");
                    double value = cell.getNumericCellValue();
                    try {
                        NumberFormat fmt;
                        if ("General".equals(format))
                            sval = "" + value;
                        else
                        {
                            fmt = new DecimalFormat(format);
                            sval = fmt.format(value);
                        }
                    } catch (Exception e) {
                        sval = "" + value;
                    }
                } else if (cellType == XSSFCell.CELL_TYPE_BOOLEAN) {
                    sval = String.valueOf(cell.getBooleanCellValue());
                }
                if(sval != null) {
                    String txt = sval + defaultChar;
                    str = new AttributedString(txt);
                    copyAttributes(font, str, 0, txt.length());

                    layout = new TextLayout(str.getIterator(), frc);
                    if(style.getRotation() != 0){
                        /*
                         * Transform the text using a scale so that it's height is increased by a multiple of the leading,
                         * and then rotate the text before computing the bounds. The scale results in some whitespace around
                         * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
View Full Code Here

        String text = txrun.getText();
        //TODO: properly process tabs
        text = text.replace('\t', ' ');
        text = text.replace((char)160, ' ');

        AttributedString at = new AttributedString(text);
        RichTextRun[] rt = txrun.getRichTextRuns();
        for (int i = 0; i < rt.length; i++) {
            int start = rt[i].getStartIndex();
            int end = rt[i].getEndIndex();
            if(start == end) {
                logger.log(POILogger.INFO,  "Skipping RichTextRun with zero length");
                continue;
            }

            at.addAttribute(TextAttribute.FAMILY, rt[i].getFontName(), start, end);
            at.addAttribute(TextAttribute.SIZE, new Float(rt[i].getFontSize()), start, end);
            at.addAttribute(TextAttribute.FOREGROUND, rt[i].getFontColor(), start, end);
            if(rt[i].isBold()) at.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, start, end);
            if(rt[i].isItalic()) at.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, start, end);
            if(rt[i].isUnderlined()) {
                at.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, start, end);
                at.addAttribute(TextAttribute.INPUT_METHOD_UNDERLINE, TextAttribute.UNDERLINE_LOW_TWO_PIXEL, start, end);
            }
            if(rt[i].isStrikethrough()) at.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON, start, end);
            int superScript = rt[i].getSuperscript();
            if(superScript != 0) at.addAttribute(TextAttribute.SUPERSCRIPT, superScript > 0 ? TextAttribute.SUPERSCRIPT_SUPER : TextAttribute.SUPERSCRIPT_SUB, start, end);

        }
        return at;
    }
View Full Code Here

        if (run == null) return null;

        String text = run.getText();
        if (text == null || text.equals("")) return null;

        AttributedString at = getAttributedString(run);

        AttributedCharacterIterator it = at.getIterator();
        int paragraphStart = it.getBeginIndex();
        int paragraphEnd = it.getEndIndex();

        ArrayList lines = new ArrayList();
        LineBreakMeasurer measurer = new LineBreakMeasurer(it, frc);
        measurer.setPosition(paragraphStart);
        while (measurer.getPosition() < paragraphEnd) {
            int startIndex = measurer.getPosition();
            int nextBreak = text.indexOf('\n', measurer.getPosition() + 1);

            boolean prStart = text.charAt(startIndex) == '\n';
            if(prStart) measurer.setPosition(startIndex++);

            RichTextRun rt = run.getRichTextRunAt(startIndex == text.length() ? (startIndex-1) : startIndex);
            if(rt == null) {
                logger.log(POILogger.WARN,  "RichTextRun not found at pos" + startIndex + "; text.length: " + text.length());
                break;
            }

            float wrappingWidth = textWidth - _shape.getMarginLeft() - _shape.getMarginRight();
            int bulletOffset = rt.getBulletOffset();
            int textOffset = rt.getTextOffset();
            int indent = rt.getIndentLevel();

            TextRulerAtom ruler = run.getTextRuler();
            if(ruler != null) {
                int bullet_val = ruler.getBulletOffsets()[indent]*Shape.POINT_DPI/Shape.MASTER_DPI;
                int text_val = ruler.getTextOffsets()[indent]*Shape.POINT_DPI/Shape.MASTER_DPI;
                if(bullet_val > text_val){
                    int a = bullet_val;
                    bullet_val = text_val;
                    text_val = a;
                }
                if(bullet_val != 0 ) bulletOffset = bullet_val;
                if(text_val != 0) textOffset = text_val;
            }

            if(bulletOffset > 0 || prStart || startIndex == 0) wrappingWidth -= textOffset;

            if (_shape.getWordWrap() == TextShape.WrapNone) {
                wrappingWidth = _shape.getSheet().getSlideShow().getPageSize().width;
            }

            TextLayout textLayout = measurer.nextLayout(wrappingWidth + 1,
                    nextBreak == -1 ? paragraphEnd : nextBreak, true);
            if (textLayout == null) {
                textLayout = measurer.nextLayout(textWidth,
                    nextBreak == -1 ? paragraphEnd : nextBreak, false);
            }
            if(textLayout == null){
                logger.log(POILogger.WARN, "Failed to break text into lines: wrappingWidth: "+wrappingWidth+
                        "; text: " + rt.getText());
                measurer.setPosition(rt.getEndIndex());
                continue;
            }
            int endIndex = measurer.getPosition();

            float lineHeight = (float)textLayout.getBounds().getHeight();
            int linespacing = rt.getLineSpacing();
            if(linespacing == 0) linespacing = 100;

            TextElement el = new TextElement();
            if(linespacing >= 0){
                el.ascent = textLayout.getAscent()*linespacing/100;
            } else {
                el.ascent = -linespacing*Shape.POINT_DPI/Shape.MASTER_DPI;
            }

            el._align = rt.getAlignment();
            el.advance = textLayout.getAdvance();
            el._textOffset = textOffset;
            el._text = new AttributedString(it, startIndex, endIndex);
            el.textStartIndex = startIndex;
            el.textEndIndex = endIndex;

            if (prStart){
                int sp = rt.getSpaceBefore();
                float spaceBefore;
                if(sp >= 0){
                    spaceBefore = lineHeight * sp/100;
                } else {
                    spaceBefore = -sp*Shape.POINT_DPI/Shape.MASTER_DPI;
                }
                el.ascent += spaceBefore;
            }

            float descent;
            if(linespacing >= 0){
                descent = (textLayout.getDescent() + textLayout.getLeading())*linespacing/100;
            } else {
                descent = -linespacing*Shape.POINT_DPI/Shape.MASTER_DPI;
            }
            if (prStart){
                int sp = rt.getSpaceAfter();
                float spaceAfter;
                if(sp >= 0){
                    spaceAfter = lineHeight * sp/100;
                } else {
                    spaceAfter = -sp*Shape.POINT_DPI/Shape.MASTER_DPI;
                }
                el.ascent += spaceAfter;
            }
            el.descent = descent;

            if(rt.isBullet() && (prStart || startIndex == 0)){
                it.setIndex(startIndex);

                AttributedString bat = new AttributedString(Character.toString(rt.getBulletChar()));
                Color clr = rt.getBulletColor();
                if (clr != null) bat.addAttribute(TextAttribute.FOREGROUND, clr);
                else bat.addAttribute(TextAttribute.FOREGROUND, it.getAttribute(TextAttribute.FOREGROUND));

                int fontIdx = rt.getBulletFont();
                if(fontIdx == -1) fontIdx = rt.getFontIndex();
                PPFont bulletFont = _shape.getSheet().getSlideShow().getFont(fontIdx);
                bat.addAttribute(TextAttribute.FAMILY, bulletFont.getFontName());

                int bulletSize = rt.getBulletSize();
                int fontSize = rt.getFontSize();
                if(bulletSize != -1) fontSize = Math.round(fontSize*bulletSize*0.01f);
                bat.addAttribute(TextAttribute.SIZE, new Float(fontSize));

                if(!new Font(bulletFont.getFontName(), Font.PLAIN, 1).canDisplay(rt.getBulletChar())){
                    bat.addAttribute(TextAttribute.FAMILY, "Arial");
                    bat = new AttributedString("" + DEFAULT_BULLET_CHAR, bat.getIterator().getAttributes());
                }

                if(text.substring(startIndex, endIndex).length() > 1){
                    el._bullet = bat;
                    el._bulletOffset = bulletOffset;
View Full Code Here

         * buffer.
         */
        public AttributedString toAttributedString() {
            switch (count) {
            case 0:
                return new AttributedString(" ");
            case 1:
                return new AttributedString((String)strings.get(0),
                                            (Map)attributes.get(0));
            }

            StringBuffer sb = new StringBuffer();
            Iterator it = strings.iterator();
            while (it.hasNext()) {
                sb.append((String)it.next());
            }

            AttributedString result = new AttributedString(sb.toString());

            // Set the attributes

            Iterator sit = strings.iterator();
            Iterator ait = attributes.iterator();
            int idx = 0;
            while (sit.hasNext()) {
                String s = (String)sit.next();
                int nidx = idx + s.length();
                Map m = (Map)ait.next();
                Iterator kit = m.keySet().iterator();
                Iterator vit = m.values().iterator();
                while (kit.hasNext()) {
                    Attribute attr = (Attribute)kit.next();
                    Object val = vit.next();
                    result.addAttribute(attr, val, idx, nidx);
                }
                idx = nidx;
            }

            return result;
View Full Code Here

        case SVGCSSEngine.STROKE_DASHARRAY_INDEX:
        case SVGCSSEngine.STROKE_DASHOFFSET_INDEX:
        case SVGCSSEngine.TEXT_DECORATION_INDEX: {
            if (!hasNewACI) {
                hasNewACI = true;
                AttributedString as =
                    new AttributedString(layoutedText.getIterator());
                TextNode tn = (TextNode)node;
                tn.setAttributedCharacterIterator(as.getIterator());
                TextDecoration textDecoration =
                    getTextDecoration(e, tn, new TextDecoration(), ctx);
                addPaintAttributes(as, e, tn, textDecoration, ctx);
                tn.setAttributedCharacterIterator(as.getIterator());
            }
            break;
        }
        case SVGCSSEngine.TEXT_RENDERING_INDEX: {
            RenderingHints hints = node.getRenderingHints();
View Full Code Here

     * @param element the text element
     */
    protected AttributedString buildAttributedString(BridgeContext ctx,
                                                     Element element) {
        List rgns = getRegions(ctx, element);
        AttributedString ret = getFlowDiv(ctx, element);
        ret.addAttribute(FLOW_REGIONS, rgns, 0, 1);
        return ret;
    }
View Full Code Here

TOP

Related Classes of java.text.AttributedString$AttributedStringIterator

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.