Sunday, 25 April 2021

Protect PowerPoint Presentations in Java

As we all know, unless we protect PowerPoint documents, anyone with access to the file can open, copy and edit the contents. Here I’ll introduce how to protect PowerPoint presentations with a password, set the presentation slides ready only, modify the password of encrypted file and decrypt a protected file.

It’s worth mentioning that the operations above can be realized by using Java codes without using Microsoft PowerPoint. In this tutorial, I used a free third-party library called Free Spire.Presentation for Java.

Before running Java codes, you need to add a Jar file in the library to IDEA. You can download a package from the link, unzip it and find the Jar file in the “lib” folder. Or you can refer to it by using the following configuration in Maven 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>

Protect a PowerPoint File with a Password

The protection using password will lock your PowerPoint files. Only someone who knows the password will be able to open and edit it.

 import com.spire.presentation.*;


public class Encrypt {
public static void main(String[] args) throws Exception {
//create a Presentation object and load a PowerPoint file
Presentation presentation = new Presentation();
presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");

//encrypt the document with a password
presentation.encrypt("abc123");

//save the resulting document
presentation.saveToFile("output/encrypt_output.pptx", FileFormat.PPTX_2013);
presentation.dispose();
}
}

Output


Modify the Password of an Encrypted File

import com.spire.presentation.*;
public class ModifyPassword {
public static void main(String[] args) throws Exception {
//create a Presentation object and load a PowerPoint file including the original password
Presentation presentation = new Presentation();
presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\encrypt_output.pptx", "abc123");

//remove the encryption
presentation.removeEncryption();

//protect the document by setting a new password
presentation.protect("def456");

//save the resulting document
presentation.saveToFile("output/modifyPasswordOfEncryptedPPT.pptx", FileFormat.PPTX_2013);
}
}

After running Java codes above, you need to enter the new password to open and edit the PowerPoint file, or you can choose the “Read Only” to open the file but can’t edit it.

Set the Presentation Slides Read Only

import com.spire.presentation.*;
public class ReadOnly {
public static void main(String[] args) throws Exception {
//create a Presentation object and load a PowerPoint file
Presentation presentation = new Presentation();
presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");

//Protect the document with the password
presentation.protect("hij789");

//save the file
presentation.saveToFile("output/setDocumentReadOnly_output.pptx", FileFormat.PPTX_2013);
presentation.dispose();
}
}

Output


Decrypt a Password-Protected PowerPoint File

import com.spire.presentation.*;

public class RemoveEncryption {
public static void main(String[] args) throws Exception {
//create a Presentation object and load a PowerPoint file
Presentation presentation = new Presentation();
presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\encrypt_output.pptx", "abc123");

//remove encryption.
presentation.removeEncryption();

//save the resulting document
presentation.saveToFile("output/removeEncryption.pptx", FileFormat.PPTX_2013);
}
}


Thursday, 22 April 2021

[Java] Search Text and Add Hyperlinks in Word Documents

Requirement

Now I have a Word document as below and it mainly introduces the Java computer language. My requirement is that I want to add the hyperlink called https://en.wikipedia.org/wiki/Java_(programming_language) for all “Java” text in this article.

Solution

Obviously, it’ll take a long time to manually add hyperlinks for every text. After testing many third-party libraries, I found one called Free Spire.Doc for Java which can use Java codes to search all matched text “Java” in the article and then add the hyperlink for them all at once. Now I’ll show you how to do it.

Preparation

Before running codes, you need to do some preparations. First, you need to install JDK and IntelliJ IDEA in your computer. The next thing is that download Free Spire.Doc for Java from the link, unzip it and find Spire.Doc.jar in the “lib” folder, finally manually add the jar to IDEA. Of course, here there is an easier way to add the Jar file which is typing the following configuration in the Maven 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.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Using the code

Create a Java Class in IDEA, write and run the following codes.

import com.spire.doc.Document;
import com.spire.doc.FieldType;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.FieldMarkType;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.documents.UnderlineStyle;
import com.spire.doc.fields.Field;
import com.spire.doc.fields.FieldMark;
import com.spire.doc.fields.TextRange;
import java.awt.*;

