Wednesday, 11 August 2021

Create, Extract and Detect a PDF Portfolio in Java

A PDF Portfolio is a collection of files that are gathered and saved into a PDF container. PDF portfolios can consist of multiple document formats including Word, PDF, Excel, PowerPoint or images, and they behave similarly to zip archives by enabling you to share collections of different documents as one PDF file.

This article will introduce how to create a PDF Portfolio using Java codes, extract files from the PDF Portfolio and detect if a PDF file is a PDF Portfolio. It’s worth mentioning that it needs a third-party library called Spire.PDF for Java to finish the operations above.

Before running codes, we need to create a development environment and then add a Jar file which is located at the “lib” folder of the library to Intellij IDEA. There are two methods we can use to add the Jar to IDEA. One is first getting the package of library from the official website, finding Spire.Pdf.jar in the “lib” folder and finally manually adding it to IDEA. The other is creating a Maven project in IDEA and then typing the following codes in the pom.xml file, finally clicking the button “Import Changes”.

<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.pdf</artifactId>
<version>4.4.5</version>
</dependency>
</dependencies>

RUNNING CODES

Create a PDF Portfolio and add multiple files to it

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;

public class CreatePDFPortfolioWithFiles {
public static void main(String[] args) {
String[] files = new String[] { "C:\\Users\\Test1\\Desktop\\Sample.docx", "C:\\Users\\Test1\\Desktop\\Sample.xlsx",
"C:\\Users\\Test1\\Desktop\\Sample.pdf","C:\\Users\\Test1\\Desktop\\Sample.pptx","C:\\Users\\Test1\\Desktop\\logo.png" };

//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();

for (int i = 0; i < files.length; i++)
{
//Create a PDF Portfolio and add files to it
pdf.getCollection().addFile(files[i]);
}

//Save the result file
pdf.saveToFile("output/PortfolioWithFiles.pdf", FileFormat.PDF);
pdf.dispose();
}
}

Output


Detect if a PDF file is a PDF Portfolio

In this part, the PDF Portfolio including multiple files will be seen as a sample document, and now the following codes will detect if

it is a PDF Portfolio.

import com.spire.pdf.PdfDocument;
public class DetectPortfolio {
public static void main(String[] args) {
//Create a PdfDocument instance
PdfDocument doc = new PdfDocument();
//Load the PDF file
doc.loadFromFile("PortfolioWithFiles.pdf");

//Detect if the PDF is a portfolio
boolean value = doc.isPortfolio();
if (value)
{
System.out.println("The document is a portfolio.");
}
else
{
System.out.println("The document is not a portfolio.");
}
}
}

Output



Extract files from a PDF Portfolio

import com.spire.pdf.PdfDocument;
import com.spire.pdf.attachments.PdfAttachment;
import java.io.*;

public class ExtractFilesFromPDFPortfolio {
public static void main(String[] args) throws IOException {
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Load the PDF file
pdf.loadFromFile("PortfolioWithFiles.pdf");

//Loop through the attachments in the file
for(PdfAttachment attachment : (Iterable<PdfAttachment>)pdf.getAttachments()){
//提取附件
String fileName = attachment.getFileName();
OutputStream fos = new FileOutputStream("extract/" + fileName);
fos.write(attachment.getData());
}
pdf.dispose();
}
}
Output


Monday, 9 August 2021

Add Animations to PowerPoint Slides in Java

Animations are normally used in PowerPoint slides and they are visual effects which make your text or objects in slides come alive, so that they can catch your audience’s attention and help them engage with you and your presentation.

This article will introduce how to add animations to shapes and paragraph text in slides using Java codes with the help of a free third-party library called Free Spire.Presentation for Java.

BEFORE CODING

First of all, you need to create a development environment and then add a Jar file which is located in the “lib” folder of the free library to Intellij IDEA. Finally create a Java class to run the corresponding codes.

You can get the package of the free library from the link. Of course, there is a way that you don’t need to download the package rather than use the following Maven configurations to add the Jar file to IDEA.

<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.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

USING THE CODES

Add an animation to a shape in a PowerPoint slide

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;
import com.spire.presentation.drawing.animation.AnimationEffectType;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class SetAnimationForShape {
public static void main(String[] args) throws Exception {
//create a PowerPoint document
Presentation ppt = new Presentation();
//add a slide
ISlide slide = ppt.getSlides().get(0);

//Add a shape to slide
IAutoShape shape = slide.getShapes().appendShape(ShapeType.CUBE, new Rectangle2D.Double(50, 150, 150, 150));
shape.getFill().setFillType(FillFormatType.SOLID);
shape.getFill().getSolidColor().setColor(Color.orange);
shape.getShapeStyle().getLineColor().setColor(Color.white);

//Add animation to the shape
slide.getTimeline().getMainSequence().addEffect(shape, AnimationEffectType.FADED_SWIVEL);

//save the document
ppt.saveToFile("output/AddAnimationToShape.pptx", FileFormat.PPTX_2013);
}
}
Output

