Рубрики
Без рубрики

Создание презентаций PowerPoint на Java

В этой статье мы покажем вам, как создавать презентации PowerPoint с нуля, используя бесплатный Java PowerPoint API – бесплатный Spire. Презентация для Java. С тегом создать презентацию powerpoint, java, spire.

В этой статье мы покажем вам, как создавать презентации PowerPoint с нуля, используя бесплатный Java PowerPoint API – бесплатный Spire. Презентация для Java.

  1. Обзор FreeSpire. Презентация для Java
  2. Создайте презентацию “Привет, мир”
  3. Форматирование контента в презентации
  4. Добавление изображений в презентацию
  5. Добавить маркированный список в презентацию
  6. Создать таблицу в презентации
  7. Создание диаграммы в презентации
  8. Задайте свойства документа для представления
  9. Защитите презентацию паролем

Свободный дух. Презентация для Java – это бесплатный Java API PowerPoint, с помощью которого разработчики могут создавать, читать, изменять, записывать, конвертировать и сохранять документы PowerPoint в приложениях Java без установки Microsoft Office.

Для получения дополнительной информации о бесплатном Шпиле. Презентация для Java, проверьте здесь .

Скачать Бесплатный Шпиль. Презентационные банки: https://www.e-iceblue.com/Download/presentation-for-java-free.html

В следующем примере показано, как создать простую презентацию с текстом “Привет, мир”.

public class CreateHelloWorldPresentation {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //Get the first slide (By default there is 1 slide after creating)
        ISlide slide = ppt.getSlides().get(0);

        Rectangle2D rect = new Rectangle2D.Double(ppt.getSlideSize().getSize().getWidth() / 2 - 150, 80, 300, 150);

        //Append a rectangle shape to the slide
        IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, rect);
        shape.getShapeStyle().getLineColor().setColor(Color.white);
        shape.getFill().setFillType(FillFormatType.NONE);

        //Append text to the rectangle
        shape.appendTextFrame("Hello World!");

        //Get the 1st paragraph from the text frame
        ParagraphEx paragraph = shape.getTextFrame().getParagraphs().get(0);
        //Set font
        paragraph.getTextRanges().get(0).setLatinFont(new TextFont("Calibri"));
        paragraph.getTextRanges().get(0).setFontHeight(30);
        paragraph.getTextRanges().get(0).getFill().setFillType(FillFormatType.SOLID);
        paragraph.getTextRanges().get(0).getFill().getSolidColor().setColor(Color.black);

        //Save the presentation with file name "HelloWorld.pptx"
        ppt.saveToFile("HelloWorld.pptx", FileFormat.PPTX_2013);
    }
}

В следующем примере показано, как форматировать текстовое содержимое в презентации.

public class FormatContent {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();

        Rectangle2D rect = new Rectangle2D.Double(20, 70, ppt.getSlideSize().getSize().getWidth() - 40, 300);

        //Get the 1st slide
        ISlide slide = ppt.getSlides().get(0);

        //Append shape
        IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, rect);
        shape.getShapeStyle().getLineColor().setColor(Color.white);
        shape.getFill().setFillType(FillFormatType.NONE);

        shape.getTextFrame().getParagraphs().clear();

        //Append paragraphs and set formatting
        shape.getTextFrame().getParagraphs().append(new ParagraphEx());
        ParagraphEx paragraph = shape.getTextFrame().getParagraphs().get(0);
        paragraph.getTextRanges().append(new PortionEx("This is paragraph 1"));
        paragraph.setAlignment(TextAlignmentType.LEFT);
        paragraph.getTextRanges().get(0).setTextUnderlineType(TextUnderlineType.WAVY);
        paragraph.getTextRanges().get(0).getFill().setFillType(FillFormatType.SOLID);
        paragraph.getTextRanges().get(0).getFill().getSolidColor().setColor(Color.BLUE);

        shape.getTextFrame().getParagraphs().append(new ParagraphEx());
        paragraph = shape.getTextFrame().getParagraphs().get(1);
        paragraph.getTextRanges().append(new PortionEx("This is paragraph 2"));
        paragraph.setAlignment(TextAlignmentType.CENTER);
        paragraph.getTextRanges().get(0).setTextUnderlineType(TextUnderlineType.DOTTED);
        paragraph.getTextRanges().get(0).getFill().setFillType(FillFormatType.GRADIENT);
        paragraph.getTextRanges().get(0).getFill().getSolidColor().setColor(Color.BLACK);

        shape.getTextFrame().getParagraphs().append(new ParagraphEx());
        paragraph = shape.getTextFrame().getParagraphs().get(2);
        paragraph.getTextRanges().append(new PortionEx("This is paragraph 3"));
        paragraph.setAlignment(TextAlignmentType.RIGHT);
        paragraph.getTextRanges().get(0).setTextUnderlineType(TextUnderlineType.WAVY);
        paragraph.getTextRanges().get(0).getFill().setFillType(FillFormatType.SOLID);
        paragraph.getTextRanges().get(0).getFill().getSolidColor().setColor(Color.GREEN);

        for(int i = 0; i < shape.getTextFrame().getParagraphs().getCount(); i++)
        {
           paragraph = shape.getTextFrame().getParagraphs().get(i);
           paragraph.setSpaceAfter(50);
           paragraph.getTextRanges().get(0).setLatinFont(new TextFont("Arial"));
           paragraph.getTextRanges().get(0).setFontHeight(30f);
           paragraph.getTextRanges().get(0).isBold(TriState.TRUE);
        }

        //Save the document
        ppt.saveToFile("FormatContent.pptx", FileFormat.PPTX_2013);
        ppt.dispose();
    }
}

В следующем примере показано, как добавлять изображения в презентацию.

public class AddImages {
    public static void main(String[] args) throws Exception {
        Presentation ppt = new Presentation();

        Rectangle2D rect = new Rectangle2D.Double(50, 50, 200, 150);

        //Get the first slide
        ISlide slide = ppt.getSlides().get(0);
        //Insert an image into the slide
        IEmbedImage image = slide.getShapes().appendEmbedImage(ShapeType.RECTANGLE, "1.jpg", rect);
        image.getLine().setFillType(FillFormatType.NONE);

        rect = new Rectangle2D.Double(50, 250, 300, 200);
        image = slide.getShapes().appendEmbedImage(ShapeType.RECTANGLE, "392491.jpg", rect);
        image.getLine().setFillType(FillFormatType.NONE);

        ppt.saveToFile("AddImages.pptx", FileFormat.PPTX_2013);
    }
}

В следующем примере показано, как добавить маркированный список в презентацию.

public class AddBulletLists {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();

        Rectangle2D rect = new Rectangle2D.Double(50, 70, 300, 150);

        //Get the 1st slide
        ISlide slide = ppt.getSlides().get(0);

        //Append shape
        IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, rect);
        shape.getShapeStyle().getLineColor().setColor(Color.white);
        shape.getFill().setFillType(FillFormatType.NONE);

        shape.getTextFrame().getParagraphs().clear();

        String[] str = new String[] {"Item 1", "Item 2", "Item 3" };

        //Add bullet list
        for(int i = 0; i < str.length; i ++)
        {
            ParagraphEx paragraph = new ParagraphEx();
            paragraph.setText(str[i]);
            paragraph.setAlignment(TextAlignmentType.LEFT);
            paragraph.getTextRanges().get(0).getFill().setFillType(FillFormatType.SOLID);
            paragraph.getTextRanges().get(0).getFill().getSolidColor().setColor(Color.black);
            paragraph.setBulletType(TextBulletType.NUMBERED);
            paragraph.setBulletStyle(NumberedBulletStyle.BULLET_ROMAN_LC_PERIOD);
            shape.getTextFrame().getParagraphs().append(paragraph);
        }

        //Save the document
        ppt.saveToFile("AddBullets.pptx", FileFormat.PPTX_2013);
    }
}

В следующем примере показано, как создать таблицу в презентации.

public class CreateTable {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();

        Double[] widths = new Double[]{100d, 100d, 150d, 100d, 100d};
        Double[] heights = new Double[]{15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d};

        //Add a table to PPT
        ITable table = ppt.getSlides().get(0).getShapes().appendTable((float) ppt.getSlideSize().getSize().getWidth() / 2 - 275, 90, widths, heights);
        String[][] dataStr = new String[][]
                {
                        {"Name", "Capital", "Continent", "Area", "Population"},
                        {"Venezuela", "Caracas", "South America", "912047", "19700000"},
                        {"Bolivia", "La Paz", "South America", "1098575", "7300000"},
                        {"Brazil", "Brasilia", "South America", "8511196", "150400000"},
                        {"Canada", "Ottawa", "North America", "9976147", "26500000"},
                        {"Chile", "Santiago", "South America", "756943", "13200000"},
                        {"Colombia", "Bagota", "South America", "1138907", "33000000"},
                        {"Cuba", "Havana", "North America", "114524", "10600000"},
                        {"Ecuador", "Quito", "South America", "455502", "10600000"},
                        {"Paraguay", "Asuncion", "South America", "406576", "4660000"},
                        {"Peru", "Lima", "South America", "1285215", "21600000"},
                        {"Jamaica", "Kingston", "North America", "11424", "2500000"},
                        {"Mexico", "Mexico City", "North America", "1967180", "88600000"}
                };
        //Add data to table
        for (int i = 0; i < 13; i++) {
            for (int j = 0; j < 5; j++) {
                //Fill the table with data
                table.get(j, i).getTextFrame().setText(dataStr[i][j]);

                //Set font
                table.get(j, i).getTextFrame().getParagraphs().get(0).getTextRanges().get(0).setLatinFont(new TextFont("Arial Narrow"));
            }
        }
        //Set the alignment of the first row to Center
        for (int i = 0; i < 5; i++) {
            table.get(i, 0).getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.CENTER);
        }
        //Set the style of table
        table.setStylePreset(TableStylePreset.LIGHT_STYLE_3_ACCENT_1);

        //Save the document
        ppt.saveToFile("AddTable.pptx", FileFormat.PPTX_2013);
    }
}

Свободный дух. Презентация для Java поддерживает различные типы диаграмм. Здесь мы выбираем пузырьковую диаграмму в качестве примера.

public class CreateChart {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();

        //Add bubble chart
        Rectangle2D.Double rect1 = new Rectangle2D.Double(90, 100, 550, 320);
        IChart chart = null;
        chart = ppt.getSlides().get(0).getShapes().appendChart(ChartType.BUBBLE, rect1, false);

        //Chart title
        chart.getChartTitle().getTextProperties().setText("Bubble Chart");
        chart.getChartTitle().getTextProperties().isCentered(true);
        chart.getChartTitle().setHeight(30);
        chart.hasTitle(true);

        //Attach the data to chart
        double[] xdata = new double[]{7.7, 8.9, 1.0, 2.4};
        double[] ydata = new double[]{15.2, 5.3, 6.7, 8};
        double[] size = new double[]{1.1, 2.4, 3.7, 4.8};

        chart.getChartData().get(0, 0).setText("X-Value");
        chart.getChartData().get(0, 1).setText("Y-Value");
        chart.getChartData().get(0, 2).setText("Size");

        for (int i = 0; i < xdata.length; ++i) {
            chart.getChartData().get(i + 1, 0).setValue(xdata[i]);
            chart.getChartData().get(i + 1, 1).setValue(ydata[i]);
            chart.getChartData().get(i + 1, 2).setValue(size[i]);
        }

        //Set series label
        chart.getSeries().setSeriesLabel(chart.getChartData().get("B1", "B1"));

        chart.getSeries().get(0).setXValues(chart.getChartData().get("A2", "A5"));
        chart.getSeries().get(0).setYValues(chart.getChartData().get("B2", "B5"));
        chart.getSeries().get(0).getBubbles().add(chart.getChartData().get("C2"));
        chart.getSeries().get(0).getBubbles().add(chart.getChartData().get("C3"));
        chart.getSeries().get(0).getBubbles().add(chart.getChartData().get("C4"));
        chart.getSeries().get(0).getBubbles().add(chart.getChartData().get("C5"));

        //Save the document
        ppt.saveToFile("CreateChart.pptx", FileFormat.PPTX_2013);
        ppt.dispose();
    }
}

В следующем примере показано, как задать свойства документа, такие как автор, компания, ключевые слова, комментарии, категория, заголовок и тема, для презентации.

public class SetDocumentProperties {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();

        //Set the DocumentProperty of PPT document
        ppt.getDocumentProperty().setApplication("Spire.Presentation");
        ppt.getDocumentProperty().setAuthor("E-iceblue");
        ppt.getDocumentProperty().setCompany("E-iceblue Co., Ltd.");
        ppt.getDocumentProperty().setKeywords("Demo File");
        ppt.getDocumentProperty().setComments("This file is used to test Spire.Presentation.");
        ppt.getDocumentProperty().setCategory("Demo");
        ppt.getDocumentProperty().setTitle("This is a demo file.");
        ppt.getDocumentProperty().setSubject("Test");

        //Save the document
        ppt.saveToFile("SetProperties.pptx", FileFormat.PPTX_2013);
        ppt.dispose();
    }
}

В следующем примере показано, как защитить презентацию паролем.

public class ProtectPresentation {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();

        //Protect presentation with password
        String strPassword = "pwd123";
        ppt.encrypt(strPassword);

        //Save the document
        ppt.saveToFile("Protected.pptx", FileFormat.PPTX_2013);
        ppt.dispose();
    }
}

Оригинал: “https://dev.to/eiceblue/create-powerpoint-presentations-in-java-3cp”