pdfbox-trunk/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/UpdateFieldOnDocumentOpen.java
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.pdfbox.examples.interactive.form;

import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;

/**
 * Update field automatically when the document is opened.
 * 
 * This sample adds document action to automatically update a 
 * field value with the current date when the document is opened.
 * 
 * This sample builds on the form generated by @link CreateSimpleForm so you need to run that first.
 * 
 */
public final class UpdateFieldOnDocumentOpen
{
    private UpdateFieldOnDocumentOpen()
    {
    }
    
    public static void main(String[] args) throws IOException
    {
        // Load the PDF document created by SimpleForm.java
        try (PDDocument document = Loader.loadPDF(new File("target/SimpleForm.pdf")))
        {
            // Note that the JavaScript will depend on the reader application.
            // The classes and methods available to Adobe Reader and Adobe Acrobat
            // are documented in the Acrobat SDK.
            String javaScript = "var now = util.printd('yyyy-mm-dd', new Date());"
                    + "var oField = this.getField('SampleField');"
                    + "oField.value = now;";
            
            // Create an action as JavaScript action
            PDActionJavaScript jsAction = new PDActionJavaScript();
            jsAction.setAction(javaScript);
            
            // Set the action to be executed when the document is opened
            document.getDocumentCatalog().setOpenAction(jsAction);
            
            document.save("target/UpdateFieldOnDocumentOpen.pdf");
        }
    }
}
