Package com.itextpdf.forms
Class PdfAcroForm
- java.lang.Object
-
- com.itextpdf.kernel.pdf.PdfObjectWrapper<PdfDictionary>
-
- com.itextpdf.forms.PdfAcroForm
-
public class PdfAcroForm extends PdfObjectWrapper<PdfDictionary>
This class represents the static form technology AcroForm on a PDF file.
-
-
Field Summary
Fields Modifier and Type Field Description static intAPPEND_ONLYTo be used withsetSignatureFlags(int).private PdfDictionarydefaultResourcesprotected PdfDocumentdocumentThe PdfDocument to which the PdfAcroForm belongs.protected java.util.Map<java.lang.String,PdfFormField>fieldsA map of field names and their associatedform fieldobjects.private java.util.Set<PdfFormField>fieldsForFlatteningprotected booleangenerateAppearanceKeeps track of whether or not appearances must be generated by the form fields themselves, or by the PDF viewer application.private static org.slf4j.LoggerLOGGERstatic intSIGNATURE_EXISTTo be used withsetSignatureFlags(int).private XfaFormxfaForm
-
Constructor Summary
Constructors Modifier Constructor Description privatePdfAcroForm(PdfArray fields)Creates a PdfAcroForm from aPdfArrayof fields.privatePdfAcroForm(PdfDictionary pdfObject, PdfDocument pdfDocument)Creates a PdfAcroForm as a wrapper of a dictionary.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidaddField(PdfFormField field)This method adds the field to the last page in the document.voidaddField(PdfFormField field, PdfPage page)This method adds the field to a specific page.voidaddField(PdfFormField field, PdfPage page, boolean throwExceptionOnError)This method adds the field to a specific page.voidaddFieldAppearanceToPage(PdfFormField field, PdfPage page)This method merges field with its annotation and places it on the given page.private AffineTransformcalcFieldAppTransformToAnnotRect(PdfFormXObject xObject, Rectangle annotBBox)PdfFormFieldcopyField(java.lang.String name)Creates an in-memory copy of aPdfFormField.private static PdfDictionarycreateAcroFormDictionaryByFields(PdfArray fields)private voiddefineWidgetPageAndAddToIt(PdfPage currentPage, PdfDictionary mergedFieldAndWidget, boolean warnIfPageFlushed)voiddisableRegenerationForAllFields()Disables appearance stream regeneration for all the root fields in the Acroform, so all of its children in the hierarchy will also not be regenerated.voidenableRegenerationForAllFields()Enables appearance stream regeneration for all the fields in the Acroform and regenerates them.voidflattenFields()Flattens interactiveform fields in the document.static PdfAcroFormgetAcroForm(PdfDocument document, boolean createIfNotExist)Retrieves AcroForm from the document.static PdfAcroFormgetAcroForm(PdfDocument document, boolean createIfNotExist, OnDuplicateFormFieldNameStrategy onDuplicateFieldNameStrategy)Retrieves AcroForm from the document.java.util.Map<java.lang.String,PdfFormField>getAllFormFields()Gets allform fields as aMapincluding fields kids.java.util.Set<AbstractPdfFormField>getAllFormFieldsAndAnnotations()Gets allform fields as aSetincluding fields kids and nameless fields.private java.util.Set<PdfFormField>getAllFormFieldsWithoutNames()PdfArraygetCalculationOrder()Gets theCOarray property on the AcroForm.PdfStringgetDefaultAppearance()Gets theDAString property on the AcroForm.PdfNumbergetDefaultJustification()Gets theQinteger property on the AcroForm.PdfDictionarygetDefaultResources()Gets theDRdictionary property on the AcroForm.PdfFormFieldgetField(java.lang.String fieldName)Gets aform fieldby its name.private PdfPagegetFieldPage(PdfDictionary annotDict)protected PdfArraygetFields()Gets all AcroForm fields in the document.java.util.Collection<PdfFormField>getFieldsForFlattening()Gets a collection ofform fields, prepared for flattening usingpartialFormFlattening(java.lang.String)method.PdfBooleangetNeedAppearances()Gets theNeedAppearancesboolean property on the AcroForm.PdfDocumentgetPdfDocument()Gets thePdfDocumentthisPdfAcroFormbelongs to.java.util.Map<java.lang.String,PdfFormField>getRootFormFields()Gets root fields (i.e.intgetSignatureFlags()Gets theSigFlagsinteger property on the AcroForm.XfaFormgetXfaForm()Gets theXfaFormatribute.PdfObjectgetXFAResource()Gets theXFAproperty on the AcroForm.booleanhasXfaForm()Determines whether the AcroForm contains XFA data.booleanisGenerateAppearance()Gets the attribute generateAppearance, which tellsflattenFields()to generate an appearance Stream for allform fields that don't have one.protected booleanisWrappedObjectMustBeIndirect()Defines if the object behind this wrapper must be an indirect object in the resultant document.private booleanneedToAddToAcroform(PdfFormField field, boolean throwExceptionOnError)voidpartialFormFlattening(java.lang.String fieldName)Adds aform field, identified by name, to the list of fields to be flattened.private java.util.Map<java.lang.String,PdfFormField>populateFormFieldsMap()private java.util.Set<PdfFormField>prepareFieldsForFlattening(PdfFormField field)private voidprocessKids(PdfFormField field, PdfPage page)PdfAcroFormput(PdfName key, PdfObject value)Put a key/value pair in the dictionary and overwrite previous value if it already exists.voidrelease()Releases underlying pdf object and other pdf entities used by wrapper.booleanremoveField(java.lang.String fieldName)Tries to remove theform fieldwith the specified name from the document.private voidremoveFieldFromParentAndAcroForm(PdfArray formFields, PdfDictionary fieldObject)voidremoveXfaForm()Removes the XFA stream from the document.voidrenameField(java.lang.String oldName, java.lang.String newName)Changes the identifier of aform field.voidreplaceField(java.lang.String name, PdfFormField field)Replaces thePdfFormFieldof a certain name with anotherPdfFormField.PdfAcroFormsetCalculationOrder(PdfArray calculationOrder)Sets theCOarray property on the AcroForm.PdfAcroFormsetDefaultAppearance(java.lang.String appearance)Sets theDAString property on the AcroForm.PdfAcroFormsetDefaultJustification(int justification)Sets theQinteger property on the AcroForm.PdfAcroFormsetDefaultResources(PdfDictionary defaultResources)Sets theDRdictionary property on the AcroForm.voidsetGenerateAppearance(boolean generateAppearance)Sets the attribute generateAppearance, which tellsflattenFields()to generate an appearance Stream for allform fields that don't have one.PdfObjectWrapper<PdfDictionary>setModified()PdfAcroFormsetNeedAppearances(boolean needAppearances)Sets theNeedAppearancesboolean property on the AcroForm.PdfAcroFormsetSignatureFlag(int sigFlag)Changes theSigFlagsinteger property on the AcroForm.PdfAcroFormsetSignatureFlags(int sigFlags)Sets theSigFlagsinteger property on the AcroForm.PdfAcroFormsetXFAResource(PdfArray xfaResource)Sets theXFAproperty on the AcroForm.PdfAcroFormsetXFAResource(PdfStream xfaResource)Sets theXFAproperty on the AcroForm.-
Methods inherited from class com.itextpdf.kernel.pdf.PdfObjectWrapper
ensureObjectIsAddedToDocument, ensureUnderlyingObjectHasIndirectReference, flush, getPdfObject, isFlushed, makeIndirect, makeIndirect, markObjectAsIndirect, setForbidRelease, setPdfObject, unsetForbidRelease
-
-
-
-
Field Detail
-
LOGGER
private static final org.slf4j.Logger LOGGER
-
SIGNATURE_EXIST
public static final int SIGNATURE_EXIST
To be used withsetSignatureFlags(int).
If set, the document contains at least one signature field. This flag allows a conforming reader to enable user interface items (such as menu items or pushbuttons) related to signature processing without having to scan the entire document for the presence of signature fields. (ISO 32000-1, section 12.7.2 "Interactive Form Dictionary")
- See Also:
- Constant Field Values
-
APPEND_ONLY
public static final int APPEND_ONLY
To be used withsetSignatureFlags(int).
If set, the document contains signatures that may be invalidated if the file is saved (written) in a way that alters its previous contents, as opposed to an incremental update. Merely updating the file by appending new information to the end of the previous version is safe. Conforming readers may use this flag to inform a user requesting a full save that signatures will be invalidated and require explicit confirmation before continuing with the operation. (ISO 32000-1, section 12.7.2 "Interactive Form Dictionary")
- See Also:
- Constant Field Values
-
generateAppearance
protected boolean generateAppearance
Keeps track of whether or not appearances must be generated by the form fields themselves, or by the PDF viewer application. Default istrue.
-
fields
protected java.util.Map<java.lang.String,PdfFormField> fields
A map of field names and their associatedform fieldobjects.
-
document
protected PdfDocument document
The PdfDocument to which the PdfAcroForm belongs.
-
defaultResources
private PdfDictionary defaultResources
-
fieldsForFlattening
private java.util.Set<PdfFormField> fieldsForFlattening
-
xfaForm
private XfaForm xfaForm
-
-
Constructor Detail
-
PdfAcroForm
private PdfAcroForm(PdfDictionary pdfObject, PdfDocument pdfDocument)
Creates a PdfAcroForm as a wrapper of a dictionary. Also initializes an XFA form if an/XFAentry is present in the dictionary.- Parameters:
pdfObject- the PdfDictionary to be wrapped
-
PdfAcroForm
private PdfAcroForm(PdfArray fields)
Creates a PdfAcroForm from aPdfArrayof fields. Also initializes an empty XFA form.- Parameters:
fields- aPdfArrayofPdfDictionaryobjects
-
-
Method Detail
-
getAcroForm
public static PdfAcroForm getAcroForm(PdfDocument document, boolean createIfNotExist)
Retrieves AcroForm from the document. If there is no AcroForm in the document Catalog and createIfNotExist flag is true then the AcroForm dictionary will be created and added to the document.- Parameters:
document- the document to retrieve thePdfAcroFormfromcreateIfNotExist- whentrue, this method will create aPdfAcroFormif none exists for this document- Returns:
- the
document's AcroForm, or a new one provided thatcreateIfNotExistparameter istrue, otherwisenull.
-
getAcroForm
public static PdfAcroForm getAcroForm(PdfDocument document, boolean createIfNotExist, OnDuplicateFormFieldNameStrategy onDuplicateFieldNameStrategy)
Retrieves AcroForm from the document. If there is no AcroForm in the document Catalog and createIfNotExist flag is true then the AcroForm dictionary will be created and added to the document.- Parameters:
document- the document to retrieve thePdfAcroFormfromcreateIfNotExist- whentrue, this method will create aPdfAcroFormif none exists for this documentonDuplicateFieldNameStrategy- the strategy to be used when a field with the same name already exists- Returns:
- the
document's AcroForm, or a new one provided thatcreateIfNotExistparameter istrue, otherwisenull.
-
addField
public void addField(PdfFormField field)
This method adds the field to the last page in the document. If there's no pages, creates a new one.- Parameters:
field- thePdfFormFieldto be added to the form
-
addField
public void addField(PdfFormField field, PdfPage page)
This method adds the field to a specific page.- Parameters:
field- thePdfFormFieldto be added to the formpage- thePdfPageon which to add the field
-
addField
public void addField(PdfFormField field, PdfPage page, boolean throwExceptionOnError)
This method adds the field to a specific page.- Parameters:
field- thePdfFormFieldto be added to the formpage- thePdfPageon which to add the fieldthrowExceptionOnError- true if the exception is expected to be thrown in case of error.
-
addFieldAppearanceToPage
public void addFieldAppearanceToPage(PdfFormField field, PdfPage page)
This method merges field with its annotation and places it on the given page. This method also work if the field has more than one widget annotation, but doesn't work with no annotations.- Parameters:
field- thePdfFormFieldto be added to the formpage- thePdfPageon which to add the field
-
getRootFormFields
public java.util.Map<java.lang.String,PdfFormField> getRootFormFields()
Gets root fields (i.e. direct children of Acroform dictionary).- Returns:
- a map of field names and their associated
form fieldobjects
-
getAllFormFields
public java.util.Map<java.lang.String,PdfFormField> getAllFormFields()
Gets allform fields as aMapincluding fields kids.- Returns:
- a map of field names and their associated
form fieldobjects
-
getAllFormFieldsAndAnnotations
public java.util.Set<AbstractPdfFormField> getAllFormFieldsAndAnnotations()
Gets allform fields as aSetincluding fields kids and nameless fields.- Returns:
- a set of
form fieldobjects.
-
getFieldsForFlattening
public java.util.Collection<PdfFormField> getFieldsForFlattening()
Gets a collection ofform fields, prepared for flattening usingpartialFormFlattening(java.lang.String)method. If returned collection is empty, all form fields will be flattened onflattenFieldscall.- Returns:
- a collection of
form fields for flattening
-
getPdfDocument
public PdfDocument getPdfDocument()
Gets thePdfDocumentthisPdfAcroFormbelongs to.- Returns:
- the document of this form
-
setNeedAppearances
public PdfAcroForm setNeedAppearances(boolean needAppearances)
Sets theNeedAppearancesboolean property on the AcroForm. NeedAppearances has been deprecated in PDF 2.0.
NeedAppearances is a flag specifying whether to construct appearance streams and appearance dictionaries for all widget annotations in the document. (ISO 32000-1, section 12.7.2 "Interactive Form Dictionary")
- Parameters:
needAppearances- a boolean. Default value isfalse- Returns:
- current AcroForm.
-
getNeedAppearances
public PdfBoolean getNeedAppearances()
Gets theNeedAppearancesboolean property on the AcroForm. NeedAppearances has been deprecated in PDF 2.0.
NeedAppearances is a flag specifying whether to construct appearance streams and appearance dictionaries for all widget annotations in the document. (ISO 32000-1, section 12.7.2 "Interactive Form Dictionary")
- Returns:
- the
NeedAppearancesproperty as aPdfBoolean. Default value isfalse
-
setSignatureFlags
public PdfAcroForm setSignatureFlags(int sigFlags)
Sets theSigFlagsinteger property on the AcroForm.
SigFlags is a set of flags specifying various document-level characteristics related to signature fields. (ISO 32000-1, section 12.7.2 "Interactive Form Dictionary")
- Parameters:
sigFlags- an integer. UseSIGNATURE_EXISTand/orAPPEND_ONLY. Use bitwise OR operator to combine these values. Default value is0- Returns:
- current AcroForm.
-
setSignatureFlag
public PdfAcroForm setSignatureFlag(int sigFlag)
Changes theSigFlagsinteger property on the AcroForm. This method allows only to add flags, not to remove them.
SigFlags is a set of flags specifying various document-level characteristics related to signature fields. (ISO 32000-1, section 12.7.2 "Interactive Form Dictionary")
- Parameters:
sigFlag- an integer. UseSIGNATURE_EXISTand/orAPPEND_ONLY. Use bitwise OR operator to combine these values. Default is0- Returns:
- current AcroForm.
-
getSignatureFlags
public int getSignatureFlags()
Gets theSigFlagsinteger property on the AcroForm.
SigFlags is a set of flags specifying various document-level characteristics related to signature fields (ISO 32000-1, section 12.7.2 "Interactive Form Dictionary")
- Returns:
- current value for
SigFlags.
-
setCalculationOrder
public PdfAcroForm setCalculationOrder(PdfArray calculationOrder)
Sets theCOarray property on the AcroForm.
CO, Calculation Order, is an array of indirect references to field dictionaries with calculation actions, defining the calculation order in which their values will be recalculated when the value of any field changes (ISO 32000-1, section 12.7.2 "Interactive Form Dictionary")- Parameters:
calculationOrder- an array of indirect references- Returns:
- current AcroForm
-
getCalculationOrder
public PdfArray getCalculationOrder()
Gets theCOarray property on the AcroForm.
CO, Calculation Order, is an array of indirect references to field dictionaries with calculation actions, defining the calculation order in which their values will be recalculated when the value of any field changes (ISO 32000-1, section 12.7.2 "Interactive Form Dictionary")- Returns:
- an array of indirect references
-
setDefaultResources
public PdfAcroForm setDefaultResources(PdfDictionary defaultResources)
Sets theDRdictionary property on the AcroForm.
DRis a resource dictionary containing default resources (such as fonts, patterns, or colour spaces) that shall be used by form field appearance streams. At a minimum, this dictionary shall contain a Font entry specifying the resource name and font dictionary of the default font for displaying text. (ISO 32000-1, section 12.7.2 "Interactive Form Dictionary")- Parameters:
defaultResources- a resource dictionary- Returns:
- current AcroForm
-
getDefaultResources
public PdfDictionary getDefaultResources()
Gets theDRdictionary property on the AcroForm.
DRis a resource dictionary containing default resources (such as fonts, patterns, or colour spaces) that shall be used by form field appearance streams. At a minimum, this dictionary shall contain a Font entry specifying the resource name and font dictionary of the default font for displaying text. (ISO 32000-1, section 12.7.2 "Interactive Form Dictionary")- Returns:
- a resource dictionary
-
setDefaultAppearance
public PdfAcroForm setDefaultAppearance(java.lang.String appearance)
Sets theDAString property on the AcroForm.
This method sets a default (fallback value) for theDAattribute of variable textform fields.- Parameters:
appearance- a String containing a sequence of valid PDF syntax- Returns:
- current AcroForm
-
getDefaultAppearance
public PdfString getDefaultAppearance()
Gets theDAString property on the AcroForm.
This method returns the default (fallback value) for theDAattribute of variable textform fields.- Returns:
- the form-wide default appearance, as a
String
-
setDefaultJustification
public PdfAcroForm setDefaultJustification(int justification)
Sets theQinteger property on the AcroForm.
This method sets a default (fallback value) for theQattribute of variable textform fields.- Parameters:
justification- an integer representing a justification value- Returns:
- current AcroForm
- See Also:
PdfFormField.setJustification(com.itextpdf.layout.properties.TextAlignment)
-
getDefaultJustification
public PdfNumber getDefaultJustification()
Gets theQinteger property on the AcroForm.
This method gets the default (fallback value) for theQattribute of variable textform fields.- Returns:
- an integer representing a justification value
- See Also:
PdfFormField.getJustification()
-
setXFAResource
public PdfAcroForm setXFAResource(PdfStream xfaResource)
Sets theXFAproperty on the AcroForm.
XFAcan either be aPdfStreamor aPdfArray. Its contents must be valid XFA.- Parameters:
xfaResource- a stream containing the XDP- Returns:
- current AcroForm
-
setXFAResource
public PdfAcroForm setXFAResource(PdfArray xfaResource)
Sets theXFAproperty on the AcroForm.
XFAcan either be aPdfStreamor aPdfArray. Its contents must be valid XFA.- Parameters:
xfaResource- an array of text string and stream pairs representing the individual packets comprising the XML Data Package. (ISO 32000-1, section 12.7.2 "Interactive Form Dictionary")- Returns:
- current AcroForm
-
getXFAResource
public PdfObject getXFAResource()
Gets theXFAproperty on the AcroForm.
-
getField
public PdfFormField getField(java.lang.String fieldName)
Gets aform fieldby its name.- Parameters:
fieldName- the name of theform fieldto retrieve- Returns:
- the
form field, ornullif it isn't present
-
isGenerateAppearance
public boolean isGenerateAppearance()
Gets the attribute generateAppearance, which tellsflattenFields()to generate an appearance Stream for allform fields that don't have one.- Returns:
- bolean value indicating if the appearances need to be generated
-
setGenerateAppearance
public void setGenerateAppearance(boolean generateAppearance)
Sets the attribute generateAppearance, which tellsflattenFields()to generate an appearance Stream for allform fields that don't have one.Not generating appearances will speed up form flattening but the results can be unexpected in Acrobat. Don't use it unless your environment is well controlled. The default is
true.If generateAppearance is set to
true, thenNeedAppearancesis set tofalse. This does not apply vice versa.Note, this method does not change default behaviour of
PdfFormField.setValue(String)method.- Parameters:
generateAppearance- a boolean
-
flattenFields
public void flattenFields()
Flattens interactiveform fields in the document. If no fields have been explicitly included viapartialFormFlattening(java.lang.String), then all fields are flattened. Otherwise only the included fields are flattened.
-
removeField
public boolean removeField(java.lang.String fieldName)
Tries to remove theform fieldwith the specified name from the document.- Parameters:
fieldName- the name of theform fieldto remove- Returns:
- a boolean representing whether or not the removal succeeded.
-
partialFormFlattening
public void partialFormFlattening(java.lang.String fieldName)
Adds aform field, identified by name, to the list of fields to be flattened. Does not perform a flattening operation in itself.- Parameters:
fieldName- the name of theform fieldto be flattened
-
renameField
public void renameField(java.lang.String oldName, java.lang.String newName)Changes the identifier of aform field.- Parameters:
oldName- the current name of the fieldnewName- the new name of the field. Must not be used currently.
-
copyField
public PdfFormField copyField(java.lang.String name)
Creates an in-memory copy of aPdfFormField. This new field is not added to the document.- Parameters:
name- the name of theform fieldto be copied- Returns:
- a clone of the original
PdfFormField
-
replaceField
public void replaceField(java.lang.String name, PdfFormField field)Replaces thePdfFormFieldof a certain name with anotherPdfFormField.- Parameters:
name- the name of theform fieldto be replacedfield- the newPdfFormField
-
disableRegenerationForAllFields
public void disableRegenerationForAllFields()
Disables appearance stream regeneration for all the root fields in the Acroform, so all of its children in the hierarchy will also not be regenerated.
-
enableRegenerationForAllFields
public void enableRegenerationForAllFields()
Enables appearance stream regeneration for all the fields in the Acroform and regenerates them.
-
getFields
protected PdfArray getFields()
Gets all AcroForm fields in the document.- Returns:
- a
PdfArrayof field dictionaries
-
isWrappedObjectMustBeIndirect
protected boolean isWrappedObjectMustBeIndirect()
Description copied from class:PdfObjectWrapperDefines if the object behind this wrapper must be an indirect object in the resultant document.
If this method returns true it doesn't necessarily mean that object must be in the indirect state at any moment, but rather defines that when the object will be written to the document it will be transformed into indirect object if it's not indirect yet.
Return value of this method shouldn't depend on any logic, it should return always true or false.- Specified by:
isWrappedObjectMustBeIndirectin classPdfObjectWrapper<PdfDictionary>- Returns:
- true if in the resultant document the object behind the wrapper must be indirect, otherwise false.
-
populateFormFieldsMap
private java.util.Map<java.lang.String,PdfFormField> populateFormFieldsMap()
-
removeFieldFromParentAndAcroForm
private void removeFieldFromParentAndAcroForm(PdfArray formFields, PdfDictionary fieldObject)
-
processKids
private void processKids(PdfFormField field, PdfPage page)
-
defineWidgetPageAndAddToIt
private void defineWidgetPageAndAddToIt(PdfPage currentPage, PdfDictionary mergedFieldAndWidget, boolean warnIfPageFlushed)
-
hasXfaForm
public boolean hasXfaForm()
Determines whether the AcroForm contains XFA data.- Returns:
- a boolean
-
removeXfaForm
public void removeXfaForm()
Removes the XFA stream from the document.
-
put
public PdfAcroForm put(PdfName key, PdfObject value)
Put a key/value pair in the dictionary and overwrite previous value if it already exists.- Parameters:
key- the key as pdf namevalue- the value as pdf object- Returns:
- this
PdfAcroForminstance
-
release
public void release()
Releases underlying pdf object and other pdf entities used by wrapper. This method should be called instead of direct call toPdfObject.release()if the wrapper is used.
-
setModified
public PdfObjectWrapper<PdfDictionary> setModified()
- Overrides:
setModifiedin classPdfObjectWrapper<PdfDictionary>
-
createAcroFormDictionaryByFields
private static PdfDictionary createAcroFormDictionaryByFields(PdfArray fields)
-
getFieldPage
private PdfPage getFieldPage(PdfDictionary annotDict)
-
prepareFieldsForFlattening
private java.util.Set<PdfFormField> prepareFieldsForFlattening(PdfFormField field)
-
calcFieldAppTransformToAnnotRect
private AffineTransform calcFieldAppTransformToAnnotRect(PdfFormXObject xObject, Rectangle annotBBox)
-
getAllFormFieldsWithoutNames
private java.util.Set<PdfFormField> getAllFormFieldsWithoutNames()
-
needToAddToAcroform
private boolean needToAddToAcroform(PdfFormField field, boolean throwExceptionOnError)
-
-