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



No comments:

Post a Comment

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