Sunday, 29 November 2020

Add Watermark to Excel Worksheets in Java

Actually, Microsoft Excel doesn’t have a built-in feature to add watermark in Excel worksheets. But there are still several ways to do it, such as adding header image or WordArt to worksheets to simulate the look of a watermark. This article will show you how to create and insert a header image in Excel to mimic a watermark using Java codes.

In addition to JDK and Intellij IDEA, you need a third-party library to build our test environment. Here I’ll recommend a free API called Free Spire.XLS for Java, which is a free and professional Java Excel API that enables developers to create, manipulate, convert and print Excel worksheets without using Microsoft Office.

Add Spire.Xls.jar as a dependency

There are two ways to add Spire.Xls.jar located in the free API to your project as a dependency. If you’re creating a Maven project in IDEA, the best choice is specifying the following configuration in the pom.xml file, and clicking the button “Import Changes”.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

If you are a non-maven user, then download the package from the website page, and add Spire.Xls.jar

to run the sample code given in this tutorial.

The screenshot below is shown what it finally looks like.


Using the code

Here are some steps to add text watermark to Excel worksheets in Java using Free Spire.XLS for Java.

Please note that the watermark can only be shown when the view mode is Layout, so don’t forget to

change the view mode.

Step 1: Define a custom function called DrawText() to create an image based on the text content of a

string. The string can be “Confidential”, “draft”, “Sample” or any text which you want to be shown as

watermark.

Step 2: Initialize a Workbook instance and load the test file.

Step 3: Call DrawText() method to create an image, set the image as left header image.

Step 4: Save the resulting document.

import com.spire.xls.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;

public class AddTextWatermark {
public static void main(String[] args) {
//Initialize a Workbook instance and load the test file
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Test.xlsx");

//Set text content of watermark and its size
Font font = new Font("Arial", Font.PLAIN, 50);
String watermark = "Draft";

for (Worksheet sheet : (Iterable<Worksheet>) workbook.getWorksheets()) {
//Call DrawText() method to insert the image
BufferedImage imgWtrmrk = drawText(watermark, font, Color.pink, Color.white, sheet.
getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());

//Set the image as left header
sheet.getPageSetup().setLeftHeaderImage(imgWtrmrk);
sheet.getPageSetup().setLeftHeader("&G");

//Set the Viewmode as Layout
sheet.setViewMode(ViewMode.Layout);
}

//Save the document
workbook.saveToFile("output/AddWatermark.xlsx", ExcelVersion.Version2010);
}
private static BufferedImage drawText (String text, Font font, Color textColor, Color backColor,double height, double width)
{
//Create an image with specified width and height
BufferedImage img = new BufferedImage((int) width, (int) height, TYPE_INT_ARGB);
Graphics2D loGraphic = img.createGraphics();

//set the font size
FontMetrics loFontMetrics = loGraphic.getFontMetrics(font);
int liStrWidth = loFontMetrics.stringWidth(text);
int liStrHeight = loFontMetrics.getHeight();

//set the text format
loGraphic.setColor(backColor);//paint the background
loGraphic.fillRect(0, 0, (int) width, (int) height);
loGraphic.translate(((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);
loGraphic.rotate(Math.toRadians(-35)); //Rotate text
//reset translate transform
loGraphic.translate(-((int) width - liStrWidth) / 2, -((int) height - liStrHeight) / 2);
loGraphic.setFont(font);
loGraphic.setColor(textColor);
//draw text on the image at center position
loGraphic.drawString(text, ((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);
loGraphic.dispose();
return img;
}
}

Output




 

Thursday, 26 November 2020

Insert HTML in PowerPoint in Java using a free API

Usually, HTML can include text, image, audio or video. In this article, I’ll use a free API to separately demonstrate how to insert HTML formatted text or HTML with an image into PowerPoint slides using Java code.

The free API I used in this tutorial is called Free Spire.Presentation for Java which is a free and professional PowerPoint API that enables developers to create, read, write, convert and save PowerPoint documents in Java Applications without installing Microsoft Office.

Before running codes, you need to insert Spire.Presentation.jar into your project. If you’re creating a Maven project, you just need to specify the following configuration in your Maven pom.xml and then click the “Import Changes”.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.presentation.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Finally, it will look like the screenshot below.


Insert HTML formatted text in a PowerPoint slide

Free Spire.Presentation for Java provides the addFromHTML method to support inserting HTML

formatted text in a PowerPoint slide. In the process of it, you can set the font color of the text. Here

are code snippets to do it.

import java.awt.Color;
import java.awt.Rectangle;
import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

public class AddHTMLText {
public static void main(String[] args) throws Exception {
//Initiate a Presentation object
Presentation ppt = new Presentation();
//Add a Shape to the first slide, and set its size and location
IAutoShape shape = ppt.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle(50, 50, 350, 120));
//Set the format type of the shape
shape.getFill().setFillType(FillFormatType.SOLID);
shape.getFill().getSolidColor().setColor(Color.white);
shape.getShapeStyle().getLineColor().setColor(Color.black);
//Clear the default paragraph
shape.getTextFrame().getParagraphs().clear();
//Insert html string with text in the shape
String code = "<ul><li style=\"color:blue\">Introduction to Brand Marketing</li><li style=\"color:green\">Brand Positioning Personality</li>" +
"<li style=\"color:gray\">Brand Design</li><li style=\"color:red\">Brand Communication Advertising</li></ul>";
shape.getTextFrame().getParagraphs().addFromHtml(code);
//Saving the resulting document
String outputFile = "output/AddHTMLStringToPPT.pptx";
ppt.saveToFile(outputFile, FileFormat.PPTX_2010);
}
}

Output


Insert
HTML with text and an image in a PowerPoint slide

You can insert HTML with an image through adding the local link of an image to the HTML String.

import com.spire.presentation.*;
import com.spire.presentation.collections.ShapeList;

public class AddHTMLWithImages {
public static void main(String[] args) throws Exception {
//Initiate a Presentation object
Presentation ppt = new Presentation();
//Get the shapes on the first slide
ShapeList shapes = ppt.getSlides().get(0).getShapes();
//Add HTML with text and an image to the shapes
String code ="<html><body><li style=\"color:blue\">Producer's Perspective</li><p>Emphasize the external performance of the brand</p>" +
"<img src='C:\\Users\\Test1\\Desktop\\Image.jpg'/></body></html>";
shapes.addFromHtml(code);
//Saving the resulting document
String outputFile = "output/AddHTMLWithImages.pptx";
ppt.saveToFile(outputFile,FileFormat.PPTX_2010);
}
}

Output



Monday, 23 November 2020

Create a PDF document in Java using a free API

Usually, we can get a PDF document only by converting other document formats. Here, I will introduce a method to directly create a PDF document with a head, paragraph and image, which is that using Java code to do it programmatically.

It is worth noting that I used a free API called Free Spire.PDF for Java in this tutorial. It enables Java applications to create, read, convert and save PDF documents without installing Adobe Acrobat.

Before running codes, please download the Free Spire.PDF for Java package from the link, unzip it and find Spire.Pdf.jar in the “lib” folder. Finally just manually add the jar file to your project.

Of course, if you’re creating a Maven project, just add the following configuration into the pom.xml file.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Using the code

After finishing the steps above, the next thing you need to do is following the code snippets in order to

generate a PDF document.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class CreateAPdf {
public static void main(String[] args) {
//create a PdfDocument object
PdfDocument doc = new PdfDocument();

//add a page
PdfPageBase page = doc.getPages().add();

//create two solid brushes
PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.BLACK));

//create two fonts
PdfFont font1 = new PdfFont(PdfFontFamily.Helvetica, 15f, PdfFontStyle.Bold);
PdfFont font2 = new PdfFont(PdfFontFamily.Helvetica, 12f);

//initialize x, y coordinates
float x = 0;
float y = 0;

//title
String title = "Java-Overview";

//align text to center via PdfTextAlignment class
PdfTextAlignment alignment = PdfTextAlignment.Center;

//draw title on the center of the page
drawTitle(page, title, font1, brush1, (float) page.getClientSize().getWidth() / 2, y, alignment);
y = y + 30;

//paragraph text
String paragraph = "Java is a class-based, object-oriented programming language that is
designed to have as few implementation dependencies as possible. It is a general-purpose 
programming language intended to let application developers write once, run anywhere, meaning 
that compiled Java code can run on all platforms that support Java without the need for 
recompilation. Java applications are typically compiled to bytecode that can run on any 
Java virtual machine (JVM) regardless of the underlying computer architecture. The syntax of Java
is similar to C and C++, but has fewer low-level facilities than either of them. The Java 
runtime provides dynamic capabilities (such as reflection and runtime code modification)that are
typically not available in traditional compiled languages. As of 2019, Java was one of the most 
popular programming languages in use according to GitHub, particularly for client-server web applications, with a reported 9 million developers.";
        //draw paragraph on the page
PdfLayoutResult layoutResult = drawParagraph(page, paragraph, font2, brush2, x, y);
y = y + (float) layoutResult.getBounds().getHeight() + 10;

//load an image file
PdfImage image = PdfImage.fromImage("C:\\Users\\Test1\\Desktop\\Image.png");

//draw image on the page
drawImage(page, image, x, y);
y = y + (float) image.getPhysicalDimension().getHeight() + 10;

//save to file
doc.saveToFile("output/CreatePdf.pdf");
}
public static void drawTitle(PdfPageBase page, String text, PdfFont font, PdfBrush brush,
float x, float y, PdfTextAlignment alignment) {

//set the text alignment via PdfStringFormat class
PdfStringFormat format = new PdfStringFormat();
format.setAlignment(alignment);

//draw title on the page
page.getCanvas().drawString(text, font, brush, x, y, format);
}
public static PdfLayoutResult drawParagraph(PdfPageBase page, String text, PdfFont font, PdfBrush
brush, float x, float y) {

//create a PdfTextWidget object
PdfTextWidget widget = new PdfTextWidget(text, font, brush);

//set the PdfLayoutType to Paginate to make the content paginated automatically
PdfTextLayout layout = new PdfTextLayout();
layout.setLayout(PdfLayoutType.Paginate);

//create a rectangle where the paragraph will be placed
Rectangle2D.Float rect = new Rectangle2D.Float(0, y, (float) page.getClientSize().getWidth(),
(float) page.getClientSize().getHeight());

//draw paragraph on the page
PdfLayoutResult layoutResult = widget.draw(page, rect, layout);
return layoutResult;
}
public static void drawImage(PdfPageBase page, PdfImage image, float x, float y) {

//draw image on the page
page.getCanvas().drawImage(image, x, y);
}
}

Output




Friday, 20 November 2020

How to replace text in a Word document in Java

Introduction

This article will mainly introduce how to replace text in a Word document using Java code. According to different requirements, there will be divided into three aspects to demonstrate it as follows.

l  Replace all matched text with new text

l  Replace the first matched text with new text

l  Replace all matched text with an image

The third-party library I used in this tutorial is Free Spire.Doc for Java. It is a free and professional Java API that enables Java applications to create, manipulate, convert and print Word documents without using Microsoft Office.

Before typing codes, please make sure that the Jar file located at Free Spire.Doc for Java is inserted in your project. If you’re creating a Maven project, just add the following configurations to the pom.xml file.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
Or you can download the package from the E-iceblue website, unzip it and find Spire.Doc.jar in the
“lib” folder. Finally manually add it to your project.
Using the code

Replace all matched text with new text
import com.spire.doc.*;
public class ReplaceTextWithNewText {
public static void main(String[] args) {
//Load the Word document
Document document = new Document("C:\\Users\\Test1\\Desktop\\Sample.docx");

//Replace the specified text with new text
document.replace("society", "NewText", false, true);

//Save the document
document.saveToFile("output/ReplaceAllMatchedText.docx", FileFormat.Docx_2013);
}
}

Output


Replace the first matched text with new text

import com.spire.doc.*;
public class ReplaceFirstText {
public static void main(String[] args) {
//Load the Word document
Document document = new Document("C:\\Users\\Test1\\Desktop\\Sample.docx");

//Set to replace only the first occurrence of the specified text
document.setReplaceFirst(true);

//Replace with new text
document.replace("Society", "NewText", false, true);

//Save the document
document.saveToFile("output/ReplaceFirstMatchedText.docx", FileFormat.Docx_2013);
}
}

Output


Replace all matched text with an Image

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
public class ReplaceTextWithImage {
public static void main(String[] args) {
//Load a sample Word file
Document document = new Document();
document.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");

//Find the string 'E-iceblue' in the document
TextSelection[] selections = document.findAllString("society", true, true);

//Replace the string with an image
int index = 0;
TextRange range = null;
for (Object obj : selections) {

TextSelection textSelection = (TextSelection)obj;
DocPicture pic = new DocPicture(document);
pic.loadImage("C:\\Users\\Test1\\Desktop\\Image.png");
range = textSelection.getAsOneRange();
index = range.getOwnerParagraph().getChildObjects().indexOf(range);
range.getOwnerParagraph().getChildObjects().insert(index,pic);
range.getOwnerParagraph().getChildObjects().remove(range);
}

//Save the document
document.saveToFile("output/ReplaceTextWithImage.docx", FileFormat.Docx_2013);
}
}

Output


Conclusion

In addition to replacing text, Free Spire.Doc for Java supports numerous functions of manipulating

Word documents. If there is any problem about codes or installation steps, please make a note on the

Comment or Forum.

 


Monday, 16 November 2020

Create an Excel file in Java using Free API

An Excel file is typically used to organize, format and calculate data with formulas and functions. In Java, there is no direct API to write, read or manipulate Microsoft Excel documents, so we have to rely on the third-party library called Free Spire.XLS for Java. In this article, I’ll show you how to create an Excel file and how to write data in it using the Java library.

Spire.XLS for Java Library

Spire.XLS for Java is a professional Java Excel API that enables developers to create, manipulate, convert and print Excel worksheets without using Microsoft Excel.

Add Spire.Xls.jar as dependency

If you are working on a Maven project, you can include the dependency in pom.xml file using this:

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

If you are not using Maven, then you can download the package from Spire.XLS for Java download

page. Include Spire.Xls.jar to run the sample code given in this tutorial.

Create an Excel file in Java

In the following program, Spire.XLS for Java library provides the class named Workbook to create a blank file.

import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;

public class CreateAnExcelFile {
public static void main(String[] args) {
//Create an instance of Workbook class
Workbook workbook = new Workbook();

//Save the file to the specified location
workbook.saveToFile("output/ABlankFile.xlsx", ExcelVersion.Version2010);

}
}

Insert Data in the Excel file

Usually, it is not enough that create a blank excel file only. We need to insert some data in the worksheet.

Let’s see how to insert data from DataTable in an excel file through the library.

import com.spire.data.table.*;
import com.spire.xls.*;

public class InsertData {
public static void main(String[] args) throws Exception {
//Load an Excel file
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\ABlankFile.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Set name for the first worksheet
sheet.setName("Country List");
//Create a DataTable object
DataTable dataTable = new DataTable();
dataTable.getColumns().add("No.", Integer.class);
dataTable.getColumns().add("Name", String.class);
dataTable.getColumns().add("Capital", String.class);
//Create rows and add data
DataRow dr = dataTable.newRow();
dr.setInt(0,1);
dr.setString(1,"Indonesia");
dr.setString(2,"Jakarta");
dataTable.getRows().add(dr);
dr = dataTable.newRow();
dr.setInt(0,2);
dr.setString(1,"Bangladesh");
dr.setString(2,"Dhaka");
dataTable.getRows().add(dr);
dr = dataTable.newRow();
dr.setInt(0,3);
dr.setString(1,"Mexican");
dr.setString(2,"Mexico City");
dataTable.getRows().add(dr);
dr = dataTable.newRow();
dr.setInt(0,4);
dr.setString(1,"China");
dr.setString(2,"Beijing");
dataTable.getRows().add(dr);
//Import the two columns of the data table to worksheet
DataColumn[] columns={dataTable.getColumns().get(1),dataTable.getColumns().get(2)};
sheet.insertDataColumns(columns, true, 1, 1);

//Save the Excel file
String result = "output/importDataFromDataColumn.xlsx";
workbook.saveToFile(result, ExcelVersion.Version2013);

}
}

Output


Conclusion

In addition to creating an Excel file and inserting data in it, Spire.XLS for Java supports numerous functions

to manipulate Excel files, such as create, read, edit, convert and print Excel worksheets, find andreplace data,

create charts, create auto filters, read and write hyperlinks, merge/unmerge cells and files, group/ungroup rows

and columns, freeze/unfreeze Panes, encrypt/decrypt Excel workbooks etc.


Wednesday, 11 November 2020

Create SmartArt graphics in PowerPoint and extract text from them in Java

SmartArt is a useful tool in PowerPoint which allows converting textual data into predefined graphics. In this article, I’ll show you how to create SmartArt graphics in PowerPoint and extract text from them in Java programmatically.

The Java API I used in this tutorial is FreeSpire.Presentation for Java. It is a professional API that enables developers to create, read, convert and print PowerPoint documents in Java Applications. Meanwhile, as an independent Java library, it doesn't need Microsoft PowerPoint to be installed on system.

BEFORE CODING

Before coding, please import Spire.Presentation.jar as reference in your project. If you are creating a Maven project, you can easily add the jar dependency by adding the following configurations to the pom.xml.

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.presentation.free</artifactId>
        <version>3.9.0</version>
    </dependency>

</dependencies>

The screenshot below is showed what it finally looks like:


USING THE CODE

Create SmartArt graphics

In the following code snippets, I create two SmartArt graphics: one is a default SmartArt, and the other

is a customized SmartArt. In the process of creating a SmartArt, we can set its location, color type, style

type and insert text in it.

import com.spire.presentation.*;

import com.spire.presentation.diagrams.*;

public class AddSmartArt {
   
public static void main(String[] args) throws Exception {
       
//Create a PowerPoint file, and get the first slide
       
Presentation ppt = new Presentation();
        ISlide slide =ppt.getSlides().get(
0);

       
//Insert the first default SmartArt
       
ISmartArt smartArt1 = slide.getShapes().appendSmartArt(50,50,350,350, SmartArtLayoutType.BASIC_CYCLE);//Insert the SmartArt into the specific location
       
smartArt1.setColorStyle(SmartArtColorType.COLORFUL_ACCENT_COLORS_4_TO_5);//Set the SmartArt color type
       
smartArt1.setStyle(SmartArtStyleType.INTENCE_EFFECT);//Set the SmartArt style type
       
ISmartArtNode smartArtNode1 = smartArt1.getNodes().get(0);         smartArtNode1.getTextFrame().setText("Information");//Gain the default nodes, and add relevant contents
       
smartArt1.getNodes().get(1).getTextFrame().setText("Communication");
        smartArt1.getNodes().get(
2).getTextFrame().setText("Analysis");
        smartArt1.getNodes().get(
3).getTextFrame().setText("Optimization");
        smartArt1.getNodes().get(
4).getTextFrame().setText("Execution");
       
//Insert the second SmartArt, and customize the node contents
       
ISmartArt smartArt2 = slide.getShapes().appendSmartArt(400,200,200,200,SmartArtLayoutType.BASIC_RADIAL);
        smartArt2.setColorStyle(SmartArtColorType.
DARK_2_OUTLINE);//set the style of the SmartArt
       
smartArt2.setStyle(SmartArtStyleType.MODERATE_EFFECT);//set the color of the SmartArt
        //Remove all default nodes
       
for (Object a : smartArt2.getNodes()) {
           smartArt2.getNodes().removeNode((ISmartArtNode) a);
        }
       
//Add a parent node
       
ISmartArtNode node2 = smartArt2.getNodes().addNode();
       
//Add three child nodes
       
ISmartArtNode node2_1 = node2.getChildNodes().addNode();
        ISmartArtNode node2_2 =node2.getChildNodes().addNode();
        ISmartArtNode node2_3 =node2.getChildNodes().addNode();
       
//add text to each node and set the font size
       
node2.getTextFrame().setText("Living Creature");
        node2.getTextFrame().getTextRange().setFontHeight(
16f);
        node2_1.getTextFrame().setText(
"Animal");
        node2_1.getTextFrame().getTextRange().setFontHeight(
14f);
        node2_2.getTextFrame().setText(
"Plant");
        node2_2.getTextFrame().getTextRange().setFontHeight(
14f);
        node2_3.getTextFrame().setText(
"Microbe");
        node2_3.getTextFrame().getTextRange().setFontHeight(
14f);
       
//Save the file
       
ppt.saveToFile("output/AddSmartArt.pptx",FileFormat.PPTX_2013);
        ppt.dispose();
    }
}

Output


Extract text from SmartArt graphics

Here are some steps to extract text from SmartArt graphics.

Step 1: Load the PowerPoint document which needs to be extracted text

Step 2: Traverse through all the slides of the PPT file and find the SmartArt shapes.

Step 3: Create a new .txt file and insert the extracted text from SmartArt into it.

import com.spire.presentation.*;
import com.spire.presentation.diagrams.ISmartArt;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter; public class ExtractTextFromSmartArt {
   
public static void main(String[] args) throws Exception {
       
//Create a Presentation instance, and load a sample
       
Presentation presentation = new Presentation();
        presentation.loadFromFile(
"C:\\Users\\Test1\\Desktop\\AddSmartArt.pptx");
       
//Create a new .txt file to store the extracted text
       
String result = "output/extractTextOfSmartArt.txt";
        File file=
new File(result);
       
if(file.exists()){
            file.delete();
        }
        file.createNewFile();
        FileWriter fw =
new FileWriter(file,true);
        BufferedWriter bw =
new BufferedWriter(fw);
        bw.write(
"Below is extracted text from SmartArt:" + "\r\n");
       
//Traverse through all the slides of the PPT file and find the SmartArt shapes.
       
for (int i = 0; i < presentation.getSlides().getCount(); i++)
        {
            
for (int j = 0; j < presentation.getSlides().get(i).getShapes().getCount(); j++)
            {
               
if (presentation.getSlides().get(i).getShapes().get(j) instanceof ISmartArt)
                { ISmartArt smartArt = (ISmartArt)presentation.getSlides().get(i).getShapes().get(j);

                   
//Extract text from SmartArt and append to the StringBuilder object
                   
for (int k = 0; k < smartArt.getNodes().getCount(); k++)
                    {
                        bw.write(smartArt.getNodes().get(k).getTextFrame().getText() +
"\r\n");
                    }
                }
            }
        }
        bw.flush();
        bw.close();
        fw.close();
    }
}

Output



Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...