public class Hyperlink {
public static void main(String[] args) {
//Load a Word sample document
Document doc = new Document();
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");
//Find all the matched text
TextSelection[] text = doc.findAllString("Java", false, true);
for (int i =0; i<text.length;i++)
{
//Get the TextRange
TextSelection seletion= text[i];
TextRange tr = seletion.getAsOneRange();
int index = tr.getOwnerParagraph().getChildObjects().indexOf(tr);
//Add hyperlinks to the matched text
Field field = new Field(doc);
field.setCode( "HYPERLINK \"" + "https://en.wikipedia.org/wiki/Java_(programming_language)" + "\"");
field.setType( FieldType.Field_Hyperlink);
tr.getOwnerParagraph().getChildObjects().insert(index, field);
FieldMark fm = new FieldMark(doc, FieldMarkType.Field_Separator);
tr.getOwnerParagraph().getChildObjects().insert(index + 1, fm);
//Set the format of hyperlinks
tr.getCharacterFormat().setTextColor( Color.BLUE);
tr.getCharacterFormat().setUnderlineStyle( UnderlineStyle.Single);
tr.getCharacterFormat().setBold(true);
FieldMark fmend = new FieldMark(doc, FieldMarkType.Field_End);
tr.getOwnerParagraph().getChildObjects().insert(index + 3, fmend);
field.setEnd(fmend);
}
//Save the resulting document
doc.saveToFile("output/SearchTextAndAddHyperlink.docx", FileFormat.Docx_2013);
}
}

Output



Tuesday, 20 April 2021

Split Excel worksheets into multiple files in Java

I introduced how to merge Excel files using a free Java API before. Today this tutorial will demonstrate how to split Excel worksheets into multiple files using the same API. The content is divided into two parts as below according to different requirements.

l  Split several worksheets into multiple Excel files

l  Split a worksheet into multiple Excel files

The free Java API I used is called Free Spire.XLS for Java. Before running codes, you need to add Spire.Xls.jar in the API to IDEA. You can download it from the link, 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.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

Split several worksheets into multiple Excel files

There are two worksheets in an Excel workbook as below. Now I’ll use the following codes to split them into two Excel files, and every file only includes one worksheet of the original workbook.

import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;

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

//Create a Workbook object
Workbook wb = new Workbook();

//Load an Excel document
wb.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

//Declare a Workbook variable
Workbook newWb;

//Declare a String variable
String sheetName;

//Specify the folder path, which is used to store the generated Excel files
String folderPath = "output/";

//Loop through the worksheets in the source file
for (int i = 0; i < wb.getWorksheets().getCount(); i++) {

//Initialize the Workbook object
newWb = new Workbook();

//Remove the default sheets
newWb.getWorksheets().clear();

//Add the the specific worksheet of the source document to the new workbook
newWb.getWorksheets().addCopy(wb.getWorksheets().get(i));

//Get the worksheet name
sheetName = wb.getWorksheets().get(i).getName();

//Save the new workbook to the specified folder
newWb.saveToFile(folderPath + sheetName + ".xlsx", FileFormat.Version2013);
}
}
}

Output


Split a worksheet into multiple Excel files

An Excel workbook includes one worksheet, and now I’ll use the following codes to split it into two Excel files according to the data range.

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

public class SplitWorksheetIntoMultiFiles {
public static void main(String[] args) {
//Create a Workbook object and load the original Excel document
Workbook bookOriginal = new Workbook();
bookOriginal.loadFromFile("C:\\Users\\Test1\\Desktop\\Test.xlsx");

//Get the first worksheet
Worksheet sheet = bookOriginal.getWorksheets().get(0);

//Get the header row
CellRange headerRow1 = sheet.getCellRange(1, 1, 1, 6);
CellRange headerRow2 = sheet.getCellRange(11, 1, 11, 5);
//Get two cell ranges
CellRange range1 = sheet.getCellRange(2, 1, 10, 6);
CellRange range2 = sheet.getCellRange(12, 1, 17, 5);

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

//Copy the header row 1 and range 1 to the new workbook
sheet.copy(headerRow1, newBook1.getWorksheets().get(0), 1, 1, true, false);
sheet.copy(range1, newBook1.getWorksheets().get(0), 2, 1, true, false);

//Copy the column width from the original workbook to the new workbook
for (int i = 0; i < sheet.getLastColumn(); i++) {

newBook1.getWorksheets().get(0).setColumnWidth(i + 1, sheet.getColumnWidth(i + 1));
}

//Save the new workbook to an Excel file
newBook1.saveToFile("output/Vendors_output.xlsx", ExcelVersion.Version2016);

//Copy the header row 2 and range 2 to another workbook, and save it to another Excel file
Workbook newBook2 = new Workbook();
sheet.copy(headerRow2, newBook2.getWorksheets().get(0), 1, 1, true, false);
sheet.copy(range2, newBook2.getWorksheets().get(0), 2, 1, true, false);
for (int i = 0; i < sheet.getLastColumn(); i++) {

newBook2.getWorksheets().get(0).setColumnWidth(i + 1, sheet.getColumnWidth(i + 1));
}
newBook2.saveToFile("output/Country List_output.xlsx", ExcelVersion.Version2016);
}
}

Output



Friday, 16 April 2021

[Java] Add Page Numbers to an Existing PDF document

Page numbers can be used to automatically number each page in documents, and they are usually placed in the header, footer, or side margin. This article will demonstrate how to add page numbers to an existing PDF document at the footer space using a free third-party library called Free Spire.PDFfor Java.

Before running codes, you need to add Spire.Pdf.jar in the library to IDEA. You can download it from the link, or directly refer to 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.pdf.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Using the code

import com.spire.pdf.PdfDocument;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;

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

//create a true type font
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 10));

//get the page size
Dimension2D pageSize = doc.getPages().get(0).getSize();

//declare a float variable
float y = (float) pageSize.getHeight() - 72;

//loop through the pages
for (int i = 0; i < doc.getPages().getCount(); i++) {

//initialize PdfPageNumberField instance
PdfPageNumberField number = new PdfPageNumberField();

//initialize PdfPageCountField instance
PdfPageCountField count = new PdfPageCountField();

//create PdfCompositeField instance
PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.getBlack(), "Page {0} of {1}", number, count);

//set the text alignment within the composite field
compositeField.setStringFormat(new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top));

//get the text size
Dimension2D textSize = font.measureString(compositeField.getText());

//set the position and size of composite field
compositeField.setBounds(new Rectangle2D.Float((float) pageSize.getWidth() - (float) textSize.getWidth() - 80, y, (float) textSize.getWidth(), (float) textSize.getHeight()));

//draw composite filed on PDF page
compositeField.draw(doc.getPages().get(i).getCanvas());
}

//save to another file
doc.saveToFile("output/AddPageNumbers.pdf");
}
}

Output


Tuesday, 13 April 2021

[Java] Creat a Chart Using Excel Data in PowerPoint documents

This tutorial will demonstrate how to create a chart using the data from an existing Excel document in a PowerPoint document. It’s worth mentioning that I used a free third-party library called Free Spire.Office for Java to accomplish the function above.

About Free Spire.Office for Java

Free Spire.Office for Java is a combination of all free Java APIs that are offered by E-iceblue. Developers can use it to perform a wide range of office document operations simply and efficiently within Java applications. Meanwhile, it doesn't require Microsoft Office, Adobe Acrobat or any other third-party libraries to be installed on system.

Add Spire.Office.jar

Before running codes, you need add Spire.Office.jar in the library to IDEA. You can download the package from the link, find the Jar file in the “lib” folder and then manually add it to IDEA. Of course you can directly refer to it by using the following Maven configuration.

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

Using the code

Below is a screenshot of the Excel document:

import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;
import com.spire.presentation.SlideSizeType;
import com.spire.presentation.charts.ChartStyle;
import com.spire.presentation.charts.ChartType;
import com.spire.presentation.charts.IChart;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
import java.awt.geom.Rectangle2D;

public class CreateChartFromExcelData {
public static void main(String[] args) throws Exception {
//Create a Presentation object
Presentation presentation = new Presentation();
presentation.getSlideSize().setType(SlideSizeType.SCREEN_16_X_9);

//Add a clustered column chart to slide
Rectangle2D rect = new Rectangle2D.Float(200, 100, 550, 320);
IChart chart = presentation.getSlides().get(0).getShapes().appendChart(ChartType.COLUMN_CLUSTERED,rect);

//Clear the default dummy data
chart.getChartData().clear(0,0,5,5 );

//Load an existing Excel file to Workbook object
Workbook wb = new Workbook();
wb.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);

//Import data from the sheet to chart table
for (int r = 0; r < sheet.getAllocatedRange().getRowCount(); r++)
{
for (int c = 0; c < sheet.getAllocatedRange().getColumnCount(); c++)
{
chart.getChartData().get(r,c).setValue(sheet.getCellRange(r+1, c+1).getValue2());
}
}

//Add chart title
chart.getChartTitle().getTextProperties().setText("Male/Female Ratio Per Grade");
chart.getChartTitle().getTextProperties().isCentered(true);
chart.getChartTitle().setHeight(25f);
chart.hasTitle(true);

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

//Set the category labels
chart.getCategories().setCategoryLabels(chart.getChartData().get("A2","A4"));

//Set the series values
chart.getSeries().get(0).setValues(chart.getChartData().get("B2","B4"));
chart.getSeries().get(1).setValues(chart.getChartData().get("C2", "C4"));

//Apply built-in chart style
chart.setChartStyle(ChartStyle.STYLE_11);

//Set overlap
chart.setOverLap(-50);

//Set gap width
chart.setGapWidth(200);

//Save to file
presentation.saveToFile("output/CreateChartFromExcelData.pptx", FileFormat.PPTX_2013);
}
}

