Example usage for org.apache.poi.xslf.usermodel XSLFTextParagraph addNewTextRun

List of usage examples for org.apache.poi.xslf.usermodel XSLFTextParagraph addNewTextRun

Introduction

In this page you can find the example usage for org.apache.poi.xslf.usermodel XSLFTextParagraph addNewTextRun.

Prototype

public XSLFTextRun addNewTextRun() 

Source Link

Document

Add a new run of text

Usage

From source file:Tutorial1.java

License:Apache License

public static void main(String[] args) throws IOException {
    XMLSlideShow ppt = new XMLSlideShow();

    // XSLFSlide#createSlide() with no arguments creates a blank slide
    XSLFSlide blankSlide = ppt.createSlide();

    XSLFSlideMaster master = ppt.getSlideMasters()[0];

    XSLFSlideLayout layout1 = master.getLayout(SlideLayout.TITLE);
    XSLFSlide slide1 = ppt.createSlide(layout1);
    XSLFTextShape[] ph1 = slide1.getPlaceholders();
    XSLFTextShape titlePlaceholder1 = ph1[0];
    titlePlaceholder1.setText("This is a title");
    XSLFTextShape subtitlePlaceholder1 = ph1[1];
    subtitlePlaceholder1.setText("this is a subtitle");

    XSLFSlideLayout layout2 = master.getLayout(SlideLayout.TITLE_AND_CONTENT);
    XSLFSlide slide2 = ppt.createSlide(layout2);
    XSLFTextShape[] ph2 = slide2.getPlaceholders();
    XSLFTextShape titlePlaceholder2 = ph2[0];
    titlePlaceholder2.setText("This is a title");
    XSLFTextShape bodyPlaceholder = ph2[1];
    // we are going to add text by paragraphs. Clear the default placehoder text before that
    bodyPlaceholder.clearText();/*from w  ww. j a  va 2s  .  c  o m*/
    XSLFTextParagraph p1 = bodyPlaceholder.addNewTextParagraph();
    p1.setLevel(0);
    p1.addNewTextRun().setText("Level1 text");
    XSLFTextParagraph p2 = bodyPlaceholder.addNewTextParagraph();
    p2.setLevel(1);
    p2.addNewTextRun().setText("Level2 text");
    XSLFTextParagraph p3 = bodyPlaceholder.addNewTextParagraph();
    p3.setLevel(3);
    p3.addNewTextRun().setText("Level3 text");

    FileOutputStream out = new FileOutputStream("slides.pptx");
    ppt.write(out);
    out.close();
}

From source file:com.hp.autonomy.frontend.reports.powerpoint.PowerPointServiceImpl.java

License:MIT License

/**
 * Internal implementation to add a topic map to a slide.
 * @param slide the slide to add to./*from   w  ww . ja  v a2 s.  c  o  m*/
 * @param anchor bounding rectangle to draw onto, in PowerPoint coordinates.
 * @param data the topic map data.
 */
