I keep getting this error in some pdf file. It works perfectly from some pdf while fails and give error on other pdfs.
Jar used: forms-7.1.4.jar io-7.1.4.jar layout-7.1.4.jar kernel-7.1.4.jar
package test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.util.*;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.forms.PdfAcroForm;
public class test5 {
public static final String DATASHEET
= "2.pdf";
public static void main(String[] args) throws Exception {
PdfReader reader = new PdfReader(DATASHEET);
PdfDocument pdfDoc = new PdfDocument(reader);
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
Set<String> fields = form.getFormFields().keySet();
for (String key : fields) {
PdfName type = form.getField(key).getFormType();
if(type!= null && 0 == PdfName.Btn.compareTo(type) )
{
String[] states = form.getField(key).getAppearanceStates();
for (int i = 0; i < states.length; i++) {
System.out.println(states[i]);
}
}
}
}
}
This program finds the radio button values in the pdf
You open the PdfDocument
with only a PdfReader
, no PdfWriter
:
PdfDocument pdfDoc = new PdfDocument(reader);
Thus, you cannot (deeply) change the document. On the other hand you retrieve the AcroForm with the second argument true
:
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
This signals to iText that you want it to add a new AcroForm structure to the document if it does not have one yet. This is a deep change.
Thus, your code works for pdfs that already have an AcroForm structure and fail for pdfs that don't.
So either use a writable PdfDocument
(with also a PdfWriter
) or don't tell iText to create AcroForm structures (with a false
parameter). For the latter option you may have to add a null
check.