Add an animation to paragraph text in a PowerPoint slide

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;
import com.spire.presentation.drawing.animation.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;

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

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

//Add a shape to the slide
IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Double(150, 150, 450, 100));
shape.getFill().setFillType(FillFormatType.
SOLID);
shape.getFill().getSolidColor().setColor(Color.
gray);
shape.getShapeStyle().getLineColor().setColor(Color.
white);
shape.appendTextFrame(
"This demo shows how to apply animation on paragraph in PPT document.");

//Add animation effect to the first paragraph in the shape
AnimationEffect animation = shape.getSlide().getTimeline().getMainSequence().addEffect(shape, AnimationEffectType.FLOAT);
animation.setStartEndParagraphs(
0, 0);

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

output




Wednesday, 4 August 2021

[Java] Change the Font Color of Paragraph Text in Word

Generally speaking, the font color in Word documents is black by default. However, in order to make some special or important contents – for example, notices in instruction document – more obvious so that readers can easily pay more attention on them, we can change the black font to other colors, such as green, red, yellow.

This article will demonstrate how to change the font color of specified paragraph text in a Word document using Java codes with the help of a free third-party library called Free Spire.Doc for Java.

DEVELOPMENT ENVIRONMENT

Before running codes, we need to create a development environment and add a Jar file called Spire.Doc.jar to Intellij IDEA. The jar file can be found in the “lib” folder of the free library, and then follow the steps listed in the screenshot below.


Actually, there is another method to add the Jar file to IDEA. Create a Maven project in IDEA, and then write down the following codes in the pom.xml file. Finally, click the button “Import Changes”.

<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.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

RUNNING THE CODE

Here is a Word sample document whose font color is black, and now I’ll use Java codes to change the 

font color of second paragraph text to green and third paragraph text to blue.

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;
import java.awt.*;

public class ChangeFontColor {
public static void main(String[] args) {
//Create a Document instance
Document doc = new Document();
//Load the Word document
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");

//Get the first section and second paragraph
Section section = doc.getSections().get(0);
Paragraph p1 = section.getParagraphs().get(1);

//Iterate through the childObjects of the second paragraph
for (int i = 0; i < p1.getChildObjects().getCount(); i ++)
{
//Change font color of the text in the second paragraph
if ( p1.getChildObjects().get(i) instanceof TextRange)
{
TextRange tr = (TextRange) p1.getChildObjects().get(i);
tr.getCharacterFormat().setTextColor(Color.green);
}
}

//Get the third paragraph
Paragraph p2 = section.getParagraphs().get(2);

//Iterate through the childObjects of the third paragraph
for (int j = 0; j < p2.getChildObjects().getCount(); j ++)
{
//Change font color of the text in the third paragraph
if ( p2.getChildObjects().get(j) instanceof TextRange)
{
TextRange tr = (TextRange) p2.getChildObjects().get(j);
tr.getCharacterFormat().setTextColor(Color.blue);
}
}

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

Output




Friday, 30 July 2021

Insert an OLE object to an Excel worksheet using Java codes

Recently, I find a free third-party library called Free Spire.Office for Java and it supports inserting Word/Excel/PowerPoint/PDF documents as linked object or embedded object into Excel worksheets. This article will show how to insert a Word document as an embedded object into Excel using Java codes with the help of it.

DEPENDENCY

First of all, we need to download and install JDK and Intellij IDEA to create a development environment. Then we get the package of the free library from the official website, find Spire.Xls.jar in the “lib” folder. Finally, manually add it to IDEA.

Besides, there is another way to add the Jar file, which is using the following codes in the Maven 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.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

USING THE CODE

import com.spire.xls.*;
import com.spire.xls.core.IOleObject;
import com.spire.doc.*;
import com.spire.doc.documents.ImageType;
import java.awt.image.BufferedImage;

public class InsertOLE {
public static void main(String[] args) {

//Load the Excel document
Workbook workbook = new Workbook();
workbook.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.xlsx");
//Get the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);

//Generate image
BufferedImage image = GenerateImage("C:\\Users\\Test1\\Desktop\\Test.docx");
//insert OLE object
IOleObject oleObject = worksheet.getOleObjects().add("C:\\Users\\Test1\\Desktop\\Test.docx", image, OleLinkType.Embed);
oleObject.setLocation(worksheet.getCellRange(
"B4"));
oleObject.setObjectType(OleObjectType.
ExcelWorksheet);
//Save the file
workbook.saveToFile("output/InsertOLE.xlsx", ExcelVersion.Version2010);
}

private static BufferedImage GenerateImage(String fileName) {

//Load the sample word document
Document document = new Document();
document.loadFromFile(fileName);

//Save the first page of word as an image
BufferedImage image = document.saveToImages(0, ImageType.Bitmap);
return image;
}
}

Output






Monday, 26 July 2021

Find and Highlight Text in PDF using Java codes

There is no doubt that highlighting a text using a color in a PDF file is a great strategy for reading and retaining key information, which can help in bringing important information immediately to the reader's attention. In this article, I’ll introduce how to find specified text and then highlight it using Java codes with the help of a free third-party library called FreeSpire.PDF for Java.

DEPENDENCY

In order to finish the operation mentioned above using Java codes, we need to create a development environment – downloading and installing JDK 1.8.0 and Intellij IDEA 2019. Furthermore, get the package of Free Spire.PDF for Java from the official website, and find Spire.Pdf.jar in the “lib” folder. Finally, add the Jar file to IDEA.

Of course, you can directly add the Jar file by using the following Maven configurations.

<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.pdf.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

USING THE CODE

Actually, Free Spire.PDF for Java supports finding the specified text through two methods. One is

directly pointing out the content of text string, the other is defining a pattern and finding results that

match the pattern.

Find and Highlight Text by Text String

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.general.find.PdfTextFind;
import java.awt.*;

public class FindAndHighlightTextString {
public static void main(String[] args) {
//Load the PDF file
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\Test.pdf");
PdfTextFind[] result;

//Find and highlight the string “New Zealand” in every PDF page
for (PdfPageBase page : (Iterable<PdfPageBase>) pdf.getPages()) {
result = page.findText("cashless society",false,false).getFinds();
for (PdfTextFind find : result) {
find.applyHighLight(Color.yellow);
}
}

//Save the file
pdf.saveToFile("output/FindAndHighlightText.pdf");
}
}

Output


Find and Highlight Text by Regular Expression

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.general.find.PdfTextFind;
import java.awt.*;

public class FindByRegularExpression {
public static void main(String[] args) {
//Load a PDF document
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\Test.pdf");

//Create an object of PdfTextFind collection
PdfTextFind[] results;

//Loop through the pages
for (Object page : (Iterable) pdf.getPages()) {
PdfPageBase pageBase = (PdfPageBase) page;

//Define a regular expression
String pattern = "\\#\\w+\\b";

//Find all results that match the pattern
results = pageBase.findText(pattern).getFinds();

//Highlight the search results with yellow
for (PdfTextFind find : results) {
find.applyHighLight(Color.yellow);
}
}

//Save to file
pdf.saveToFile("output/FindTextByRegularExpression.pdf");
}
}

Output



Tuesday, 20 July 2021

[Java] Get the position of text in PowerPoint slides

Here is a PowerPoint slide and there is a English word called test in it. Now I want to get its location using Java codes. Through a lot of tests, I used a free third-party library called Free Spire.Presentation for Java to do it.


About Free Spire.Presentation for Java

Free Spire.Presentation for Java is a professional PowerPoint API that enables developers to create, read, write, convert and save PowerPoint documents in Java Applications. As an independent Java library, you only need to it without installing Microsoft PowerPoint on the system.

Dependency

First of all, we need to create a development environment by downloading and installing JDK and Intellij IDEA. Then get the package of library from the E-iceblue official website, find Spire.Presentation.jar in the “lib” folder. Finally, manually add it to IDEA through several steps as the following screenshot shows.

Of course, there is the other method to add it to IDEA. Create a Maven project in IDEA, and type the following codes in the pom.xml file. Finally, click the button “Import Changes”.

<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.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
Using the code

Free Spire.Presentation for Java not only supports getting the x and y coordinates of the location relative

to slide, but also can print out the x and y coordinates of the location relative to shape.

import com.spire.presentation.IAutoShape;
import com.spire.presentation.ISlide;
import com.spire.presentation.Presentation;

import java.awt.geom.Point2D;

public class GetPositionOfText {
public static void main(String[] args) throws Exception {
//Create a Presentation instance
Presentation ppt = new Presentation();
//Load a PowerPoint document
ppt.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");

//Get the first slide
ISlide slide = ppt.getSlides().get(0);
//Get the first shape
IAutoShape shape = (IAutoShape)slide.getShapes().get(0);
//Get location of text in the shape
Point2D location =shape.getTextFrame().getTextLocation();

//Print out the x and y coordinates of the location relative to slide
String point1="Text's position relative to Slide: x= "+location.getX()+" y = "+location.getY();
System.out.println(point1);

//Print out the x and y coordinates of the location relative to shape
String point2 = "Text's position relative to shape: x= " + (location.getX() - shape.getLeft()) + " y = " + (location.getY() - shape.getTop());
System.out.println(point2);
}
}

Output




Friday, 16 July 2021

Add, Delete and Reply to Comments in Word documents with Java codes

Adding comments in Word is a great way to mark up your documents without having to directly edit its content, and you can add comments to anything in Word, including text, images, charts, tables, etc. If there are comments on the document already, replying to them lets you have a discussion with others, even when you're not all in the document at the same time.

This article will introduce how to add a comment to the specified paragraph or text in Word, reply to the comment and then delete it using Java codes. It’s worth mentioning that the operation mentioned above need to be done with the help of a third-party library called Free Spire.Doc for Java.

BEFORE CODING

First of all, we need to create a development environment by installing JDK and Intellij IDEA, and then add a Jar file called Spire.Doc.jar which is in the library to IDEA. You can get the Jar file through the link or directly reference it by using the following Maven configuration.

<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.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

USING THE CODE

Add a comment to a specified paragraph in Word

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.Comment;

public class AddCommentToParagraph {
public static void main(String[] args) {
//load a word document
Document document= new Document("C:\\Users\\Test1\\Desktop\\Sample.docx");

//Get the fifth paragraph of first section
Section section = document.getSections().get(0);
Paragraph paragraph = section.getParagraphs().get(4);

//Insert a new comment to the paragraph
Comment comment = paragraph.appendComment("The definition of Cashless Society");
comment.getFormat().setAuthor("Tina");
comment.getFormat().setInitial("CM");

//save the file
document.saveToFile("output/AddCommentToParagraph.docx", FileFormat.Docx);
}
}

Output


Add a comment to specified text in Word

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.CommentMark;
import com.spire.doc.documents.CommentMarkType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.Comment;

public class AddCommentToText {
public static void main(String[] args) {
//Load a Word document
Document doc = new Document();
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");

//Find the text string in the document
TextSelection[] finds = doc.findAllString("a cashless society is one in which financial transactions " +
"are handled through the transfer of digital information instead of physical money in the form of banknotes " +
"or coins", false, true);

for (TextSelection find : finds) {
//Create comment start mark and comment end mark
CommentMark commentmarkStart = new CommentMark(doc);
commentmarkStart.setType(CommentMarkType.Comment_Start);
CommentMark commentmarkEnd = new CommentMark(doc);
commentmarkEnd.setType(CommentMarkType.Comment_End);

//Create a comment
Comment comment = new Comment(doc);
comment.getBody().addParagraph().setText("The definition of Cashless Society");
comment.getFormat().setAuthor("Tina");

//Find the paragraph where the string is located in
Paragraph para = find.getAsOneRange().getOwnerParagraph();
//Get the index of the string in the paragraph
int index = para.getChildObjects().indexOf(find.getAsOneRange());

//Add the comment to the paragraph
para.getChildObjects().add(comment);
//Insert the comment start mark and comment end mark to the paragraph based on the index
para.getChildObjects().insert(index, commentmarkStart);
para.getChildObjects().insert(index + 2, commentmarkEnd);
}

//Save the resulting document
doc.saveToFile("output/AddCommentToText.docx",FileFormat.Docx_2013);
}
}
Output

Reply to a comment in Word

import com.spire.doc.*;
import com.spire.doc.FileFormat;
import com.spire.doc.fields.*;

public class ReplyToComment {
public static void main(String[] args) {
//load a word document
Document document= new Document("C:\\Users\\Test1\\Desktop\\AddCommentToParagraph.docx");

//Get the first comment
Comment comment1 = document.getComments().get(0);

//add the new comment as a reply to the selected comment.
Comment replyComment1 = new Comment(document);
replyComment1.getFormat().setAuthor("Emma");
replyComment1.getBody().addParagraph().appendText("You never need to use paper bills or coins in a Cashless Society");
comment1.replyToComment(replyComment1);

//save the file
document.saveToFile("output/ReplyToComment.docx", FileFormat.Docx);
}
}

Output


Delete a specified comment in Word

import com.spire.doc.*;
import com.spire.doc.FileFormat;

public class DeleteComment {
public static void main(String[] args) {
//load a word document
Document document= new Document("C:\\Users\\Test1\\Desktop\\ReplyToComment.docx");

//remove the first comment
document.getComments().removeAt(0);

//save the file.
document.saveToFile("output/DeleteComment.docx", FileFormat.Docx);
}
}

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...