private static void addTopicMap(final XSLFSlide slide, final Rectangle2D.Double anchor,
        final TopicMapData data) {
    for (final TopicMapData.Path reqPath : data.getPaths()) {
        final XSLFFreeformShape shape = slide.createFreeform();
        final Path2D.Double path = new Path2D.Double();

        boolean first = true;

        for (double[] point : reqPath.getPoints()) {
            final double x = point[0] * anchor.getWidth() + anchor.getMinX();
            final double y = point[1] * anchor.getHeight() + anchor.getMinY();
            if (first) {
                path.moveTo(x, y);
                first = false;
            } else {
                path.lineTo(x, y);
            }
        }
        path.closePath();

        shape.setPath(path);
        shape.setStrokeStyle(2);
        shape.setLineColor(Color.GRAY);
        shape.setHorizontalCentered(true);
        shape.setVerticalAlignment(VerticalAlignment.MIDDLE);
        shape.setTextAutofit(TextShape.TextAutofit.NORMAL);

        final XSLFTextParagraph text = shape.addNewTextParagraph();
        final XSLFTextRun textRun = text.addNewTextRun();
        textRun.setText(reqPath.name);
        textRun.setFontColor(Color.WHITE);
        textRun.setBold(true);

        final CTShape cs = (CTShape) shape.getXmlObject();

        double max = 100, min = 1, scale = 100;
        final CTTextNormalAutofit autoFit = cs.getTxBody().getBodyPr().getNormAutofit();
        final double availHeight = path.getBounds2D().getHeight();
        final int RESIZE_ATTEMPTS = 7;

        for (int attempts = 0; attempts < RESIZE_ATTEMPTS; ++attempts) {
            // PowerPoint doesn't resize the text till you edit it once, which means the text initially looks too
            //   large when you first view the slide; so we binary-chop to get a sensible initial approximation.
            // OpenOffice does the text resize on load so it doesn't have this problem.
            autoFit.setFontScale(Math.max(1, (int) (scale * 1000)));

            final double textHeight = shape.getTextHeight();
            if (textHeight < availHeight) {
                min = scale;
                scale = 0.5 * (min + max);
            } else if (textHeight > availHeight) {
                max = scale;
                scale = 0.5 * (min + max);
            } else {
                break;
            }
        }

        final int opacity = (int) (100000 * reqPath.getOpacity());
        final Color c1 = Color.decode(reqPath.getColor());
        final Color c2 = Color.decode(reqPath.getColor2());

        final CTGradientFillProperties gFill = cs.getSpPr().addNewGradFill();
        gFill.addNewLin().setAng(3300000);
        final CTGradientStopList list = gFill.addNewGsLst();

        final CTGradientStop stop1 = list.addNewGs();
        stop1.setPos(0);
        final CTSRgbColor color1 = stop1.addNewSrgbClr();
        color1.setVal(new byte[] { (byte) c1.getRed(), (byte) c1.getGreen(), (byte) c1.getBlue() });
        color1.addNewAlpha().setVal(opacity);

        final CTGradientStop stop2 = list.addNewGs();
        stop2.setPos(100000);
        final CTSRgbColor color2 = stop2.addNewSrgbClr();
        color2.setVal(new byte[] { (byte) c2.getRed(), (byte) c2.getGreen(), (byte) c2.getBlue() });
        color2.addNewAlpha().setVal(opacity);

        if (reqPath.level > 0) {
            // The nodes which aren't leaf nodes can be clicked on to hide them so you can see the nodes underneath.
            // This only works in PowerPoint; OpenOffice doesn't seem to support it. OpenOffice has its own syntax
            //   to do something similar, but we don't use it since PowerPoint treats it as corrupt.
            final String shapeId = Integer.toString(shape.getShapeId());
            final CTSlide slXML = slide.getXmlObject();

            final CTTimeNodeList childTnLst;
            final CTBuildList bldLst;
            if (!slXML.isSetTiming()) {
                final CTSlideTiming timing = slXML.addNewTiming();
                final CTTLCommonTimeNodeData ctn = timing.addNewTnLst().addNewPar().addNewCTn();
                ctn.setDur("indefinite");
                ctn.setRestart(STTLTimeNodeRestartTypeImpl.NEVER);
                ctn.setNodeType(STTLTimeNodeType.TM_ROOT);
                childTnLst = ctn.addNewChildTnLst();
                bldLst = timing.addNewBldLst();
            } else {
                final CTSlideTiming timing = slXML.getTiming();
                childTnLst = timing.getTnLst().getParArray(0).getCTn().getChildTnLst();
                bldLst = timing.getBldLst();
            }

            final CTTLTimeNodeSequence seq = childTnLst.addNewSeq();
            seq.setConcurrent(true);
            seq.setNextAc(STTLNextActionType.SEEK);
            final CTTLCommonTimeNodeData common = seq.addNewCTn();

            common.setRestart(STTLTimeNodeRestartType.WHEN_NOT_ACTIVE);
            common.setFill(STTLTimeNodeFillType.HOLD);
            common.setEvtFilter("cancelBubble");
            common.setNodeType(STTLTimeNodeType.INTERACTIVE_SEQ);

            final CTTLTimeConditionList condList = common.addNewStCondLst();
            final CTTLTimeCondition cond = condList.addNewCond();
            cond.setEvt(STTLTriggerEvent.ON_CLICK);
            cond.setDelay(0);
            cond.addNewTgtEl().addNewSpTgt().setSpid(shapeId);

            final CTTLTimeCondition endSync = common.addNewEndSync();
            endSync.setEvt(STTLTriggerEvent.END);
            endSync.setDelay(0);
            endSync.addNewRtn().setVal(STTLTriggerRuntimeNode.ALL);

            // These holdCtn* 'hold' transitions with zero delay might seem redundant; but they're exported in the
            //   PowerPoint XML, and the online PowerPoint Office365 viewer won't support the click animations
            //   unless they're present (e.g. from the 'Start Slide Show' button in the browser).
            final CTTLCommonTimeNodeData holdCtn1 = common.addNewChildTnLst().addNewPar().addNewCTn();

            holdCtn1.setFill(STTLTimeNodeFillType.HOLD);
            holdCtn1.addNewStCondLst().addNewCond().setDelay(0);

            final CTTLCommonTimeNodeData holdCtn2 = holdCtn1.addNewChildTnLst().addNewPar().addNewCTn();

            holdCtn2.setFill(STTLTimeNodeFillType.HOLD);
            holdCtn2.addNewStCondLst().addNewCond().setDelay(0);

            final CTTLCommonTimeNodeData clickCtn = holdCtn2.addNewChildTnLst().addNewPar().addNewCTn();

            clickCtn.setPresetID(10);
            clickCtn.setPresetClass(STTLTimeNodePresetClassType.EXIT);
            clickCtn.setPresetSubtype(0);
            clickCtn.setFill(STTLTimeNodeFillType.HOLD);
            clickCtn.setGrpId(0);
            clickCtn.setNodeType(STTLTimeNodeType.CLICK_EFFECT);

            clickCtn.addNewStCondLst().addNewCond().setDelay(0);

            final CTTimeNodeList clickChildTnList = clickCtn.addNewChildTnLst();

            final CTTLAnimateEffectBehavior animEffect = clickChildTnList.addNewAnimEffect();
            animEffect.setTransition(STTLAnimateEffectTransition.OUT);
            animEffect.setFilter("fade");
            final CTTLCommonBehaviorData cBhvr = animEffect.addNewCBhvr();
            final CTTLCommonTimeNodeData bhvrCtn = cBhvr.addNewCTn();

            bhvrCtn.setDur(500);
            cBhvr.addNewTgtEl().addNewSpTgt().setSpid(shapeId);

            final CTTLSetBehavior clickSet = clickChildTnList.addNewSet();
            final CTTLCommonBehaviorData clickSetBhvr = clickSet.addNewCBhvr();
            final CTTLCommonTimeNodeData hideCtn = clickSetBhvr.addNewCTn();

            hideCtn.setDur(1);
            hideCtn.setFill(STTLTimeNodeFillType.HOLD);
            hideCtn.addNewStCondLst().addNewCond().setDelay(499);

            clickSetBhvr.addNewTgtEl().addNewSpTgt().setSpid(shapeId);
            clickSetBhvr.addNewAttrNameLst().addAttrName("style.visibility");
            clickSet.addNewTo().addNewStrVal().setVal("hidden");

            final CTTLBuildParagraph bldP = bldLst.addNewBldP();
            bldP.setSpid(shapeId);
            bldP.setGrpId(0);
            bldP.setAnimBg(true);
        }
    }
}

From source file:com.hp.autonomy.frontend.reports.powerpoint.PowerPointServiceImpl.java

License:MIT License

@Override
public XMLSlideShow map(final MapData map, final String title) throws TemplateLoadException {
    final String image = map.getImage();

    final XMLSlideShow ppt = loadTemplate().getSlideShow();
    final XSLFSlide sl = ppt.createSlide();

    final Rectangle2D.Double pageAnchor = createPageAnchor(ppt);
    final double textHeight;

    if (StringUtils.isNotBlank(title)) {
        textHeight = 0.1 * pageAnchor.getHeight();

        final XSLFTextBox textBox = sl.createTextBox();
        textBox.clearText();//from  w  w w. j a v  a2s . c  o  m
        final XSLFTextParagraph paragraph = textBox.addNewTextParagraph();
        paragraph.setTextAlign(TextParagraph.TextAlign.CENTER);
        paragraph.addNewTextRun().setText(title);
        textBox.setHorizontalCentered(true);
        textBox.setTextAutofit(TextShape.TextAutofit.SHAPE);
        textBox.setAnchor(startingSpace(pageAnchor, textHeight));
    } else {
        textHeight = 0;
    }

    final XSLFPictureData picture = addPictureData(imageSource, ppt, image);
    addMap(sl, remainingSpace(pageAnchor, textHeight), picture, map.getMarkers(), map.getPolygons());

    return ppt;
}

From source file:com.hp.autonomy.frontend.reports.powerpoint.PowerPointServiceImpl.java

License:MIT License

/**
 * Internal implementation to add an image (a world map, though other image data is also fine) to a slide.
 *   Preserves the original image's aspect ratio, leaving blank space below and to the sides of the image.
 * @param slide the slide to add to./*from  w ww.j a  v a2 s  .c  o m*/
 * @param anchor bounding rectangle to draw onto, in PowerPoint coordinates.
 * @param picture the picture data.
 * @param markers an array of markers to draw over the map.
 * @param polygons
 * @return the picture shape object added to the slide.
 */
