Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save patcon/a24382ebd0479763b814ba8c4e9c3e63 to your computer and use it in GitHub Desktop.
Save patcon/a24382ebd0479763b814ba8c4e9c3e63 to your computer and use it in GitHub Desktop.
This Gist will convert a Static XFA Form to an AcroForm by removing the XFA dictionary.
/*
* Copyright Datalogics, Inc. 2015
*/
package pdfjt.cookbook.forms;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import pdfjt.util.SampleFileServices;
import com.adobe.internal.io.ByteReader;
import com.adobe.internal.io.ByteWriter;
import com.adobe.internal.io.InputStreamByteReader;
import com.adobe.pdfjt.core.types.ASString;
import com.adobe.pdfjt.pdf.document.PDFDocument;
import com.adobe.pdfjt.pdf.document.PDFOpenOptions;
import com.adobe.pdfjt.pdf.document.PDFSaveFullOptions;
import com.adobe.pdfjt.pdf.interactive.forms.PDFNamedJavaScripts;
import com.adobe.pdfjt.services.xfa.XFAService;
/**
* This sample will remove the XFA dictionary from a PDF file.
*/
public class StaticXFA2AcroForm {
private static final String inputPDFURL = "http://dev.datalogics.com/cookbook/forms/Static_XFA_Input.pdf";
private static final String outputDir = "cookbook/Forms/output/";
static public void main(String[] args) throws Exception {
URLConnection connection = new URL(inputPDFURL).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
connection.connect();
InputStream fis = connection.getInputStream();
ByteReader byteReader = new InputStreamByteReader(fis);
PDFDocument pdfDocument = PDFDocument.newInstance(byteReader, PDFOpenOptions.newInstance());
// Make sure we have the right kind of form.
if (pdfDocument.getInteractiveForm().hasXFA()) {
if (XFAService.isStaticXFANonShell(pdfDocument)) {
// Remove the XFA Dictionary
pdfDocument.getInteractiveForm().removeXFA();
// Remove the Scripts automatically added by LC Designer.
PDFNamedJavaScripts namedJavaScripts = pdfDocument.requireCatalog().getNameDictionary().getNamedJavaScripts();
namedJavaScripts.removeEntry(new ASString("!ADBE::0100_VersChkStrings"));
namedJavaScripts.removeEntry(new ASString("!ADBE::0100_VersChkVars"));
namedJavaScripts.removeEntry(new ASString("!ADBE::0200_VersChkCode_XFACheck"));
// Save the file
String outputFileName = "Converted_AcroForm.pdf";
ByteWriter outputFile = SampleFileServices.getRAFByteWriter(outputDir + outputFileName);
pdfDocument.save(outputFile, PDFSaveFullOptions.newInstance());
System.out.println("Created: " + outputFileName);
}
else {
System.out.println("Not Static XFA");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment