Thursday, 25 February 2021

Set an expiration date for a PDF document in Java

In daily work, in order to protect our document from being disclosed, we can set an expiration data for it. The document can’t be opened once the expiration date has gone. Today, I’ll introduce how to set an expiration date or a PDF document in Java using a free API called Free Spire.PDF for Java.

About Free Spire.PDF for Java

Free Spire.PDF for Java is a PDF API that enables Java applications to read, write and save PDF documents without using Adobe Acrobat. Using this Java PDF library, developers and programmers can implement rich capabilities to create PDF files from scratch or process existing PDF documents entirely on Java applications (J2SE and J2EE).

Dependency

First of all, please download the latest version of Free Spire.PDF for Java from the link, and add Spire.Pdf.jar to your project as a dependency.

Of course, if you are using maven, you can directly add the following code to your project's pom.xml file.

<repositories>
<repository>
<id>com.e-iceblue</id>
<url>http://repo.e-iceblue.cn/repository/maven-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

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

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

//Load a PDF file
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

//Set expiration date and warning information,and then close the document through JavaScript
String javaScript = "var rightNow = new Date();"
+ "var endDate = new Date('February 26, 2021 14:40:59');"
+ "if(rightNow.getTime() > endDate)"
+ "app.alert('This document is no longer valid, please contact us for a updated one.',1);"
+ "this.closeDoc();";

//Create a PdfJavaScriptAction object based on the javascript
PdfJavaScriptAction js = new PdfJavaScriptAction(javaScript);

//Set PdfJavaScriptAction as the AfterOpenAction
doc.setAfterOpenAction(js);

//Save to file
doc.saveToFile("output/ExpirationDate.pdf", FileFormat.PDF);
}
}

Output



Wednesday, 24 February 2021

Add multiple image watermarks to Word documents in Java

I introduced how to add multiple text watermarks to a Word document in Java before. Today, this tutorial will demonstrate how to add multiple image watermarks to a Word document in Java.

Dependency

It’s worth mentioning that I used a free third-party library called Free Spire.doc for Java to achieve the effect I want. Before typing codes, you need to add the jar file in the library to IDEA. Please click the link to download the product package and manually add Spire.doc.jar to IDEA, or directly reference it using the following Maven configurations.

<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>
Using the code

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.HeaderFooter;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextWrappingStyle;
import com.spire.doc.fields.DocPicture;

public class Watermark {
public static void main(String[] args) {
//Load the sample file
Document doc=new Document();
doc.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.docx");
//Load the image
DocPicture picture = new DocPicture(doc);
picture.loadImage(
"C:\\Users\\Test1\\Desktop\\Image.png");

//Set the text wrapping style
picture.setTextWrappingStyle(TextWrappingStyle.Behind);

for (int n = 0; n < doc.getSections().getCount(); n++) {
Section section = doc.getSections().get(n);
//Get the head of section
HeaderFooter header = section.getHeadersFooters().getHeader();
Paragraph paragrapg1;
if(header.getParagraphs().getCount()>0){
paragrapg1=header.getParagraphs().get(
0);

}
else {
//Add the header to the paragraph
paragrapg1 = header.addParagraph();
}

for (int p = 0; p < 3; p++) {

for (int q = 0; q < 2; q++) {
//copy the image and add it to many places
picture = (DocPicture)picture.deepClone();
picture.setVerticalPosition(
100 + 200 * p);
picture.setHorizontalPosition(
50 + 210 * q);
paragrapg1.getChildObjects().add(picture);
}
}
}
//Save the document to file
doc.saveToFile("output/AddMultipleImageWatermark.docx", FileFormat.Docx_2013);
}
}

Output




Sunday, 21 February 2021

How to merge Excel files using a free Java API

In the process of manipulating Excel files, it is a lot easier to process data in a single file instead of switching between numerous sources. In this article, I’m going to introduce how to copy data from one worksheet into another worksheet in the same Excel file, and how to copy sheets from multiple Excel workbooks into one workbook.

Dependency

I used a free Java API called Free Spire.XLS for Java in this tutorial. Before running codes, we need to insert the Jar file in the library into IDEA. You can download it from the website or directly reference it using the following Maven configurations.

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

How to copy data from one worksheet to another worksheet

I have an Excel file which includes two worksheets as below. Now I want to copy the data and its format

in the second worksheet into the first worksheet.


Use the following codes to achieve the effect I mentioned above.

import com.spire.xls.*;

public class MergeWorksheets {
public static void main(String[] args) {
//Create a workbook
Workbook workbook = new Workbook();

//Load a Excel file including two worksheets
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

//Get the first worksheet
Worksheet sheet1 = workbook.getWorksheets().get(0);

//Get the second worksheet
Worksheet sheet2 = workbook.getWorksheets().get(1);

//Copy the data and format in the second worksheet into the first worksheet
sheet2.getAllocatedRange().copy(sheet1.getRange().get(sheet1.getLastRow() +1, 1));

//Save the resulting document
workbook.saveToFile("output/MergeWorksheets.xlsx", ExcelVersion.Version2013);
}
}

Output


How to copy sheets from multiple Excel workbooks into one workbook