private static XSLFPictureShape addMap(final XSLFSlide slide, final Rectangle2D.Double anchor,
        final XSLFPictureData picture, final Marker[] markers, final MapData.Polygon[] polygons) {
    double tgtW = anchor.getWidth(), tgtH = anchor.getHeight();

    final Dimension size = picture.getImageDimension();
    final double ratio = size.getWidth() / size.getHeight();

    if (ratio > tgtW / tgtH) {
        // source image is wider than target, clip fixed width variable height
        tgtH = tgtW / ratio;
    } else {
        tgtW = tgtH * ratio;
    }

    final XSLFPictureShape canvas = slide.createPicture(picture);
    // Vertically align top, horizontally-align center
    final double offsetX = anchor.getMinX() + 0.5 * (anchor.getWidth() - tgtW), offsetY = anchor.getMinY();
    canvas.setAnchor(new Rectangle2D.Double(offsetX, offsetY, tgtW, tgtH));

    if (polygons != null) {
        for (MapData.Polygon polygon : polygons) {
            final Color color = Color.decode(polygon.getColor());
            final double[][] shapes = polygon.getPoints();
            // The ESRI spec version 1.2.1 from http://www.opengeospatial.org/standards/sfa has section 6.1.11.1,
            //    which defines polygons as follows:
            /// A Polygon is a planar Surface defined by 1 exterior boundary and 0 or more interior boundaries.
            //    Each interior boundary defines a hole in the Polygon. A Triangle is a polygon with 3 distinct,
            //    non-collinear vertices and no interior boundary.
            /// The exterior boundary LinearRing defines the top? of the surface which is the side of the surface
            //    from which the exterior boundary appears to traverse the boundary in a counter clockwise direction.
            //    The interior LinearRings will have the opposite orientation, and appear as clockwise
            //    when viewed from the top?
            // so it's even-odd winding (whereas the Path2D default is non-zero-winding).
            final Path2D.Double path = new Path2D.Double(Path2D.WIND_EVEN_ODD);

            for (final double[] points : shapes) {
                for (int ii = 0; ii < points.length; ii += 2) {
                    final double x1 = offsetX + points[ii] * tgtW;
                    final double y1 = offsetY + points[ii + 1] * tgtH;
                    if (ii == 0) {
                        path.moveTo(x1, y1);
                    } else {
                        path.lineTo(x1, y1);
                    }
                }
                path.closePath();
            }

            final XSLFFreeformShape freeform = slide.createFreeform();
            freeform.setPath(path);
            freeform.setStrokeStyle(0.5);
            // There's a 0.5 alpha transparency on the stroke, and a 0.2 alpha transparency on the polygon fill.
            freeform.setLineColor(transparentColor(color, 128));
            freeform.setFillColor(transparentColor(color, 51));

            if (StringUtils.isNotEmpty(polygon.getText())) {
                final PackageRelationship rel = freeform.getSheet().getPackagePart().addRelationship(
                        slide.getPackagePart().getPartName(), TargetMode.INTERNAL,
                        XSLFRelation.SLIDE.getRelation());
                // We create a hyperlink which links back to this slide; so we get hover-over-detail-text on the polygon
                final CTHyperlink link = ((CTShape) freeform.getXmlObject()).getNvSpPr().getCNvPr()
                        .addNewHlinkClick();
                link.setTooltip(polygon.getText());
                link.setId(rel.getId());
                link.setAction("ppaction://hlinksldjump");
            }
        }
    }

    for (Marker marker : markers) {
        final Color color = Color.decode(marker.getColor());
        final double centerX = offsetX + marker.getX() * tgtW;
        final double centerY = offsetY + marker.getY() * tgtH;

        if (marker.isCluster()) {
            final XSLFGroupShape group = slide.createGroup();
            double halfMark = 10;
            double mark = halfMark * 2;
            double innerHalfMark = 7;
            double innerMark = innerHalfMark * 2;
            // align these so the middle is the latlng position
            final Rectangle2D.Double groupAnchor = new Rectangle2D.Double(centerX - halfMark,
                    centerY - halfMark, mark, mark);

            group.setAnchor(groupAnchor);
            group.setInteriorAnchor(groupAnchor);

            final XSLFAutoShape shape = group.createAutoShape();
            shape.setShapeType(ShapeType.ELLIPSE);
            final boolean fade = marker.isFade();
            // There's a 0.3 alpha transparency (255 * 0.3 is 76) when a marker is faded out
            final int FADE_ALPHA = 76;
            shape.setFillColor(transparentColor(color, fade ? 47 : 154));
            shape.setAnchor(groupAnchor);

            final XSLFAutoShape inner = group.createAutoShape();
            inner.setFillColor(fade ? transparentColor(color, FADE_ALPHA) : color);
            inner.setLineWidth(0.1);
            inner.setLineColor(new Color((int) (color.getRed() * 0.9), (int) (color.getGreen() * 0.9),
                    (int) (color.getBlue() * 0.9), fade ? FADE_ALPHA : 255));
            inner.setShapeType(ShapeType.ELLIPSE);
            inner.setHorizontalCentered(true);
            inner.setWordWrap(false);
            inner.setVerticalAlignment(VerticalAlignment.MIDDLE);
            inner.clearText();
            final XSLFTextParagraph para = inner.addNewTextParagraph();
            para.setTextAlign(TextParagraph.TextAlign.CENTER);
            final XSLFTextRun text = para.addNewTextRun();
            text.setFontSize(6.0);
            final Color fontColor = Color.decode(StringUtils.defaultString(marker.getFontColor(), "#000000"));
            text.setFontColor(fade ? transparentColor(fontColor, FADE_ALPHA) : fontColor);
            text.setText(marker.getText());
            inner.setAnchor(new Rectangle2D.Double(centerX - innerHalfMark, centerY - innerHalfMark, innerMark,
                    innerMark));
        } else {
            final XSLFGroupShape group = slide.createGroup();

            final XSLFFreeformShape shape = group.createFreeform();
            shape.setHorizontalCentered(true);
            shape.setWordWrap(false);

            shape.setVerticalAlignment(VerticalAlignment.BOTTOM);
            shape.setLineWidth(0.5);
            shape.setLineColor(color.darker());
            shape.setFillColor(transparentColor(color, 210));

            final double halfMark = 8, mark = halfMark * 2, extension = 0.85,
                    markerHeight = (0.5 + extension) * mark, angle = Math.asin(0.5 / extension) * 180 / Math.PI;

            // Set group position
            group.setAnchor(
                    new Rectangle2D.Double(centerX - halfMark, centerY - markerHeight, mark, markerHeight));
            group.setInteriorAnchor(new Rectangle2D.Double(0, 0, mark, markerHeight));

            // Draw a semicircle and a triangle to represent the marker, pointing at the precise x,y location
            final Path2D.Double path = new Path2D.Double();
            path.moveTo(halfMark, markerHeight);
            path.append(new Arc2D.Double(0, 0, mark, mark, -angle, 180 + angle + angle, Arc2D.OPEN), true);
            path.lineTo(halfMark, markerHeight);
            shape.setPath(path);
            shape.setAnchor(new Rectangle2D.Double(0, 0, mark, markerHeight));

            final XSLFAutoShape disc = group.createAutoShape();
            disc.setShapeType(ShapeType.DONUT);
            final double discRadius = 0.25 * mark;
            final double discDiameter = 2 * discRadius;
            disc.setAnchor(new Rectangle2D.Double(halfMark - discRadius, halfMark - discRadius, discDiameter,
                    discDiameter));
            disc.setFillColor(Color.WHITE);
            disc.setLineColor(Color.WHITE);

            if (StringUtils.isNotEmpty(marker.getText())) {
                final PackageRelationship rel = shape.getSheet().getPackagePart().addRelationship(
                        slide.getPackagePart().getPartName(), TargetMode.INTERNAL,
                        XSLFRelation.SLIDE.getRelation());
                // We create a hyperlink which links back to this slide; so we get hover-over-detail-text on the marker
                // Annoyingly, you can't put a link on the group, just on the individual shapes.
                for (XSLFShape clickable : group.getShapes()) {
                    final CTHyperlink link = ((CTShape) clickable.getXmlObject()).getNvSpPr().getCNvPr()
                            .addNewHlinkClick();
                    link.setTooltip(marker.getText());
                    link.setId(rel.getId());
                    link.setAction("ppaction://hlinksldjump");
                }
            }
        }
    }

    return canvas;
}

From source file:com.hp.autonomy.frontend.reports.powerpoint.PowerPointServiceImpl.java

License:MIT License

/**
 * Utility function to create a text run with specified formatting.
 * @param paragraph the paragraph to add to.
 * @param text the text string to add, can contain e.g. '\n' for newlines.
 * @param fontSize font size./*from w w  w  .  jav  a  2 s.  co  m*/
 * @param color font colour.
 * @return the new text run which was added to the paragraph.
 */
private static XSLFTextRun addTextRun(final XSLFTextParagraph paragraph, final String text,
        final double fontSize, final Color color) {
    final XSLFTextRun summary = paragraph.addNewTextRun();
    summary.setFontColor(color);
    summary.setText(text);
    summary.setFontSize(fontSize);
    return summary;
}

From source file:com.hp.autonomy.frontend.reports.powerpoint.PowerPointServiceImpl.java

License:MIT License

/**
 * Utility function to render a TextData object as multiple text runs on the screen in a single text paragraph.
 * Note that newlines are not added automatically; this is so we can support adjacent text with different formatting.
 * @param slide the slide to add to.// ww w .jav  a 2  s.  co m
 * @param anchor bounding rectangle to draw onto, in PowerPoint coordinates.
 * @param data the text data to render.
 */
private void addTextData(final XSLFSlide slide, final Rectangle2D.Double anchor, final TextData data) {
    final XSLFTextBox textBox = slide.createTextBox();
    textBox.setAnchor(anchor);
    textBox.clearText();

    final XSLFTextParagraph para = textBox.addNewTextParagraph();

    for (final TextData.Paragraph runData : data.getText()) {
        final XSLFTextRun run = para.addNewTextRun();
        run.setText(runData.getText());
        run.setFontSize(runData.getFontSize());
        run.setBold(runData.isBold());
        run.setItalic(runData.isItalic());
        run.setFontColor(Color.decode(runData.getColor()));

        if (textBox.getTextHeight() > anchor.getHeight()) {
            // Try removing words from the last box until we find something that fits, or we run out of words
            final String trimmedText = runData.getText().trim();
            run.setText(trimmedText);

            for (final StringBuilder text = new StringBuilder(trimmedText); textBox.getTextHeight() > anchor
                    .getHeight() && text.length() > 0;) {
                final int lastSpaceIdx = Math.max(text.lastIndexOf(" "), text.lastIndexOf("\n"));

                if (lastSpaceIdx < 0) {
                    break;
                }

                text.delete(lastSpaceIdx, text.length());
                // Add a trailing ellipsis unless it's empty or already contained a trailing ellipsis or "..." at the final truncated position.
                run.setText(
                        text.length() > 0 ? text.toString().replaceFirst("(\\s*(\\.{3}|\u2026))?$", "\u2026")
                                : "");
            }

            // The font metrics aren't going to be perfect (due to unavailability of fonts etc.) so we force the truncated text to fit.
            textBox.setTextAutofit(TextShape.TextAutofit.NORMAL);

            break;
        }
    }
}

