Class PdfStamper
- java.lang.Object
-
- com.gitlab.pdftk_java.com.lowagie.text.pdf.PdfStamper
-
public class PdfStamper extends Object
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.
- Author:
- Paulo Soares (psoares@consiste.pt)
-
-
Field Summary
Fields Modifier and Type Field Description protected PdfStamperImpstamperThe writer
-
Constructor Summary
Constructors Constructor Description PdfStamper(PdfReader reader, OutputStream os)Starts the process of adding extra content to an existing PDF document.PdfStamper(PdfReader reader, OutputStream os, char pdfVersion)Starts the process of adding extra content to an existing PDF document.PdfStamper(PdfReader reader, OutputStream os, char pdfVersion, boolean append)Starts the process of adding extra content to an existing PDF document, possibly as a new revision.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidaddAnnotation(PdfAnnotation annot, int page)Adds an annotation of form field in a specific page.voidaddComments(FdfReader fdf)Adds the comments present in an FDF file.voidaddJavaScript(String js)Adds a JavaScript action at the document level.voidclose()Closes the document.static PdfStampercreateSignature(PdfReader reader, OutputStream os, char pdfVersion)Applies a digital signature to a document.static PdfStampercreateSignature(PdfReader reader, OutputStream os, char pdfVersion, File tempFile)Applies a digital signature to a document.static PdfStampercreateSignature(PdfReader reader, OutputStream os, char pdfVersion, File tempFile, boolean append)Applies a digital signature to a document, possibly as a new revision, making possible multiple signatures.AcroFieldsgetAcroFields()Gets theAcroFieldsobject that allows to get and set field values and to merge FDF forms.PdfImportedPagegetImportedPage(PdfReader reader, int pageNumber)Gets a page from other PDF document.HashMapgetMoreInfo()Gets the optionalStringmap to add or change values in the info dictionary.PdfContentBytegetOverContent(int pageNum)Gets aPdfContentByteto write over the page of the original document.PdfReadergetReader()Gets the underlying PdfReader.PdfSignatureAppearancegetSignatureAppearance()Gets the signing instance.PdfContentBytegetUnderContent(int pageNum)Gets aPdfContentByteto write under the page of the original document.PdfWritergetWriter()Gets the underlying PdfWriter.voidinsertPage(int pageNumber, Rectangle mediabox)Inserts a blank page.booleanisFullCompression()Gets the 1.5 compression status.booleanisRotateContents()Checks if the content is automatically adjusted to compensate the original page rotation.booleanpartialFormFlattening(String name)Addsnameto the list of fields that will be flattened on close, all the other fields will remain.voidsetDuration(int seconds, int page)Sets the display duration for the page (for presentations)voidsetEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, boolean strength128Bits)Sets the encryption options for this document.voidsetEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType)Sets the encryption options for this document.voidsetFormFlattening(boolean flat)Determines if the fields are flattened on close.voidsetFreeTextFlattening(boolean flat)Determines if the FreeText annotations are flattened on close.voidsetFullCompression()Sets the document's compression to the new 1.5 mode with object streams and xref streams.voidsetMoreInfo(HashMap moreInfo)An optionalStringmap to add or change values in the info dictionary.voidsetOutlines(List outlines)Sets the bookmarks.voidsetPageAction(PdfName actionType, PdfAction action, int page)Sets the open and close page additional action.voidsetRotateContents(boolean rotateContents)Flags the content to be automatically adjusted to compensate the original page rotation.voidsetTransition(PdfTransition transition, int page)Sets the transition for the pagevoidsetViewerPreferences(int preferences)Sets the viewer preferences.voidsetXmpMetadata(byte[] xmp)Sets the XMP metadata.
-
-
-
Field Detail
-
stamper
protected PdfStamperImp stamper
The writer
-
-
Constructor Detail
-
PdfStamper
public PdfStamper(PdfReader reader, OutputStream os) throws DocumentException, 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 errorIOException- on error
-
PdfStamper
public PdfStamper(PdfReader reader, OutputStream os, char pdfVersion) throws DocumentException, IOException
Starts the process of adding extra content to an existing PDF document.- 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 document- Throws:
DocumentException- on errorIOException- on error
-
PdfStamper
public PdfStamper(PdfReader reader, OutputStream os, char pdfVersion, boolean append) throws DocumentException, 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- iftrueappends 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 errorIOException- on error
-
-
Method Detail
-
getMoreInfo
public HashMap getMoreInfo()
Gets the optionalStringmap to add or change values in the info dictionary.- Returns:
- the map or
null
-
setMoreInfo
public void setMoreInfo(HashMap moreInfo)
An optionalStringmap to add or change values in the info dictionary. Entries withnullvalues 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 includingpageNumberwill be shifted up. IfpageNumberis 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, IOExceptionCloses 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
PdfSignatureAppearanceinstance.- Throws:
DocumentException- on errorIOException- on error
-
getUnderContent
public PdfContentByte getUnderContent(int pageNum)
Gets aPdfContentByteto write under the page of the original document.- Parameters:
pageNum- the page number where the extra content is written- Returns:
- a
PdfContentByteto write under the page of the original document
-
getOverContent
public PdfContentByte getOverContent(int pageNum)
Gets aPdfContentByteto write over the page of the original document.- Parameters:
pageNum- the page number where the extra content is written- Returns:
- a
PdfContentByteto write over the page of the original document
-
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-trueto set auto-rotation,falseotherwise
-
setEncryption
public void setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, boolean strength128Bits) throws DocumentExceptionSets 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-truefor 128 bit key length,falsefor 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 DocumentExceptionSets 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 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
-
getImportedPage
public PdfImportedPage getImportedPage(PdfReader reader, int pageNumber) throws IOException
Gets a page from other PDF document. Note that calling this method more than once with the same parameters will retrieve the same object.- Parameters:
reader- the PDF document where the page ispageNumber- the page number. The first page is 1- Returns:
- the template representing the imported page
- Throws:
IOException
-
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 theAcroFieldsobject that allows to get and set field values and to merge FDF forms.- Returns:
- the
AcroFieldsobject
-
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-trueto flatten the fields,falseto keep the fields
-
setFreeTextFlattening
public void setFreeTextFlattening(boolean flat)
Determines if the FreeText annotations are flattened on close.- Parameters:
flat-trueto 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
-
addComments
public void addComments(FdfReader fdf) throws IOException
Adds the comments present in an FDF file.- Parameters:
fdf- the FDF file- Throws:
IOException- on error
-
setOutlines
public void setOutlines(List outlines) throws IOException
Sets the bookmarks. The list structure is defined inSimpleBookmark.- Parameters:
outlines- the bookmarks ornullto remove any- Throws:
IOException- on error
-
partialFormFlattening
public boolean partialFormFlattening(String name)
Addsnameto the list of fields that will be flattened on close, all the other fields will remain. If this method is never called or is called with invalid field names, all the fields will be flattened.Calling
setFormFlattening(true)is needed to have any kind of flattening.- Parameters:
name- the field name- Returns:
trueif the field exists,falseotherwise
-
addJavaScript
public void addJavaScript(String js)
Adds a JavaScript action at the document level. When the document opens all this JavaScript runs.- Parameters:
js- the JavaScript code
-
setViewerPreferences
public void setViewerPreferences(int preferences)
Sets the viewer preferences.- Parameters:
preferences- the viewer preferences- See Also:
PdfWriter.setViewerPreferences(int)
-
setXmpMetadata
public void setXmpMetadata(byte[] xmp)
Sets the XMP metadata.- Parameters:
xmp-- See Also:
PdfWriter.setXmpMetadata(byte[])
-
isFullCompression
public boolean isFullCompression()
Gets the 1.5 compression status.- Returns:
trueif 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.
-
setPageAction
public void setPageAction(PdfName actionType, PdfAction action, int page) throws PdfException
Sets the open and close page additional action.- Parameters:
actionType- the action type. It can bePdfWriter.PAGE_OPENorPdfWriter.PAGE_CLOSEaction- the action to performpage- the page where the action will be applied. The first page is 1- Throws:
PdfException- if the action type is invalid
-
setDuration
public void setDuration(int seconds, int page)Sets the display duration for the page (for presentations)- Parameters:
seconds- the number of seconds to display the page. A negative value removes the entrypage- the page where the duration will be applied. The first page is 1
-
setTransition
public void setTransition(PdfTransition transition, int page)
Sets the transition for the page- Parameters:
transition- the transition object. Anullremoves the transitionpage- the page where the transition will be applied. The first page is 1
-
createSignature
public static PdfStamper createSignature(PdfReader reader, OutputStream os, char pdfVersion, File tempFile, boolean append) throws DocumentException, 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 ornullto 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 unlessosis null. In that case the document can be retrieved directly from the temporary file. If it'snullno temporary file will be created and memory will be usedappend- iftruethe signature and all the other content will be added as a new revision thus not invalidating existing signatures- Returns:
- a
PdfStamper - Throws:
DocumentException- on errorIOException- on error
-
createSignature
public static PdfStamper createSignature(PdfReader reader, OutputStream os, char pdfVersion) throws DocumentException, IOException
Applies a digital signature to a document. The returned PdfStamper can be used normally as the signature is only applied when closing.Note that the pdf is created in memory.
A possible use 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'); 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 streampdfVersion- the new pdf version or '\0' to keep the same version as the original document- Returns:
- a
PdfStamper - Throws:
DocumentException- on errorIOException- on error
-
createSignature
public static PdfStamper createSignature(PdfReader reader, OutputStream os, char pdfVersion, File tempFile) throws DocumentException, IOException
Applies a digital signature to a document. The returned PdfStamper can be used normally as the signature is only applied when closing.A possible use 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")); 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 ornullto 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 unlessosis null. In that case the document can be retrieved directly from the temporary file. If it'snullno temporary file will be created and memory will be used- Returns:
- a
PdfStamper - Throws:
DocumentException- on errorIOException- on error
-
-