Package com.aowagie.text.pdf
Class PdfStamper
- java.lang.Object
-
- com.aowagie.text.pdf.PdfStamper
-
- All Implemented Interfaces:
PdfEncryptionSettings
,PdfViewerPreferences
public class PdfStamper extends java.lang.Object implements PdfViewerPreferences, PdfEncryptionSettings
Applies extra content to the pages of a PDF document. This extra content can be all the objects allowed in PdfContentByte including pages from other Pdfs. The original PDF will keep all the interactive elements including bookmarks, links and form fields.It is also possible to change the field values and to flatten them. New fields can be added but not flattened.
-
-
Field Summary
Fields Modifier and Type Field Description private boolean
hasSignature
private java.util.Map
moreInfo
private PdfSignatureAppearance
sigApp
private PdfStamperImp
stamper
The writer
-
Constructor Summary
Constructors Modifier Constructor Description PdfStamper(PdfReader reader, java.io.OutputStream os)
Starts the process of adding extra content to an existing PDF document.private
PdfStamper(PdfReader reader, java.io.OutputStream os, char pdfVersion, boolean append, java.util.Calendar globalDate)
Starts the process of adding extra content to an existing PDF document, possibly as a new revision.PdfStamper(PdfReader reader, java.io.OutputStream os, java.util.Calendar globalDate)
Starts the process of adding extra content to an existing PDF document.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description void
addAnnotation(PdfAnnotation annot, int page)
Adds an annotation of form field in a specific page.private void
addFileAttachment(java.lang.String description, PdfFileSpecification fs)
Adds a file attachment at the document level.void
addViewerPreference(PdfName key, PdfObject value)
Adds a viewer preferencevoid
close()
Closes the document.void
close(java.util.Calendar globalDate)
Closes the document.static PdfStamper
createSignature(PdfReader reader, java.io.OutputStream os, char pdfVersion, java.io.File tempFile, boolean append)
Applies a digital signature to a document, possibly as a new revision, making possible multiple signatures.static PdfStamper
createSignature(PdfReader reader, java.io.OutputStream os, char pdfVersion, java.io.File tempFile, boolean append, java.util.Calendar globalDate)
Applies a digital signature to a document, possibly as a new revision, making possible multiple signatures.AcroFields
getAcroFields()
Gets theAcroFields
object that allows to get and set field values and to merge FDF forms.java.util.Map
getMoreInfo()
Gets the optionalString
map to add or change values in the info dictionary.PdfContentByte
getOverContent(int pageNum)
Gets aPdfContentByte
to write over the page of the original document.java.util.Map
getPdfLayers()
Gets the PdfLayer objects in an existing document as a Map with the names/titles of the layers as keys.PdfReader
getReader()
Gets the underlying PdfReader.PdfSignatureAppearance
getSignatureAppearance()
Gets the signing instance.PdfWriter
getWriter()
Gets the underlying PdfWriter.void
insertPage(int pageNumber, Rectangle mediabox)
Inserts a blank page.boolean
isFullCompression()
Gets the 1.5 compression status.boolean
isRotateContents()
Checks if the content is automatically adjusted to compensate the original page rotation.(package private) void
setEncryption(boolean strength, java.lang.String userPassword, java.lang.String ownerPassword, int permissions)
Sets the encryption options for this document.(package private) void
setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, boolean strength128Bits)
Sets the encryption options for this document.void
setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType)
Sets the encryption options for this document.(package private) void
setEncryption(int encryptionType, java.lang.String userPassword, java.lang.String ownerPassword, int permissions)
Sets the encryption options for this document.void
setEncryption(java.security.cert.Certificate[] certs, int[] permissions, int encryptionType)
Sets the certificate encryption options for this document.void
setFormFlattening(boolean flat)
Determines if the fields are flattened on close.void
setFreeTextFlattening(boolean flat)
Determines if the FreeText annotations are flattened on close.void
setFullCompression()
Sets the document's compression to the new 1.5 mode with object streams and xref streams.void
setMoreInfo(java.util.Map moreInfo)
An optionalString
map to add or change values in the info dictionary.void
setOutlines(java.util.List outlines)
Sets the bookmarks.void
setRotateContents(boolean rotateContents)
Flags the content to be automatically adjusted to compensate the original page rotation.void
setViewerPreferences(int preferences)
Sets the viewer preferences.void
setXmpMetadata(byte[] xmp)
Sets the XMP metadata.
-
-
-
Field Detail
-
stamper
private final PdfStamperImp stamper
The writer
-
moreInfo
private java.util.Map moreInfo
-
hasSignature
private boolean hasSignature
-
sigApp
private PdfSignatureAppearance sigApp
-
-
Constructor Detail
-
PdfStamper
public PdfStamper(PdfReader reader, java.io.OutputStream os, java.util.Calendar globalDate) throws DocumentException, java.io.IOException
Starts the process of adding extra content to an existing PDF document.- Parameters:
reader
- the original document. It cannot be reusedos
- the output streamglobalDate
- global date- Throws:
DocumentException
- on errorjava.io.IOException
- on error
-
PdfStamper
public PdfStamper(PdfReader reader, java.io.OutputStream os) throws DocumentException, java.io.IOException
Starts the process of adding extra content to an existing PDF document.- Parameters:
reader
- the original document. It cannot be reusedos
- the output stream- Throws:
DocumentException
- on errorjava.io.IOException
- on error.
-
PdfStamper
private PdfStamper(PdfReader reader, java.io.OutputStream os, char pdfVersion, boolean append, java.util.Calendar globalDate) throws DocumentException, java.io.IOException
Starts the process of adding extra content to an existing PDF document, possibly as a new revision.- Parameters:
reader
- the original document. It cannot be reusedos
- the output streampdfVersion
- the new pdf version or '\0' to keep the same version as the original documentappend
- iftrue
appends the document changes as a new revision. This is only useful for multiple signatures as nothing is gained in speed or memory- Throws:
DocumentException
- on errorjava.io.IOException
- on error.
-
-
Method Detail
-
getMoreInfo
public java.util.Map getMoreInfo()
Gets the optionalString
map to add or change values in the info dictionary.- Returns:
- the map or
null
.
-
setMoreInfo
public void setMoreInfo(java.util.Map moreInfo)
An optionalString
map to add or change values in the info dictionary. Entries withnull
values delete the key in the original info dictionary- Parameters:
moreInfo
- additional entries to the info dictionary.
-
insertPage
public void insertPage(int pageNumber, Rectangle mediabox)
Inserts a blank page. All the pages above and includingpageNumber
will be shifted up. IfpageNumber
is bigger than the total number of pages the new page will be the last one.- Parameters:
pageNumber
- the page number position where the new page will be insertedmediabox
- the size of the new page
-
getSignatureAppearance
public PdfSignatureAppearance getSignatureAppearance()
Gets the signing instance. The appearances and other parameters can the be set.- Returns:
- the signing instance
-
close
public void close() throws DocumentException, java.io.IOException
Closes the document. No more content can be written after the document is closed.If closing a signed document with an external signature the closing must be done in the
PdfSignatureAppearance
instance.- Throws:
DocumentException
- on errorjava.io.IOException
- on error.
-
close
public void close(java.util.Calendar globalDate) throws DocumentException, java.io.IOException
Closes the document. No more content can be written after the document is closed.If closing a signed document with an external signature the closing must be done in the
PdfSignatureAppearance
instance.- Parameters:
globalDate
- global date- Throws:
DocumentException
- on errorjava.io.IOException
- on error.
-
isRotateContents
public boolean isRotateContents()
Checks if the content is automatically adjusted to compensate the original page rotation.- Returns:
- the auto-rotation status
-
setRotateContents
public void setRotateContents(boolean rotateContents)
Flags the content to be automatically adjusted to compensate the original page rotation. The default istrue
.- Parameters:
rotateContents
-true
to set auto-rotation,false
otherwise
-
setEncryption
void setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, boolean strength128Bits) throws DocumentException
Sets the encryption options for this document. The userPassword and the ownerPassword can be null or have zero length. In this case the ownerPassword is replaced by a random string. The open permissions for the document can be AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations, AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting. The permissions can be combined by ORing them.- Parameters:
userPassword
- the user password. Can be null or emptyownerPassword
- the owner password. Can be null or emptypermissions
- the user permissionsstrength128Bits
-true
for 128 bit key length,false
for 40 bit key length- Throws:
DocumentException
- if anything was already written to the output
-
setEncryption
public void setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType) throws DocumentException
Sets the encryption options for this document. The userPassword and the ownerPassword can be null or have zero length. In this case the ownerPassword is replaced by a random string. The open permissions for the document can be AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations, AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting. The permissions can be combined by ORing them.- Specified by:
setEncryption
in interfacePdfEncryptionSettings
- Parameters:
userPassword
- the user password. Can be null or emptyownerPassword
- the owner password. Can be null or emptypermissions
- the user permissionsencryptionType
- the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128. Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext- Throws:
DocumentException
- if the document is already open
-
setEncryption
void setEncryption(boolean strength, java.lang.String userPassword, java.lang.String ownerPassword, int permissions) throws DocumentException
Sets the encryption options for this document. The userPassword and the ownerPassword can be null or have zero length. In this case the ownerPassword is replaced by a random string. The open permissions for the document can be AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations, AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting. The permissions can be combined by ORing them.- Parameters:
strength
-true
for 128 bit key length,false
for 40 bit key lengthuserPassword
- the user password. Can be null or emptyownerPassword
- the owner password. Can be null or emptypermissions
- the user permissions- Throws:
DocumentException
- if anything was already written to the output
-
setEncryption
void setEncryption(int encryptionType, java.lang.String userPassword, java.lang.String ownerPassword, int permissions) throws DocumentException
Sets the encryption options for this document. The userPassword and the ownerPassword can be null or have zero length. In this case the ownerPassword is replaced by a random string. The open permissions for the document can be AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations, AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting. The permissions can be combined by ORing them.- Parameters:
encryptionType
- the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128. Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartextuserPassword
- the user password. Can be null or emptyownerPassword
- the owner password. Can be null or emptypermissions
- the user permissions- Throws:
DocumentException
- if anything was already written to the output
-
setEncryption
public void setEncryption(java.security.cert.Certificate[] certs, int[] permissions, int encryptionType) throws DocumentException
Sets the certificate encryption options for this document. An array of one or more public certificates must be provided together with an array of the same size for the permissions for each certificate. The open permissions for the document can be AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations, AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting. The permissions can be combined by ORing them. Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext- Specified by:
setEncryption
in interfacePdfEncryptionSettings
- Parameters:
certs
- the public certificates to be used for the encryptionpermissions
- the user permissions for each of the certificatesencryptionType
- the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.- Throws:
DocumentException
- if the encryption was set too late
-
getWriter
public PdfWriter getWriter()
Gets the underlying PdfWriter.- Returns:
- the underlying PdfWriter
-
getReader
public PdfReader getReader()
Gets the underlying PdfReader.- Returns:
- the underlying PdfReader
-
getAcroFields
public AcroFields getAcroFields()
Gets theAcroFields
object that allows to get and set field values and to merge FDF forms.- Returns:
- the
AcroFields
object
-
setFormFlattening
public void setFormFlattening(boolean flat)
Determines if the fields are flattened on close. The fields added withaddAnnotation(PdfAnnotation,int)
will never be flattened.- Parameters:
flat
-true
to flatten the fields,false
to keep the fields
-
setFreeTextFlattening
public void setFreeTextFlattening(boolean flat)
Determines if the FreeText annotations are flattened on close.- Parameters:
flat
-true
to flatten the FreeText annotations,false
(the default) to keep the FreeText annotations as active content.
-
addAnnotation
public void addAnnotation(PdfAnnotation annot, int page)
Adds an annotation of form field in a specific page. This page number can be overridden withPdfAnnotation.setPlaceInPage(int)
.- Parameters:
annot
- the annotationpage
- the page
-
setOutlines
public void setOutlines(java.util.List outlines)
Sets the bookmarks. The list structure is defined inSimpleBookmark
.- Parameters:
outlines
- the bookmarks ornull
to remove any
-
addFileAttachment
private void addFileAttachment(java.lang.String description, PdfFileSpecification fs) throws java.io.IOException
Adds a file attachment at the document level. Existing attachments will be kept.- Parameters:
description
- the file descriptionfs
- the file specification- Throws:
java.io.IOException
-
setViewerPreferences
public void setViewerPreferences(int preferences)
Sets the viewer preferences.- Specified by:
setViewerPreferences
in interfacePdfViewerPreferences
- Parameters:
preferences
- the viewer preferences- See Also:
PdfViewerPreferences.setViewerPreferences(int)
-
addViewerPreference
public void addViewerPreference(PdfName key, PdfObject value)
Adds a viewer preference- Specified by:
addViewerPreference
in interfacePdfViewerPreferences
- Parameters:
key
- a key for a viewer preferencevalue
- the value for the viewer preference- See Also:
PdfViewerPreferences.addViewerPreference(com.aowagie.text.pdf.PdfName, com.aowagie.text.pdf.PdfObject)
-
setXmpMetadata
public void setXmpMetadata(byte[] xmp)
Sets the XMP metadata.- Parameters:
xmp
- info with xmp- See Also:
PdfWriter.setXmpMetadata(byte[])
-
isFullCompression
public boolean isFullCompression()
Gets the 1.5 compression status.- Returns:
true
if the 1.5 compression is on
-
setFullCompression
public void setFullCompression()
Sets the document's compression to the new 1.5 mode with object streams and xref streams. It can be set at any time but once set it can't be unset.
-
createSignature
public static PdfStamper createSignature(PdfReader reader, java.io.OutputStream os, char pdfVersion, java.io.File tempFile, boolean append) throws DocumentException, java.io.IOException
Applies a digital signature to a document, possibly as a new revision, making possible multiple signatures. The returned PdfStamper can be used normally as the signature is only applied when closing.A possible use for adding a signature without invalidating an existing one is:
KeyStore ks = KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray()); String alias = (String)ks.aliases().nextElement(); PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray()); Certificate[] chain = ks.getCertificateChain(alias); PdfReader reader = new PdfReader("original.pdf"); FileOutputStream fout = new FileOutputStream("signed.pdf"); PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0', new File("/temp"), true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason("I'm the author"); sap.setLocation("Lisbon"); // comment next line to have an invisible signature sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null); stp.close();
- Parameters:
reader
- the original documentos
- the output stream ornull
to keep the document in the temporary filepdfVersion
- the new pdf version or '\0' to keep the same version as the original documenttempFile
- location of the temporary file. If it's a directory a temporary file will be created there. If it's a file it will be used directly. The file will be deleted on exit unlessos
is null. In that case the document can be retrieved directly from the temporary file. If it'snull
no temporary file will be created and memory will be usedappend
- iftrue
the signature and all the other content will be added as a new revision thus not invalidating existing signatures- Returns:
- a
PdfStamper
- Throws:
DocumentException
- on errorjava.io.IOException
- on error
-
createSignature
public static PdfStamper createSignature(PdfReader reader, java.io.OutputStream os, char pdfVersion, java.io.File tempFile, boolean append, java.util.Calendar globalDate) throws DocumentException, java.io.IOException
Applies a digital signature to a document, possibly as a new revision, making possible multiple signatures. The returned PdfStamper can be used normally as the signature is only applied when closing.A possible use for adding a signature without invalidating an existing one is:
KeyStore ks = KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray()); String alias = (String)ks.aliases().nextElement(); PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray()); Certificate[] chain = ks.getCertificateChain(alias); PdfReader reader = new PdfReader("original.pdf"); FileOutputStream fout = new FileOutputStream("signed.pdf"); PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0', new File("/temp"), true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason("I'm the author"); sap.setLocation("Lisbon"); // comment next line to have an invisible signature sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null); stp.close();
- Parameters:
reader
- the original documentos
- the output stream ornull
to keep the document in the temporary filepdfVersion
- the new pdf version or '\0' to keep the same version as the original documenttempFile
- location of the temporary file. If it's a directory a temporary file will be created there. If it's a file it will be used directly. The file will be deleted on exit unlessos
is null. In that case the document can be retrieved directly from the temporary file. If it'snull
no temporary file will be created and memory will be usedappend
- iftrue
the signature and all the other content will be added as a new revision thus not invalidating existing signaturesglobalDate
- global date- Returns:
- a
PdfStamper
- Throws:
DocumentException
- on errorjava.io.IOException
- on error
-
getOverContent
public PdfContentByte getOverContent(int pageNum)
Gets aPdfContentByte
to write over the page of the original document.- Parameters:
pageNum
- the page number where the extra content is written- Returns:
- a
PdfContentByte
to write over the page of the original document
-
getPdfLayers
public java.util.Map getPdfLayers()
Gets the PdfLayer objects in an existing document as a Map with the names/titles of the layers as keys.- Returns:
- a Map with all the PdfLayers in the document (and the name/title of the layer as key)
- Since:
- 2.1.2
-
-