DEV Community


Posted on • Updated on

Set Expiration Date for PDF Document Using Java

Nowadays, more and more e-books, company contracts/agreement, academic report are in PDF file format. And for some confidential documents, setting expiration date is a very effective way to protect them. After the expiration date, the documents will be automatically destroyed. This article will demonstrate how to set an expiration date for a PDF document using Free Spire.PDF for Java.

Import jar dependency (2 Methods)
● Download the free API and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.
● Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

Enter fullscreen mode Exit fullscreen mode

Code Snippet

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

        //Set expiration date and warning information,and close the document through JavaScript
        String javaScript = "var rightNow = new Date();"
                + "var endDate = new Date('June 30, 2021 23:59: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

        //Save to file
        doc.saveToFile("ExpirationDate.pdf", FileFormat.PDF);
Enter fullscreen mode Exit fullscreen mode


Discussion (0)