In addition to merging worksheets, Free Spire.XLS for Java supports merging multiple Excel files into

a single file. The screenshot of the original files is shown as below.


Use the following codes to merge several Excel files into a single file.

import com.spire.xls.*;
public class MergeFiles {
public static void main(String[] args) {
//Input the two Excel files which are used to merge into a file
String[] inputFiles = new String[]{"C:\\Users\\Test1\\Desktop\\file1.xlsx","C:\\Users\\Test1\\Desktop\\file2.xlsx"};

//Create a new workbook
Workbook newBook = new Workbook();

//Clear all worksheets
newBook.getWorksheets().clear();

//Create another workbook
Workbook tempBook = new Workbook();

//Loop through the two Excel files, and copy worksheets in each Excel file into the new workbook
for (String file : inputFiles)
{
tempBook.loadFromFile(file);
for (Worksheet sheet : (Iterable<Worksheet>)tempBook.getWorksheets())
{
newBook.getWorksheets().addCopy(sheet, WorksheetCopyType.CopyAll);
}
}

//Save the resulting document
newBook.saveToFile("output/MergeFiles.xlsx", ExcelVersion.Version2013);

}
}

Output



Thursday, 18 February 2021

[Java] Add, Read and Delete Speaker Notes in a PowerPoint document

Speaker Notes in PowerPoint slides are a short paragraph that reminds the speaker of the contents of the current slide in the slide-show, and they are an important tool in ensuring a smooth presentation for your work. The most interesting thing about them is the fact that they are not viewable by the audience during a presentation. This article will show you how to add, read and delete speaker notes using Java codes.

Using the tool

In this tutorial, I used a free third-party library called FreeSpire.Presentation for Java. It is a professional PowerPoint API that enables developers to create, edit, read, convert and save PowerPoint documents in Java Applications without installing Microsoft PowerPoint.

Before typing codes, you need to add the Jar file in the library to your project. You can download it from the link, and manually add it to IDEA, or directly reference it using the following Maven configuration.

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

Using the code

Add Speaker Notes

import com.spire.presentation.*;
public class AddSpeakerNotes {
public static void main(String[] args) throws Exception {
//Load the PowerPoint document
Presentation ppt = new Presentation();
ppt.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");

//Get the first slide
ISlide slide = ppt.getSlides().get(0);
//Add note slide
NotesSlide notesSlide = slide.addNotesSlide();

//Add a paragraph to the note slide
ParagraphEx paragraph = new ParagraphEx();
paragraph.setText("Tips for making effective presentations:");
notesSlide.getNotesTextFrame().getParagraphs().append(paragraph);
//Set the bullet type and style for the paragraph
notesSlide.getNotesTextFrame().getParagraphs().get(0).setBulletType(TextBulletType.NUMBERED);
notesSlide.getNotesTextFrame().getParagraphs().get(0).setBulletStyle(NumberedBulletStyle.BULLET_ARABIC_PERIOD);

//Add a paragraph to the note slide
paragraph = new ParagraphEx();
paragraph.setText("Use the slide master feature to create a consistent and simple design template.");
notesSlide.getNotesTextFrame().getParagraphs().append(paragraph);
//Set the bullet type and style for the paragraph
notesSlide.getNotesTextFrame().getParagraphs().get(2).setBulletType(TextBulletType.NUMBERED);
notesSlide.getNotesTextFrame().getParagraphs().get(2).setBulletStyle(NumberedBulletStyle.BULLET_ARABIC_PERIOD);

//Add a paragraph to the note slide
paragraph = new ParagraphEx();
paragraph.setText("Simplify and limit the number of words on each screen.");
notesSlide.getNotesTextFrame().getParagraphs().append(paragraph);
//Set the bullet type and style for the paragraph
notesSlide.getNotesTextFrame().getParagraphs().get(3).setBulletType(TextBulletType.NUMBERED);
notesSlide.getNotesTextFrame().getParagraphs().get(3).setBulletStyle(NumberedBulletStyle.BULLET_ARABIC_PERIOD);

//Add a paragraph to the note slide
paragraph = new ParagraphEx();
paragraph.setText("Use contrasting colors for text and background.");
notesSlide.getNotesTextFrame().getParagraphs().append(paragraph);
//Set the bullet and style type for the paragraph
notesSlide.getNotesTextFrame().getParagraphs().get(4).setBulletType(TextBulletType.NUMBERED);
notesSlide.getNotesTextFrame().getParagraphs().get(4).setBulletStyle(NumberedBulletStyle.BULLET_ARABIC_PERIOD);

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

Output


Read Speaker Notes

import com.spire.presentation.*;
import java.io.FileWriter;

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

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

//Get the content of notes from note slide
StringBuilder buffer = new StringBuilder();
String notes = slide.getNotesSlide().getNotesTextFrame().getText();
buffer.append(notes);

//Save to .txt file
FileWriter writer = new FileWriter("output/ReadSpeakerNotes.txt");
writer.write(buffer.toString());
writer.flush();
writer.close();
}
}

Output



Delete Speaker Notes

import com.spire.presentation.*;

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

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

//Delete all speaker notes from the note slide
slide.getNotesSlide().getNotesTextFrame().getParagraphs().clear();

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

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