Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /* ====================================================================
     Licensed to the Apache Software Foundation (ASF) under one or more
     contributor license agreements.  See the NOTICE file distributed with
     this work for additional information regarding copyright ownership.
     The ASF licenses this file to You under the Apache License, Version 2.0
     (the "License"); you may not use this file except in compliance with
     the License.  You may obtain a copy of the License at
  
         http://www.apache.org/licenses/LICENSE-2.0
 
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 ==================================================================== */
 
 package org.apache.poi.hslf.model;
 
 import java.awt.Font;
 
A common superclass of all shapes that can hold text.

Author(s):
Yegor Kozlov
 
 public abstract class TextShape extends SimpleShape {

    
How to anchor the text
 
     public static final int AnchorTop = 0;
     public static final int AnchorMiddle = 1;
     public static final int AnchorBottom = 2;
     public static final int AnchorTopCentered = 3;
     public static final int AnchorMiddleCentered = 4;
     public static final int AnchorBottomCentered = 5;
     public static final int AnchorTopBaseline = 6;
     public static final int AnchorBottomBaseline = 7;
     public static final int AnchorTopCenteredBaseline = 8;
     public static final int AnchorBottomCenteredBaseline = 9;

    
How to wrap the text
 
     public static final int WrapSquare = 0;
     public static final int WrapByPoints = 1;
     public static final int WrapNone = 2;
     public static final int WrapTopBottom = 3;
     public static final int WrapThrough = 4;

    
How to align the text
 
     public static final int AlignLeft = 0;
     public static final int AlignCenter = 1;
     public static final int AlignRight = 2;
     public static final int AlignJustify = 3;

    
TextRun object which holds actual text and format data
 
     protected TextRun _txtrun;

    
Escher container which holds text attributes such as TextHeaderAtom, TextBytesAtom ot TextCharsAtom, StyleTextPropAtom etc.
 
     protected EscherTextboxWrapper _txtbox;

    
Used to calculate text bounds
    protected static final FontRenderContext _frc = new FontRenderContext(nulltruetrue);

    
Create a TextBox object and initialize it from the supplied Record container.

Parameters:
escherRecord EscherSpContainer container which holds information about this shape
parent the parent of the shape
   protected TextShape(EscherContainerRecord escherRecordShape parent){
        super(escherRecordparent);
    }

    
Create a new TextBox. This constructor is used when a new shape is created.

Parameters:
parent the parent of this Shape. For example, if this text box is a cell in a table then the parent is Table.
    public TextShape(Shape parent){
        super(nullparent);
         = createSpContainer(parent instanceof ShapeGroup);
    }

    
Create a new TextBox. This constructor is used when a new shape is created.
    public TextShape(){
        this(null);
    }
    public TextRun createTextRun(){
         = getEscherTextboxWrapper();
        if( == null = new EscherTextboxWrapper();
         = getTextRun();
        if( == null){
            TextHeaderAtom tha = new TextHeaderAtom();
            tha.setParentRecord();
            .appendChildRecord(tha);
            TextCharsAtom tca = new TextCharsAtom();
            .appendChildRecord(tca);
            StyleTextPropAtom sta = new StyleTextPropAtom(0);
            .appendChildRecord(sta);
             = new TextRun(tha,tca,sta);
            . = new Record[]{thatcasta};
            .setText("");
            setDefaultTextProperties();
        }
        return ;
    }

    
Set default properties for the TextRun. Depending on the text and shape type the defaults are different: TextBox: align=left, valign=top AutoShape: align=center, valign=middle
    protected void setDefaultTextProperties(TextRun _txtrun){
    }

    
Returns the text contained in this text frame.

Returns:
the text string for this textbox.
     public String getText(){
        TextRun tx = getTextRun();
        return tx == null ? null : tx.getText();
    }

    
Sets the text contained in this text frame.

Parameters:
text the text string used by this object.
    public void setText(String text){
        TextRun tx = getTextRun();
        if(tx == null){
            tx = createTextRun();
        }
        tx.setText(text);
        setTextId(text.hashCode());
    }

    
When a textbox is added to a sheet we need to tell upper-level PPDrawing about it.

Parameters:
sh the sheet we are adding to
    protected void afterInsert(Sheet sh){
        super.afterInsert(sh);
        EscherTextboxWrapper _txtbox = getEscherTextboxWrapper();
        if(_txtbox != null){
            PPDrawing ppdrawing = sh.getPPDrawing();
            ppdrawing.addTextboxWrapper(_txtbox);
            // Ensure the escher layer knows about the added records
            try {
                _txtbox.writeOut(null);
            } catch (IOException e){
                throw new HSLFException(e);
            }
            if(getAnchor().equals(new Rectangle()) && !"".equals(getText())) resizeToFitText();
        }
        if( != null) {
            .setShapeId(getShapeId());
            sh.onAddTextShape(this);
        }
    }
        if( == null){
            if(textRecord != null = new EscherTextboxWrapper(textRecord);
        }
        return ;
    }
    
Adjust the size of the TextShape so it encompasses the text inside it.

Returns:
a Rectangle2D that is the bounds of this TextShape.
    public Rectangle2D resizeToFitText(){
        String txt = getText();
        if(txt == null || txt.length() == 0) return new Rectangle2D.Float();
        RichTextRun rt = getTextRun().getRichTextRuns()[0];
        int size = rt.getFontSize();
        int style = 0;
        if (rt.isBold()) style |= .;
        if (rt.isItalic()) style |= .;
        String fntname = rt.getFontName();
        Font font = new Font(fntnamestylesize);
        float width = 0, height = 0, leading = 0;
        String[] lines = txt.split("\n");
        for (int i = 0; i < lines.lengthi++) {
            if(lines[i].length() == 0) continue;
            TextLayout layout = new TextLayout(lines[i], font);
            leading = Math.max(leadinglayout.getLeading());
            width = Math.max(widthlayout.getAdvance());
            height = Math.max(height, (height + (layout.getDescent() + layout.getAscent())));
        }
        // add one character to width
        Rectangle2D charBounds = font.getMaxCharBounds();
        width += getMarginLeft() + getMarginRight() + charBounds.getWidth();
        // add leading to height
        height += getMarginTop() + getMarginBottom() + leading;
        Rectangle2D anchor = getAnchor2D();
        anchor.setRect(anchor.getX(), anchor.getY(), widthheight);
        setAnchor(anchor);
        return anchor;
    }

    
Returns the type of vertical alignment for the text. One of the Anchor* constants defined in this class.

Returns:
the type of alignment
    public int getVerticalAlignment(){
        int valign = .;
        if (prop == null){
            
If vertical alignment was not found in the shape properties then try to fetch the master shape and search for the align property there.
            int type = getTextRun().getRunType();
            MasterSheet master = getSheet().getMasterSheet();
            if(master != null){
                TextShape masterShape = master.getPlaceholderByTextType(type);
                if(masterShape != nullvalign = masterShape.getVerticalAlignment();
            } else {
                //not found in the master sheet. Use the hardcoded defaults.
                switch (type){
                     case .:
                     case .:
                         valign = .;
                         break;
                     default:
                         valign = .;
                         break;
                 }
            }
        } else {
            valign = prop.getPropertyValue();
        }
        return valign;
    }

    
Sets the type of vertical alignment for the text. One of the Anchor* constants defined in this class.

Parameters:
align - the type of alignment
    public void setVerticalAlignment(int align){
    }

    
Sets the type of horizontal alignment for the text. One of the Align* constants defined in this class.

Parameters:
align - the type of horizontal alignment
    public void setHorizontalAlignment(int align){
        TextRun tx = getTextRun();
        if(tx != nulltx.getRichTextRuns()[0].setAlignment(align);
    }

    
Gets the type of horizontal alignment for the text. One of the Align* constants defined in this class.

Returns:
align - the type of horizontal alignment
    public int getHorizontalAlignment(){
        TextRun tx = getTextRun();
        return tx == null ? -1 : tx.getRichTextRuns()[0].getAlignment();
    }

    
Returns the distance (in points) between the bottom of the text frame and the bottom of the inscribed rectangle of the shape that contains the text. Default value is 1/20 inch.

Returns:
the botom margin
    public float getMarginBottom(){
        int val = prop == null ? /20 : prop.getPropertyValue();
        return (float)val/;
    }

    
Sets the botom margin.

Parameters:
margin the bottom margin
See also:
getMarginBottom()
    public void setMarginBottom(float margin){
    }

    
Returns the distance (in points) between the left edge of the text frame and the left edge of the inscribed rectangle of the shape that contains the text. Default value is 1/10 inch.

Returns:
the left margin
    public float getMarginLeft(){
        int val = prop == null ? /10 : prop.getPropertyValue();
        return (float)val/;
    }

    
Sets the left margin.

Parameters:
margin the left margin
See also:
getMarginLeft()
    public void setMarginLeft(float margin){
    }

    
Returns the distance (in points) between the right edge of the text frame and the right edge of the inscribed rectangle of the shape that contains the text. Default value is 1/10 inch.

Returns:
the right margin
    public float getMarginRight(){
        int val = prop == null ? /10 : prop.getPropertyValue();
        return (float)val/;
    }

    
Sets the right margin.

Parameters:
margin the right margin
See also:
getMarginRight()
    public void setMarginRight(float margin){
    }

     
Returns the distance (in points) between the top of the text frame and the top of the inscribed rectangle of the shape that contains the text. Default value is 1/20 inch.

Returns:
the top margin
    public float getMarginTop(){
        int val = prop == null ? /20 : prop.getPropertyValue();
        return (float)val/;
    }

   
Sets the top margin.

Parameters:
margin the top margin
See also:
getMarginTop()
    public void setMarginTop(float margin){
    }


    
Returns the value indicating word wrap.

Returns:
the value indicating word wrap. Must be one of the Wrap* constants defined in this class.
    public int getWordWrap(){
        return prop == null ?  : prop.getPropertyValue();
    }

    
Specifies how the text should be wrapped

Parameters:
wrap the value indicating how the text should be wrapped. Must be one of the Wrap* constants defined in this class.
    public void setWordWrap(int wrap){
    }

    

Returns:
id for the text.
    public int getTextId(){
        return prop == null ? 0 : prop.getPropertyValue();
    }

    
Sets text ID

Parameters:
id of the text
    public void setTextId(int id){
    }

    

Returns:
the TextRun object for this text box
    public TextRun getTextRun(){
       if (null == this.initTextRun();
       if (null == this. && null != this.) {
          TextHeaderAtom    tha = null
          TextBytesAtom     tba = null;
          TextCharsAtom     tca = null;
          StyleTextPropAtom sta = null;
          Record[] childRecords = this..getChildRecords();
          for (Record r : childRecords) {
             if (r instanceof TextHeaderAtom) {
                tha = (TextHeaderAtomr;
             } else if (r instanceof TextBytesAtom) {
                tba = (TextBytesAtomr;
             } else if (r instanceof TextCharsAtom) {
                tca = (TextCharsAtomr;
             } else if (r instanceof StyleTextPropAtom) {
                sta = (StyleTextPropAtomr;
             }
          }
          if (tba != null) {
             this. = new TextRun(thatbasta);
          } else if (tca != null) {
             this. = new TextRun(thatcasta);
          }
       }
       return ;
    }
    public void setSheet(Sheet sheet) {
         = sheet;
        // Initialize _txtrun object.
        // (We can't do it in the constructor because the sheet
        //  is not assigned then, it's only built once we have
        //  all the records)
        TextRun tx = getTextRun();
        if (tx != null) {
            // Supply the sheet to our child RichTextRuns
            tx.setSheet();
            RichTextRun[] rt = tx.getRichTextRuns();
            for (int i = 0; i < rt.lengthi++) {
                rt[i].supplySlideShow(.getSlideShow());
            }
        }
    }
    protected void initTextRun(){
        EscherTextboxWrapper txtbox = getEscherTextboxWrapper();
        Sheet sheet = getSheet();
        if(sheet == null || txtbox == nullreturn;
        OutlineTextRefAtom ota = null;
        Record[] child = txtbox.getChildRecords();
        for (int i = 0; i < child.lengthi++) {
            if (child[iinstanceof OutlineTextRefAtom) {
                ota = (OutlineTextRefAtom)child[i];
                break;
            }
        }
        TextRun[] runs = .getTextRuns();
        if (ota != null) {
            int idx = ota.getTextIndex();
            for (int i = 0; i < runs.lengthi++) {
                if(runs[i].getIndex() == idx){
                     = runs[i];
                    break;
                }
            }
            if( == null) {
                .log(."text run not found for OutlineTextRefAtom.TextIndex=" + idx);
            }
        } else {
            EscherSpRecord escherSpRecord = .getChildById(.);
            int shapeId = escherSpRecord.getShapeId();
            if(runs != nullfor (int i = 0; i < runs.lengthi++) {
                if(runs[i].getShapeId() == shapeId){
                     = runs[i];
                    break;
                }
            }
        }
        // ensure the same references child records of TextRun
        if( != nullfor (int i = 0; i < child.lengthi++) {
            for (Record r : .getRecords()) {
                if (child[i].getRecordType() == r.getRecordType()) {
                    child[i] = r;
                }
            }
        }
    }
    public void draw(Graphics2D graphics){
        AffineTransform at = graphics.getTransform();
        ShapePainter.paint(thisgraphics);
        new TextPainter(this).paint(graphics);
        graphics.setTransform(at);
    }

    
Return OEPlaceholderAtom, the atom that describes a placeholder.

Returns:
OEPlaceholderAtom or null if not found
    }

    
Assigns a hyperlink to this text shape

Parameters:
linkId id of the hyperlink, @see org.apache.poi.hslf.usermodel.SlideShow#addHyperlink(Hyperlink)
beginIndex the beginning index, inclusive.
endIndex the ending index, exclusive.
See also:
org.apache.poi.hslf.usermodel.SlideShow.addHyperlink(org.apache.poi.hslf.model.Hyperlink)
    public void setHyperlink(int linkIdint beginIndexint endIndex){
        //TODO validate beginIndex and endIndex and throw IllegalArgumentException
        InteractiveInfo info = new InteractiveInfo();
        InteractiveInfoAtom infoAtom = info.getInteractiveInfoAtom();
        infoAtom.setHyperlinkID(linkId);
        .appendChildRecord(info);
        TxInteractiveInfoAtom txiatom = new TxInteractiveInfoAtom();
        txiatom.setStartIndex(beginIndex);
        txiatom.setEndIndex(endIndex);
        .appendChildRecord(txiatom);
    }
New to GrepCode? Check out our FAQ X