From source file:info.informationsea.venn.graphics.VennDrawSlides.java

License:Open Source License

public void draw() {
    Dimension slideSize = slide.getSlideShow().getPageSize();
    Dimension availableSize = new Dimension(slideSize.width - marginLeft - marginRight,
            slideSize.height - marginBottom - marginTop);

    BufferedImage image = new BufferedImage(10, 10, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D g = (Graphics2D) image.getGraphics();
    Font font = new Font("SansSerif", Font.PLAIN, (int) fontSize);

    // Calculate draw area
    Rectangle2D drawRect = vennFigure.drawRect(str -> font.getStringBounds(str, g.getFontRenderContext()));

    // resize graphics
    double resizeFactorX = drawRect.getWidth() / availableSize.getWidth();
    double resizeFactorY = drawRect.getHeight() / availableSize.getHeight();
    double resizeFactor = 1 / Math.max(resizeFactorX, resizeFactorY);

    /*/*www .  ja v  a2  s  .  c  om*/
    {
    XSLFAutoShape autoShape = slide.createAutoShape();
    autoShape.setShapeType(XSLFShapeType.RECT);
    autoShape.setAnchor(new Rectangle(new Point(marginLeft, marginTop), availableSize));
    autoShape.setLineColor(Color.BLACK);
    autoShape.setLineWidth(1);
    }
    */

    // fill first
    for (VennFigure.Shape<T> shape : vennFigure.getShapes()) {

        if (shape instanceof VennFigure.Oval) {
            VennFigure.Oval<T> oval = (VennFigure.Oval<T>) shape;
            Color fillColor = VennDrawGraphics2D.decodeColor(oval.getColor());

            if (fillColor.getAlpha() != 0) {
                XSLFAutoShape autoShape = slide.createAutoShape();
                autoShape.setShapeType(XSLFShapeType.ELLIPSE);

                autoShape.setFillColor(fillColor);
                if (fillColor.getAlpha() != 255) {
                    CTShapeImpl obj = (CTShapeImpl) autoShape.getXmlObject();
                    obj.getSpPr().getSolidFill().getSrgbClr().addNewAlpha()
                            .setVal(100000 * fillColor.getAlpha() / 255);
                }

                autoShape.setAnchor(new Rectangle(
                        (int) ((oval.getCenter().getX() - oval.getWidth() / 2 - drawRect.getMinX())
                                * resizeFactor + marginLeft),
                        (int) ((oval.getCenter().getY() - oval.getHeight() / 2 - drawRect.getMinY())
                                * resizeFactor + marginTop),
                        (int) (oval.getWidth() * resizeFactor), (int) (oval.getHeight() * resizeFactor)));
                autoShape.setRotation(oval.getTheta() / Math.PI * 180);
            }
        }
    }

    // stroke next
    for (VennFigure.Shape<T> shape : vennFigure.getShapes()) {
        if (shape instanceof VennFigure.Oval) {
            VennFigure.Oval<T> oval = (VennFigure.Oval<T>) shape;
            XSLFAutoShape autoShape = slide.createAutoShape();
            autoShape.setShapeType(XSLFShapeType.ELLIPSE);
            autoShape.setLineColor(Color.BLACK);
            autoShape.setLineWidth(1);

            autoShape.setAnchor(new Rectangle(
                    (int) ((oval.getCenter().getX() - oval.getWidth() / 2 - drawRect.getMinX()) * resizeFactor
                            + marginLeft),
                    (int) ((oval.getCenter().getY() - oval.getHeight() / 2 - drawRect.getMinY()) * resizeFactor
                            + marginTop),
                    (int) (oval.getWidth() * resizeFactor), (int) (oval.getHeight() * resizeFactor)));
            autoShape.setRotation(oval.getTheta() / Math.PI * 180);
        } else if (shape instanceof VennFigure.Text) {
            VennFigure.Text<T> text = (VennFigure.Text<T>) shape;
            XSLFTextBox textBox = slide.createTextBox();

            XSLFTextParagraph paragraph = textBox.addNewTextParagraph();

            XSLFTextRun textRun = paragraph.addNewTextRun();
            textRun.setText(text.getText());
            textRun.setFontSize(fontSize * resizeFactor);

            final double RESIZE_FACTOR = 1.1;
            final double TEXT_OFFSET = 10;

            Rectangle2D textSizeActual = font.getStringBounds(text.getText(), g.getFontRenderContext());

            textBox.setAnchor(new Rectangle2D.Double(0, 0,
                    textSizeActual.getWidth() * RESIZE_FACTOR * resizeFactor + TEXT_OFFSET,
                    100 * resizeFactor));
            Rectangle2D textSize = textBox.resizeToFitText();

            switch (text.getJust()) {
            case CENTER:
            default:
                paragraph.setTextAlign(TextAlign.CENTER);
                textBox.setAnchor(new Rectangle(
                        (int) ((text.getCenter().getX() - drawRect.getMinX()) * resizeFactor
                                - textSize.getWidth() / 2 + marginLeft),
                        (int) ((text.getCenter().getY() - drawRect.getMinY()) * resizeFactor
                                - textSize.getHeight() / 2 + marginTop),
                        (int) (textSize.getWidth()), (int) (textSize.getHeight())));
                break;
            case LEFT:
                paragraph.setTextAlign(TextAlign.LEFT);
                textBox.setAnchor(new Rectangle(
                        (int) ((text.getCenter().getX() - drawRect.getMinX()) * resizeFactor + marginLeft),
                        (int) ((text.getCenter().getY() - drawRect.getMinY()) * resizeFactor
                                - textSize.getHeight() / 2 + marginTop),
                        (int) (textSize.getWidth()), (int) (textSize.getHeight())));
                break;
            case RIGHT:
                paragraph.setTextAlign(TextAlign.RIGHT);
                textBox.setAnchor(new Rectangle(
                        (int) ((text.getCenter().getX() - drawRect.getMinX()) * resizeFactor
                                - textSize.getWidth() + marginLeft),
                        (int) ((text.getCenter().getY() - drawRect.getMinY()) * resizeFactor
                                - textSize.getHeight() / 2 + marginTop),
                        (int) (textSize.getWidth()), (int) (textSize.getHeight())));
                break;
            }
        }
    }
}

From source file:poi.xslf.usermodel.Tutorial2.java

License:Apache License

public static void main(String[] args) throws IOException {
    XMLSlideShow ppt = new XMLSlideShow();

    XSLFSlide slide1 = ppt.createSlide();
    XSLFTextBox shape1 = slide1.createTextBox();
    // initial height of the text box is 100 pt but
    Rectangle anchor = new Rectangle(10, 100, 300, 100);
    shape1.setAnchor(anchor);/*from ww w  .  j  a v a2s . c  om*/

    XSLFTextParagraph p1 = shape1.addNewTextParagraph();
    XSLFTextRun r1 = p1.addNewTextRun();
    r1.setText("Paragraph Formatting");
    r1.setFontSize(24);
    r1.setFontColor(new Color(85, 142, 213));

    XSLFTextParagraph p2 = shape1.addNewTextParagraph();
    // If spaceBefore >= 0, then space is a percentage of normal line height.
    // If spaceBefore < 0, the absolute value of linespacing is the spacing in points
    p2.setSpaceBefore(-20); // 20 pt from the previous paragraph
    p2.setSpaceAfter(300); // 3 lines after the paragraph
    XSLFTextRun r2 = p2.addNewTextRun();
    r2.setText("Paragraph  properties apply to all text residing within the corresponding paragraph.");
    r2.setFontSize(16);

    XSLFTextParagraph p3 = shape1.addNewTextParagraph();

    XSLFTextRun r3 = p3.addNewTextRun();
    r3.setText("Run Formatting");
    r3.setFontSize(24);
    r3.setFontColor(new Color(85, 142, 213));

    XSLFTextParagraph p4 = shape1.addNewTextParagraph();
    p4.setSpaceBefore(-20); // 20 pt from the previous paragraph
    p4.setSpaceAfter(300); // 3 lines after the paragraph
    XSLFTextRun r4 = p4.addNewTextRun();
    r4.setFontSize(16);
    r4.setText("Run level formatting is the most granular property level and allows "
            + "for the specifying of all low level text properties. The text run is "
            + "what all paragraphs are derived from and thus specifying various "
            + "properties per run will allow for a diversely formatted text paragraph.");

    // resize the shape to fit text
    shape1.resizeToFitText();

    FileOutputStream out = new FileOutputStream("text.pptx");
    ppt.write(out);
    out.close();
}

From source file:poi.xslf.usermodel.Tutorial4.java

License:Apache License

public static void main(String[] args) throws IOException {
    XMLSlideShow ppt = new XMLSlideShow();

    // XSLFSlide#createSlide() with no arguments creates a blank slide
    XSLFSlide slide = ppt.createSlide();

    XSLFTable tbl = slide.createTable();
    tbl.setAnchor(new Rectangle2D.Double(50, 50, 450, 300));

    int numColumns = 3;
    int numRows = 5;
    XSLFTableRow headerRow = tbl.addRow();
    headerRow.setHeight(50);//ww w  .  ja va 2 s.  c  om
    // header
    for (int i = 0; i < numColumns; i++) {
        XSLFTableCell th = headerRow.addCell();
        XSLFTextParagraph p = th.addNewTextParagraph();
        p.setTextAlign(TextAlign.CENTER);
        XSLFTextRun r = p.addNewTextRun();
        r.setText("Header " + (i + 1));
        r.setBold(true);
        r.setFontColor(Color.white);
        th.setFillColor(new Color(79, 129, 189));
        th.setBorderBottom(2);
        th.setBorderBottomColor(Color.white);

        tbl.setColumnWidth(i, 150); // all columns are equally sized
    }

    // rows

    for (int rownum = 0; rownum < numRows; rownum++) {
        XSLFTableRow tr = tbl.addRow();
        tr.setHeight(50);
        // header
        for (int i = 0; i < numColumns; i++) {
            XSLFTableCell cell = tr.addCell();
            XSLFTextParagraph p = cell.addNewTextParagraph();
            XSLFTextRun r = p.addNewTextRun();

            r.setText("Cell " + (i + 1));
            if (rownum % 2 == 0)
                cell.setFillColor(new Color(208, 216, 232));
            else
                cell.setFillColor(new Color(233, 247, 244));

        }

    }

    FileOutputStream out = new FileOutputStream("table.pptx");
    ppt.write(out);
    out.close();
}

From source file:poi.xslf.usermodel.Tutorial7.java

License:Apache License

public static void main(String[] args) throws IOException {
    XMLSlideShow ppt = new XMLSlideShow();

    XSLFSlide slide = ppt.createSlide();
    XSLFTextBox shape = slide.createTextBox();
    shape.setAnchor(new Rectangle(50, 50, 400, 200));

    XSLFTextParagraph p1 = shape.addNewTextParagraph();
    p1.setLevel(0);//from  w w w . j av  a2  s . c  o  m
    p1.setBullet(true);
    XSLFTextRun r1 = p1.addNewTextRun();
    r1.setText("Bullet1");

    XSLFTextParagraph p2 = shape.addNewTextParagraph();
    // indentation before text
    p2.setLeftMargin(60);
    // the bullet is set 40 pt before the text
    p2.setIndent(-40);
    p2.setBullet(true);
    // customize bullets
    p2.setBulletFontColor(Color.red);
    p2.setBulletFont("Wingdings");
    p2.setBulletCharacter("\u0075");
    p2.setLevel(1);
    XSLFTextRun r2 = p2.addNewTextRun();
    r2.setText("Bullet2");

    // the next three paragraphs form an auto-numbered list
    XSLFTextParagraph p3 = shape.addNewTextParagraph();
    p3.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 1);
    p3.setLevel(2);
    XSLFTextRun r3 = p3.addNewTextRun();
    r3.setText("Numbered List Item - 1");

    XSLFTextParagraph p4 = shape.addNewTextParagraph();
    p4.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 2);
    p4.setLevel(2);
    XSLFTextRun r4 = p4.addNewTextRun();
    r4.setText("Numbered List Item - 2");

    XSLFTextParagraph p5 = shape.addNewTextParagraph();
    p5.setBulletAutoNumber(ListAutoNumber.ALPHA_LC_PARENT_R, 3);
    p5.setLevel(2);
    XSLFTextRun r5 = p5.addNewTextRun();
    r5.setText("Numbered List Item - 3");

    shape.resizeToFitText();

    FileOutputStream out = new FileOutputStream("list.pptx");
    ppt.write(out);
    out.close();
}