Output




Friday, 9 April 2021

Print Word documents in Java using a free API

This tutorial will introduce two methods to print word documents using Java codes. In the process of printing documents, you can set the paper size, copies and whether to show print dialog.

I used a free third-party library called Free Spire.Doc for Java in this sample. Before running codes, you need to add Spire.Doc.jar in the library to IDEA. Download the package from the link, and manually add it to IDEA or directly refer to it using the following configuration in the Maven pom.xml.

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

Print Word file

import com.spire.doc.Document;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintFile {
public static void main(String[] args) {
//load a Word document that you want to print
Document document = new Document();
document.loadFromFile(
"C:\\Users\\Administrator\\Desktop\\DocoumentToPrint.docx");

//Create a PrinterJob object
PrinterJob printerJob = PrinterJob.getPrinterJob();

//Create a PageFormat object and set it to the default size and orientation
PageFormat pageFormat = printerJob.defaultPage();

//Return a copy of the Paper object associated with this PageFormat
Paper paper = pageFormat.getPaper();

//Set the imageable area of this Paper
paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

//Set the number of copies
printerJob.setCopies(1);

//Set the Paper object for this PageFormat
pageFormat.setPaper(paper);

//Call painter to render the pages in the specified format
printerJob.setPrintable(document, pageFormat);

//Execute print
try {
printerJob.print();
}
catch (PrinterException e) {
e.printStackTrace();
}
}
}

New method to print Word

import com.spire.doc.*;
import java.awt.print.*;
public class NewMethodToPrint {
public static void main(String[] args) {
//Load the sample document
Document doc = new Document();
doc.loadFromFile("Sample.docx");

PrinterJob loPrinterJob = PrinterJob.getPrinterJob();
PageFormat loPageFormat = loPrinterJob.defaultPage();

//set the paper size
Paper loPaper = loPageFormat.getPaper();
loPaper.setSize(600, 500);
loPageFormat.setPaper(loPaper);

//remove the default margin
loPaper.setImageableArea(0, 0, loPageFormat.getWidth(), loPageFormat.getHeight());
//set copies
loPrinterJob.setCopies(1);
loPrinterJob.setPrintable(doc, loPageFormat);
//set the print dialog
if (loPrinterJob.printDialog()) {
//print the word document
try {
loPrinterJob.print();
} catch (PrinterException e)

{
e.printStackTrace();
}
}
}
}

Wednesday, 7 April 2021

[Java] Add and Delete Digital Signature in an Excel worksheet

To add a digital signature in an Excel worksheet can authenticate the document, which shows that it belongs to you or your company. This tutorial will demonstrate how to add a digital signature to an Excel worksheet using Java codes, and then shows how to delete it.

It's worth mentioning that I used a free third-party library called Free Spire.XLS for Java. Before running codes, you need to add Spire.Xls.jar in the library to IDEA. Download the package from the link and manually add it 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.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

Add Digital Signature

import com.spire.xls.digital.CertificateAndPrivateKey;
import java.util.Date;

public class AddDigitalSignature {
public static void main(String[] args) throws Exception {
//Load the sample document
Workbook workbook=new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

//Add digital signature
CertificateAndPrivateKey cap = new CertificateAndPrivateKey("C:\\Users\\Test1\\Desktop\\gary.pfx","e-iceblue");
workbook.addDigitalSignature(cap, "e-iceblue",new Date());

//Save the document
String result="output/AddDigitalSignature.xlsx";
workbook.saveToFile(result,ExcelVersion.Version2013);
}
}
Output

Delete Digital Signature

import com.spire.xls.*;

public class DeleteDigitalSignature {
public static void main(String[] args) {
//Load the sample document
Workbook workbook=new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\AddDigitalSignature.xlsx");

//Remove digital signature
workbook.removeAllDigitalSignatures();

//Save the document
String result="output/RemoveDigitalSignature.xlsx";
workbook.saveToFile(result,ExcelVersion.Version2013);
}
}

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