questions.javascript.RemoveJavaScript.java Source code

Java tutorial

Introduction

Here is the source code for questions.javascript.RemoveJavaScript.java

Source

/*
 * This example was written by Bruno Lowagie, author of the book
 * 'iText in Action' by Manning Publications (ISBN: 1932394796).
 * You can use this example as inspiration for your own applications.
 * The following license applies:
 * http://www.1t3xt.com/about/copyright/index.php?page=MIT
 */

package questions.javascript;

import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfDictionary;
import com.lowagie.text.pdf.PdfName;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class RemoveJavaScript {

    public static final String RESULT = "results/questions/javascript/pdf_without_js.pdf";

    public static void main(String[] args) throws DocumentException, IOException {
        // creating the form with JS
        AddJavaScriptToForm.main(args);
        // removing the document level JS
        PdfReader reader = new PdfReader(AddJavaScriptToForm.RESULT);
        PdfDictionary root = reader.getCatalog();
        PdfDictionary names = root.getAsDict(PdfName.NAMES);
        names.remove(PdfName.JAVASCRIPT);
        if (names.size() == 0) {
            root.remove(PdfName.NAMES);
        }
        reader.removeUnusedObjects();
        // filling out and flattening the form
        // (if you don't flatten, you'll get JS errors!)
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        AcroFields form = stamper.getAcroFields();
        form.setField("married", "no");
        stamper.setFormFlattening(true);
        stamper.close();
    }
}