Skip to content

Instantly share code, notes, and snippets.

@carlochess
Created April 19, 2016 18:42
Show Gist options
  • Save carlochess/7532dad90270798b5e20bd44b1cc142e to your computer and use it in GitHub Desktop.
Save carlochess/7532dad90270798b5e20bd44b1cc142e to your computer and use it in GitHub Desktop.
Java Pdfbox form filler and inspector example
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
public final class App
{
private App()
{
}
public static void main(String[] args) throws IOException
{
String formTemplate = "<RUTA a PDF>";
// Carga el pdf
PDDocument pdfDocument = PDDocument.load(new File(formTemplate));
// Obtiene el formulario del pdf cargado
PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
// Comprobamos que exista dicho formulario
if (acroForm != null)
{
// Listamos todos los campos del formulario
List<PDField> fields= acroForm.getFields();
for (PDField f : fields ) {
//System.out.println(f.getFullyQualifiedName());
// Todo campo de texto se completará con la cadena "llll"
if(f.getFieldType().equals("Tx"))
f.setValue("llll");
}
/* Tambien es posible obtener un campo individualmente
PDTextField field = (PDTextField) acroForm.getField( "sampleField" );
field.setValue("Text Entry");*/
}
// Guardamos y cerramos el archivo.
pdfDocument.save("<RUTA SALIDA>");
pdfDocument.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment