Java (482)
A bar chart is a type of graph that represents or summarizes data in the form of horizontal rectangular bars of equal width but different lengths. In MS Excel, the bar chart is a great tool to compare data among different groups, which helps users to analyze data and draw conclusions quickly. In this article, you will learn how to programmatically create a clustered bar chart or a stacked bar chart in an Excel worksheet using Spire.XLS for Java.
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>16.3.2</version>
</dependency>
</dependencies>
Create a Clustered Bar Chart in Excel
In clustered bar chart, data values of different series are displayed in separate bars side-by-side, which allows a direct comparison of multiple data series per category. The following are the detailed steps to create a clustered bar chart in an Excel worksheet.
- Create an instance of Workbook class.
- Get a specified worksheet by its index using Workbook.getWorksheets().get() method.
- Add some data to specified cells and set the cell styles.
- Add a 2D clustered bar chart to the specified worksheet using Worksheet.getCharts().add(ExcelChartType.BarClustered) method.
- Set data range for the chart using Chart.setDataRange(CellRange dataRange) method.
- Set the position and title of the chart.
- Get the primary category axis of the chart using Chart.getPrimaryCategoryAxis() method, and then set the display text and title of the category axis using the methods under ChartCategoryAxis class.
- Get the primary value axis of the chart using Chart.getPrimaryValueAxis() method, and then set the title, minimum value and major gridlines of the value axis using the methods under ChartValueAxis class.
- Loop through the data series of the chart, and then show data labels for the data points of each data series by setting the value of ChartSerie.getDataPoints().getDefaultDataPoint().getDataLabels().hasValue() method to true.
- Set the position of chart legend using Chart.getLegend().setPosition() method.
- Save the result file using Workbook.saveToFile() method.
- Java
import com.spire.xls.*;
import com.spire.xls.charts.ChartSerie;
import com.spire.xls.charts.ChartSeries;
import java.awt.*;
public class CreateBarChart {
public static void main(String[] args) {
//Create an instance of Workbook class
Workbook workbook = new Workbook();
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Insert data to specified cells
sheet.getCellRange("A1").setValue("Country");
sheet.getCellRange("A2").setValue("Cuba");
sheet.getCellRange("A3").setValue("Mexico");
sheet.getCellRange("A4").setValue("France");
sheet.getCellRange("A5").setValue("German");
sheet.getCellRange("B1").setValue("Jun");
sheet.getCellRange("B2").setNumberValue(6000);
sheet.getCellRange("B3").setNumberValue(8000);
sheet.getCellRange("B4").setNumberValue(9000);
sheet.getCellRange("B5").setNumberValue(8500);
sheet.getCellRange("C1").setValue("Aug");
sheet.getCellRange("C2").setNumberValue(3000);
sheet.getCellRange("C3").setNumberValue(2000);
sheet.getCellRange("C4").setNumberValue(6000);
sheet.getCellRange("C5").setNumberValue(3500);
//Set cell styles
sheet.getCellRange("A1:C1").setRowHeight(15);
sheet.getCellRange("A1:C1").getCellStyle().setColor(Color.darkGray);
sheet.getCellRange("A1:C1").getCellStyle().getExcelFont().setColor(Color.white);
sheet.getCellRange("A1:C5").getCellStyle().setVerticalAlignment(VerticalAlignType.Center);
sheet.getCellRange("A1:C5").getCellStyle().setHorizontalAlignment(HorizontalAlignType.Center);
//Set number format
sheet.getCellRange("B2:C5").getCellStyle().setNumberFormat("\"$\"#,##0");
//Add a clustered bar chart to the worksheet
Chart chart = sheet.getCharts().add(ExcelChartType.BarClustered);
//Set data range for the chart
chart.setDataRange(sheet.getCellRange("A1:C5"));
chart.setSeriesDataFromRange(false);
//Set position of the chart
chart.setLeftColumn(1);
chart.setTopRow(6);
chart.setRightColumn(11);
chart.setBottomRow(29);
//Set and format chart title
chart.setChartTitle("Sales Report");
chart.getChartTitleArea().isBold(true);
chart.getChartTitleArea().setSize(12);
//Set and format category axis title
chart.getPrimaryCategoryAxis().setTitle("Country");
chart.getPrimaryCategoryAxis().getFont().isBold(true);
chart.getPrimaryCategoryAxis().getTitleArea().isBold(true);
chart.getPrimaryCategoryAxis().getTitleArea().setTextRotationAngle(90);
//Set and format value axis title
chart.getPrimaryValueAxis().setTitle("Sales(in USD)");
chart.getPrimaryValueAxis().hasMajorGridLines(false);
chart.getPrimaryValueAxis().setMinValue(1000);
chart.getPrimaryValueAxis().getTitleArea().isBold(true);
//Show data labels for data points
ChartSeries series = chart.getSeries();
for (int i = 0;i < series.size();i++)
{
ChartSerie cs = series.get(i);
cs.getFormat().getOptions().isVaryColor(true);
cs.getDataPoints().getDefaultDataPoint().getDataLabels().hasValue(true);
}
//Set position of chart legend
chart.getLegend().setPosition(LegendPositionType.Top);
//Save the result file
workbook.saveToFile("CreateBarChart.xlsx", ExcelVersion.Version2016);
}
}

Create a Stacked Bar Chart in Excel
In stacked bar chart, data values of different series are stacked one over the other in a single bar. Compared with the clustered bar chart, the stacked bar chart provides a clearer view of part-to-whole comparison in each category. The following are the detailed steps to create a stacked bar chart in an Excel worksheet.
- Create an instance of Workbook class.
- Get a specified worksheet by its index using Workbook.getWorksheets().get() method.
- Add some data to specified cells and set the cell styles.
- Add a 2D stacked bar chart to the specified worksheet using Worksheet.getCharts().add(ExcelChartType.BarStacked) method.
- Set data range for the chart using Chart.setDataRange(CellRange dataRange) method.
- Set position, title, category axis title and value axis title for the chart.
- Loop through the data series of the chart, and then show data labels for the data points of each data series by setting the value of ChartSerie.getDataPoints().getDefaultDataPoint().getDataLabels().hasValue() method to true.
- Set the position of chart legend using Chart.getLegend().setPosition() method.
- Save the result file using Workbook.saveToFile() method.
- Java
import com.spire.xls.*;
import com.spire.xls.charts.ChartSerie;
import com.spire.xls.charts.ChartSeries;
import java.awt.*;
public class CreateBarChart {
public static void main(String[] args) {
//Create a Workbook object
Workbook workbook = new Workbook();
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Insert data to specified cells
sheet.getCellRange("A1").setValue("Country");
sheet.getCellRange("A2").setValue("Cuba");
sheet.getCellRange("A3").setValue("Mexico");
sheet.getCellRange("A4").setValue("France");
sheet.getCellRange("A5").setValue("German");
sheet.getCellRange("B1").setValue("Jun");
sheet.getCellRange("B2").setNumberValue(6000);
sheet.getCellRange("B3").setNumberValue(8000);
sheet.getCellRange("B4").setNumberValue(9000);
sheet.getCellRange("B5").setNumberValue(8500);
sheet.getCellRange("C1").setValue("Aug");
sheet.getCellRange("C2").setNumberValue(3000);
sheet.getCellRange("C3").setNumberValue(2000);
sheet.getCellRange("C4").setNumberValue(6000);
sheet.getCellRange("C5").setNumberValue(3500);
//Set cell styles
sheet.getCellRange("A1:C1").setRowHeight(15);
sheet.getCellRange("A1:C1").getCellStyle().setColor(Color.darkGray);
sheet.getCellRange("A1:C1").getCellStyle().getExcelFont().setColor(Color.white);
sheet.getCellRange("A1:C5").getCellStyle().setVerticalAlignment(VerticalAlignType.Center);
sheet.getCellRange("A1:C5").getCellStyle().setHorizontalAlignment(HorizontalAlignType.Center);
//Set number format
sheet.getCellRange("B2:C5").getCellStyle().setNumberFormat("\"$\"#,##0");
//Add a stacked bar chart to the worksheet
Chart chart = sheet.getCharts().add(ExcelChartType.BarStacked);
//Set data range for the chart
chart.setDataRange(sheet.getCellRange("A1:C5"));
chart.setSeriesDataFromRange(false);
//Set position of the chart
chart.setLeftColumn(1);
chart.setTopRow(6);
chart.setRightColumn(11);
chart.setBottomRow(29);
//Set and format chart title
chart.setChartTitle("Sales Report");
chart.getChartTitleArea().isBold(true);
chart.getChartTitleArea().setSize(12);
//Set and format category axis title
chart.getPrimaryCategoryAxis().setTitle("Country");
chart.getPrimaryCategoryAxis().getFont().isBold(true);
chart.getPrimaryCategoryAxis().getTitleArea().isBold(true);
chart.getPrimaryCategoryAxis().getTitleArea().setTextRotationAngle(90);
//Set and format value axis title
chart.getPrimaryValueAxis().setTitle("Sales(in USD)");
chart.getPrimaryValueAxis().hasMajorGridLines(false);
chart.getPrimaryValueAxis().setMinValue(1000);
chart.getPrimaryValueAxis().getTitleArea().isBold(true);
//Show data labels for data points
ChartSeries series = chart.getSeries();
for (int i = 0;i < series.size();i++)
{
ChartSerie cs = series.get(i);
cs.getFormat().getOptions().isVaryColor(true);
cs.getDataPoints().getDefaultDataPoint().getDataLabels().hasValue(true);
}
//Set position of chart legend
chart.getLegend().setPosition(LegendPositionType.Top);
//Save the result file
workbook.saveToFile("StackedBarChart.xlsx", ExcelVersion.Version2016);
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Word and Excel are different from each other in terms of their uses and functioning. Word is used primarily for text documents such as essays, emails, letters, books, resumes, or academic papers where text formatting is essential. Excel is used to save data, make tables and charts and make complex calculations.
It is not recommended to convert a complex Word file to an Excel spreadsheet, because Excel can hardly render contents in the same way as Word. However, if your Word document is mainly composed of tables and you want to analyze the table data in Excel, you can use Spire.Office for Java to convert Word to Excel while maintaining good readability.
Install Spire.Office for Java
First of all, you're required to add the Spire.Office.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.office</artifactId>
<version>11.3.0</version>
</dependency>
</dependencies>
Convert Word to Excel in Java
This scenario actually uses two libraries in the Spire.Office package. They're Spire.Doc for Java and Spire.XLS for Java. The former is used to read and extract content from a Word document, and the latter is used to create an Excel document and write data in the specific cells. To make this code example easy to understand, we created the following three custom methods that preform specific functions.
- exportTableInExcel() - Export data from a Word table to specified Excel cells.
- copyContentInTable() - Copy content from a table cell in Word to an Excel cell.
- copyTextAndStyle() - Copy text with formatting from a Word paragraph to an Excel cell.
The following steps demonstrate how to export data from a Word document to a worksheet using Spire.Office for Java.
- Create a Document object to load a Word file.
- Create a Workbook object and add a worksheet named "WordToExcel" to it.
- Traverse though all the sections in the Word document, traverse through all the document objects under a certain section, and then determine if a document object is a paragraph or a table.
- If the document object is a paragraph, write the paragraph in a specified cell in Excel using coypTextAndStyle() method.
- If the document object is a table, export the table data from Word to Excel cells using exportTableInExcel() method.
- Auto fit the row height and column width in Excel so that the data within a cell will not exceed the bound of the cell.
- Save the workbook to an Excel file using Workbook.saveToFile() method.
- Java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import com.spire.xls.*;
import java.awt.*;
public class ConvertWordToExcel {
public static void main(String[] args) {
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Invoice.docx");
//Create a Workbook object
Workbook wb = new Workbook();
//Remove the default worksheets
wb.getWorksheets().clear();
//Create a worksheet named "WordToExcel"
Worksheet worksheet = wb.createEmptySheet("WordToExcel");
int row = 1;
int column = 1;
//Loop through the sections in the Word document
for (int i = 0; i < doc.getSections().getCount(); i++) {
//Get a specific section
Section section = doc.getSections().get(i);
//Loop through the document object under a certain section
for (int j = 0; j < section.getBody().getChildObjects().getCount(); j++) {
//Get a specific document object
DocumentObject documentObject = section.getBody().getChildObjects().get(j);
//Determine if the object is a paragraph
if (documentObject instanceof Paragraph) {
CellRange cell = worksheet.getCellRange(row, column);
Paragraph paragraph = (Paragraph) documentObject;
//Copy paragraph from Word to a specific cell
copyTextAndStyle(cell, paragraph);
row++;
}
//Determine if the object is a table
if (documentObject instanceof Table) {
Table table = (Table) documentObject;
//Export table data from Word to Excel
int currentRow = exportTableInExcel(worksheet, row, table);
row = currentRow;
}
}
}
//Wrap text in cells
worksheet.getAllocatedRange().isWrapText(true);
//Auto fit row height and column width
worksheet.getAllocatedRange().autoFitRows();
worksheet.getAllocatedRange().autoFitColumns();
//Save the workbook to an Excel file
wb.saveToFile("output/WordToExcel.xlsx", ExcelVersion.Version2013);
}
//Export data from Word table to Excel cells
private static int exportTableInExcel(Worksheet worksheet, int row, Table table) {
CellRange cell;
int column;
for (int i = 0; i < table.getRows().getCount(); i++) {
column = 1;
TableRow tbRow = table.getRows().get(i);
for (int j = 0; j < tbRow.getCells().getCount(); j++) {
TableCell tbCell = tbRow.getCells().get(j);
cell = worksheet.getCellRange(row, column);
cell.borderAround(LineStyleType.Thin, Color.BLACK);
copyContentInTable(tbCell, cell);
column++;
}
row++;
}
return row;
}
//Copy content from a Word table cell to an Excel cell
private static void copyContentInTable(TableCell tbCell, CellRange cell) {
Paragraph newPara = new Paragraph(tbCell.getDocument());
for (int i = 0; i < tbCell.getChildObjects().getCount(); i++) {
DocumentObject documentObject = tbCell.getChildObjects().get(i);
if (documentObject instanceof Paragraph) {
Paragraph paragraph = (Paragraph) documentObject;
for (int j = 0; j < paragraph.getChildObjects().getCount(); j++) {
DocumentObject cObj = paragraph.getChildObjects().get(j);
newPara.getChildObjects().add(cObj.deepClone());
}
if (i < tbCell.getChildObjects().getCount() - 1) {
newPara.appendText("\n");
}
}
}
copyTextAndStyle(cell, newPara);
}
//Copy text and style of a paragraph to a cell
private static void copyTextAndStyle(CellRange cell, Paragraph paragraph) {
RichText richText = cell.getRichText();
richText.setText(paragraph.getText());
int startIndex = 0;
for (int i = 0; i < paragraph.getChildObjects().getCount(); i++) {
DocumentObject documentObject = paragraph.getChildObjects().get(i);
if (documentObject instanceof TextRange) {
TextRange textRange = (TextRange) documentObject;
String fontName = textRange.getCharacterFormat().getFontName();
boolean isBold = textRange.getCharacterFormat().getBold();
Color textColor = textRange.getCharacterFormat().getTextColor();
float fontSize = textRange.getCharacterFormat().getFontSize();
String textRangeText = textRange.getText();
int strLength = textRangeText.length();
ExcelFont font = new ExcelFont(cell.getWorksheet().getWorkbook().createFont());
font.setColor(textColor);
font.isBold(isBold);
font.setSize(fontSize);
font.setFontName(fontName);
int endIndex = startIndex + strLength;
richText.setFont(startIndex, endIndex, font);
startIndex += strLength;
}
if (documentObject instanceof DocPicture) {
DocPicture picture = (DocPicture) documentObject;
cell.getWorksheet().getPictures().add(cell.getRow(), cell.getColumn(), picture.getImage());
cell.getWorksheet().setRowHeightInPixels(cell.getRow(), 1, picture.getImage().getHeight());
}
}
switch (paragraph.getFormat().getHorizontalAlignment()) {
case Left:
cell.setHorizontalAlignment(HorizontalAlignType.Left);
break;
case Center:
cell.setHorizontalAlignment(HorizontalAlignType.Center);
break;
case Right:
cell.setHorizontalAlignment(HorizontalAlignType.Right);
break;
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Java: Convert Images (PNG, JPG, BMP, etc.) to PowerPoint
2022-11-17 01:36:00 Written by AdministratorPicture files are among the most commonly used types of documents in people's lives. Sometimes, you may want to take all image files in a folder and convert them into slides for a PowerPoint presentation. Depending on your requirements, you can convert images to shapes or slide backgrounds. This article demonstrates how to convert images (in any common image format) to a PowerPoint document in Java using Spire.Presentation for Java.
- Convert Images to Backgrounds in PowerPoint in Java
- Convert Images to Shapes in PowerPoint in Java
- Convert Images to PowerPoint with Customized Slide Size in Java
Install Spire.Presentation for Java
First, you're required to add the Spire.Presentation.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.presentation</artifactId>
<version>11.3.5</version>
</dependency>
</dependencies>
Convert Images to Backgrounds in PowerPoint in Java
When images are converted as background of each slide in a PowerPoint document, they cannot be moved or scaled. The following are the steps to convert a set of images to a PowerPoint file as background images using Spire.Presentation for Java.
- Create a Presentation object.
- Set the slide size type to Sreen16x9.
- Get the image paths from a folder.
- Traverse through the images.
- Get a specific image and append it to the image collection of the document using Presentation.getImages().append() method.
- Add a slide to the document using Presentation.getSlides().append() method.
- Set the image as the background of the slide using the methods under SlideBackground object.
- Save the document to a PowerPoint file using Presentation.saveToFile() method.
- Java
import com.spire.presentation.*;
import com.spire.presentation.drawing.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
public class ConvertImagesAsBackground {
public static void main(String[] args) throws Exception {
//Create a Presentation object
Presentation presentation = new Presentation();
//Set slide size type
presentation.getSlideSize().setType(SlideSizeType.SCREEN_16_X_9);
//Remove the default slide
presentation.getSlides().removeAt(0);
//Get image files from a folder
File directoryPath = new File("C:\\Users\\Administrator\\Desktop\\Images");
File[] picFiles = directoryPath.listFiles();
//Loop through the images
for (int i = 0; i < picFiles.length; i++)
{
//Add a slide
ISlide slide = presentation.getSlides().append();
//Get a specific image
String imageFile = picFiles[i].getAbsolutePath();
//Append it to the image collection
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imageFile));
IImageData imageData = presentation.getImages().append(bufferedImage);
//Set the image as the background image of the slide
slide.getSlideBackground().setType(BackgroundType.CUSTOM);
slide.getSlideBackground().getFill().setFillType(FillFormatType.PICTURE);
slide.getSlideBackground().getFill().getPictureFill().setFillType(PictureFillType.STRETCH);
slide.getSlideBackground().getFill().getPictureFill().getPicture().setEmbedImage(imageData);
}
//Save to file
presentation.saveToFile("output/ImagesToBackground.pptx", FileFormat.PPTX_2013);
}
}

Convert Images to Shapes in PowerPoint in Java
If you would like the images are moveable and resizable in the PowerPoint file, you can convert them as shapes. Below are the steps to convert images to shapes in a PowerPoint document using Spire.Presentation for Java.
- Create a Presentation object.
- Set the slide size type to Sreen16x9.
- Get the image paths from a folder.
- Traverse through the images.
- Get a specific image and append it to the image collection of the document using Presentation.getImages().append() method.
- Add a slide to the document using Presentation.getSlides().append() method.
- Add a shape with the size equal to the slide using ISlide.getShapes().appendShape() method.
- Fill the shape with the image using the methods under FillFormat object.
- Save the document to a PowerPoint file using Presentation.saveToFile() method.
- Java
import com.spire.presentation.*;
import com.spire.presentation.drawing.*;
import javax.imageio.ImageIO;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
public class ConvertImageToShape {
public static void main(String[] args) throws Exception {
//Create a Presentation object
Presentation presentation = new Presentation();
//Set slide size type
presentation.getSlideSize().setType(SlideSizeType.SCREEN_16_X_9);
//Remove the default slide
presentation.getSlides().removeAt(0);
//Get image files from a folder
File directoryPath = new File("C:\\Users\\Administrator\\Desktop\\Images");
File[] picFiles = directoryPath.listFiles();
//Loop through the images
for (int i = 0; i < picFiles.length; i++)
{
//Add a slide
ISlide slide = presentation.getSlides().append();
//Get a specific image
String imageFile = picFiles[i].getAbsolutePath();
//Append it to the image collection
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imageFile));
IImageData imageData = presentation.getImages().append(bufferedImage);
//Add a shape with the size equal to the slide
IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Float(0, 0, (float) presentation.getSlideSize().getSize().getWidth(), (float)presentation.getSlideSize().getSize().getHeight()));
//Fill the shape with image
shape.getLine().setFillType(FillFormatType.NONE);
shape.getFill().setFillType(FillFormatType.PICTURE);
shape.getFill().getPictureFill().setFillType(PictureFillType.STRETCH);
shape.getFill().getPictureFill().getPicture().setEmbedImage(imageData);
}
//Save to file
presentation.saveToFile("output/ImagesToShape.pptx", FileFormat.PPTX_2013);
}
}

Convert Images to PowerPoint with Customized Slide Size in Java
If the aspect ratio of your images is not 16:9, or they are not in a standard slide size, you can create slides based on the actual size of the pictures. This will prevent the image from being over stretched or compressed. The following are the steps to convert images to a PowerPoint document with customized slide size using Spire.Presentation for Java.
- Create a Presentation object.
- Create a PdfUnitConvertor object, which is used to convert pixel to point.
- Get the image paths from a folder.
- Traverse through the images.
- Get a specific image and append it to the image collection of the document using Presentation.getImages().append() method.
- Get the image width and height, and convert them to point.
- Set the slide size of the presentation based on the image size using Presentation.getSlideSize().setSize() method.
- Add a slide to the document using Presentation.getSlides().append() method.
- Set the image as the background image of the slide using the methods under SlideBackground object.
- Save the document to a PowerPoint file using Presentation.saveToFile() method.
- Java
import com.spire.presentation.pdf.graphics.PdfGraphicsUnit;
import com.spire.presentation.pdf.graphics.PdfUnitConvertor;
import com.spire.presentation.*;
import com.spire.presentation.drawing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
public class CustomizeSlideSize {
public static void main(String[] args) throws Exception {
//Create a Presentation object
Presentation presentation = new Presentation();
//Remove the default slide
presentation.getSlides().removeAt(0);
//Get image files from a folder
File directoryPath = new File("C:\\Users\\Administrator\\Desktop\\Images");
File[] picFiles = directoryPath.listFiles();
//Create a PdfUnitConvertor object
PdfUnitConvertor convertor = new PdfUnitConvertor();
//Loop through the images
for (int i = 0; i < picFiles.length; i++)
{
//Get a specific image
String imageFile = picFiles[i].getAbsolutePath();
//Append it to the image collection
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imageFile));
IImageData imageData = presentation.getImages().append(bufferedImage);
//Get image height and width in pixel
int height = imageData.getHeight();
int width = imageData.getWidth();
//Convert pixel to point
float widthPoint = convertor.convertUnits(width, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);
float heightPoint= convertor.convertUnits(height, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);
//Set slide size
presentation.getSlideSize().setSize(new Dimension((int)widthPoint, (int)heightPoint));
//Add a slide
ISlide slide = presentation.getSlides().append();
//Set the image as the background image of the slide
slide.getSlideBackground().setType(BackgroundType.CUSTOM);
slide.getSlideBackground().getFill().setFillType(FillFormatType.PICTURE);
slide.getSlideBackground().getFill().getPictureFill().setFillType(PictureFillType.STRETCH);
slide.getSlideBackground().getFill().getPictureFill().getPicture().setEmbedImage(imageData);
}
//Save to file
presentation.saveToFile("output/CustomizeSlideSize.pptx", FileFormat.PPTX_2013);
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.