public class PdfStamper extends Object implements PdfViewerPreferences, PdfEncryptionSettings
It is also possible to change the field values and to flatten them. New fields can be added but not flattened.
Modifier and Type | Field and Description |
---|---|
protected com.lowagie.text.pdf.PdfStamperImp |
stamper
The writer
|
Constructor and 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.
|
Modifier and Type | Method and Description |
---|---|
void |
addAnnotation(PdfAnnotation annot,
int page)
Adds an annotation of form field in a specific page.
|
void |
addComments(FdfReader fdf)
Adds the comments present in an FDF file.
|
void |
addFileAttachment(String description,
byte[] fileStore,
String file,
String fileDisplay)
Adds a file attachment at the document level.
|
void |
addFileAttachment(String description,
PdfFileSpecification fs)
Adds a file attachment at the document level.
|
void |
addJavaScript(String js)
Adds a JavaScript action at the document level.
|
PdfFormField |
addSignature(String name,
int page,
float llx,
float lly,
float urx,
float ury)
Adds an empty signature.
|
void |
addViewerPreference(PdfName key,
PdfObject value)
Adds a viewer preference
|
void |
close()
Closes the document.
|
static PdfStamper |
createSignature(PdfReader reader,
OutputStream os,
char pdfVersion)
Applies a digital signature to a document.
|
static PdfStamper |
createSignature(PdfReader reader,
OutputStream os,
char pdfVersion,
File tempFile)
Applies a digital signature to a document.
|
static PdfStamper |
createSignature(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.
|
AcroFields |
getAcroFields()
Gets the
AcroFields object that allows to get and set field values
and to merge FDF forms. |
Calendar |
getEnforcedModificationDate()
Returns the enforced modification date, used to specifically override the PDF modification date (ModDate) property when creating and signing the PDF file.
|
PdfImportedPage |
getImportedPage(PdfReader reader,
int pageNumber)
Gets a page from other PDF document.
|
HashMap |
getMoreInfo()
Gets the optional
String map to add or change values in
the info dictionary. |
PdfContentByte |
getOverContent(int pageNum)
Gets a
PdfContentByte to write over the page of
the original document. |
PdfObject |
getOverrideFileId()
Returns the enforced PDF file ID, used to specifically override the created PDF file ID when creating and signing the PDF file.
|
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.
|
PdfContentByte |
getUnderContent(int pageNum)
Gets a
PdfContentByte to write under the page of
the original document. |
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 |
isIncludeFileID()
Returns if the file ID property should be included in the PDF file header when creating and signing the PDF file.
|
boolean |
isRotateContents()
Checks if the content is automatically adjusted to compensate
the original page rotation.
|
void |
makePackage(PdfCollection collection)
Adds or replaces the Collection Dictionary in the Catalog.
|
void |
makePackage(PdfName initialView)
This is the most simple way to change a PDF into a
portable collection.
|
boolean |
partialFormFlattening(String name)
Adds
name to the list of fields that will be flattened on close,
all the other fields will remain. |
void |
replacePage(PdfReader r,
int pageImported,
int pageReplaced)
Replaces a page from this document with a page from other document.
|
void |
setDuration(int seconds,
int page)
Sets the display duration for the page (for presentations)
|
void |
setEncryption(boolean strength,
String userPassword,
String ownerPassword,
int permissions)
Sets the encryption options for this document.
|
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.
|
void |
setEncryption(Certificate[] certs,
int[] permissions,
int encryptionType)
Sets the certificate encryption options for this document.
|
void |
setEncryption(int encryptionType,
String userPassword,
String ownerPassword,
int permissions)
Sets the encryption options for this document.
|
void |
setEnforcedModificationDate(Calendar modificationDate)
Specifies the enforced modification date, used to specifically override the PDF modification date (ModDate) property when creating and signing the PDF file.
|
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 |
setIncludeFileID(boolean includeFileID)
Specifies if the file ID property should be included in the PDF file header when creating and stamping the PDF file.
|
void |
setMoreInfo(HashMap moreInfo)
An optional
String map to add or change values in
the info dictionary. |
void |
setOutlines(List outlines)
Sets the bookmarks.
|
void |
setOverrideFileId(PdfObject overrideFileId)
Specifies the enforced PDF file ID, used to specifically override the PDF file ID when creating and signing the PDF file.
|
void |
setPageAction(PdfName actionType,
PdfAction action,
int page)
Sets the open and close page additional action.
|
void |
setRotateContents(boolean rotateContents)
Flags the content to be automatically adjusted to compensate
the original page rotation.
|
void |
setThumbnail(Image image,
int page)
Sets the thumbnail image for a page.
|
void |
setTransition(PdfTransition transition,
int page)
Sets the transition for the page
|
void |
setViewerPreferences(int preferences)
Sets the viewer preferences.
|
void |
setXmpMetadata(byte[] xmp)
Sets the XMP metadata.
|
public PdfStamper(PdfReader reader, OutputStream os) throws DocumentException, IOException
reader
- the original document. It cannot be reusedos
- the output streamDocumentException
- on errorIOException
- on errorpublic PdfStamper(PdfReader reader, OutputStream os, char pdfVersion) throws DocumentException, IOException
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
documentDocumentException
- on errorIOException
- on errorpublic PdfStamper(PdfReader reader, OutputStream os, char pdfVersion, boolean append) throws DocumentException, IOException
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
- if true
appends the document changes as a new revision. This is
only useful for multiple signatures as nothing is gained in speed or memoryDocumentException
- on errorIOException
- on errorpublic HashMap getMoreInfo()
String
map to add or change values in
the info dictionary.null
public void setMoreInfo(HashMap moreInfo)
String
map to add or change values in
the info dictionary. Entries with null
values delete the key in the original info dictionarymoreInfo
- additional entries to the info dictionarypublic void replacePage(PdfReader r, int pageImported, int pageReplaced)
r
- the PdfReader
from where the new page will be importedpageImported
- the page number of the imported pagepageReplaced
- the page to replace in this documentpublic void insertPage(int pageNumber, Rectangle mediabox)
pageNumber
will
be shifted up. If pageNumber
is bigger than the total number of pages
the new page will be the last one.pageNumber
- the page number position where the new page will be insertedmediabox
- the size of the new pagepublic PdfSignatureAppearance getSignatureAppearance()
public void close() throws DocumentException, IOException
If closing a signed document with an external signature the closing must be done
in the PdfSignatureAppearance
instance.
DocumentException
- on errorIOException
- on errorpublic PdfContentByte getUnderContent(int pageNum)
PdfContentByte
to write under the page of
the original document.pageNum
- the page number where the extra content is writtenPdfContentByte
to write under the page of
the original documentpublic PdfContentByte getOverContent(int pageNum)
PdfContentByte
to write over the page of
the original document.pageNum
- the page number where the extra content is writtenPdfContentByte
to write over the page of
the original documentpublic boolean isRotateContents()
public void setRotateContents(boolean rotateContents)
true
.rotateContents
- true
to set auto-rotation, false
otherwisepublic void setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, boolean strength128Bits) throws DocumentException
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 lengthDocumentException
- if anything was already written to the outputpublic void setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType) throws DocumentException
setEncryption
in interface PdfEncryptionSettings
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 cleartextDocumentException
- if the document is already openpublic void setEncryption(boolean strength, String userPassword, String ownerPassword, int permissions) throws DocumentException
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 permissionsDocumentException
- if anything was already written to the outputpublic void setEncryption(int encryptionType, String userPassword, String ownerPassword, int permissions) throws DocumentException
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 permissionsDocumentException
- if anything was already written to the outputpublic void setEncryption(Certificate[] certs, int[] permissions, int encryptionType) throws DocumentException
setEncryption
in interface PdfEncryptionSettings
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.DocumentException
- if the encryption was set too latepublic PdfImportedPage getImportedPage(PdfReader reader, int pageNumber)
reader
- the PDF document where the page ispageNumber
- the page number. The first page is 1public PdfWriter getWriter()
public PdfReader getReader()
public AcroFields getAcroFields()
AcroFields
object that allows to get and set field values
and to merge FDF forms.AcroFields
objectpublic void setFormFlattening(boolean flat)
addAnnotation(PdfAnnotation,int)
will never be flattened.flat
- true
to flatten the fields, false
to keep the fieldspublic void setFreeTextFlattening(boolean flat)
flat
- true
to flatten the FreeText annotations, false
(the default) to keep the FreeText annotations as active content.public void addAnnotation(PdfAnnotation annot, int page)
PdfAnnotation.setPlaceInPage(int)
.annot
- the annotationpage
- the pagepublic PdfFormField addSignature(String name, int page, float llx, float lly, float urx, float ury)
name
- the name of the signaturepage
- the page numberllx
- lower left x coordinate of the signature's positionlly
- lower left y coordinate of the signature's positionurx
- upper right x coordinate of the signature's positionury
- upper right y coordinate of the signature's positionpublic void addComments(FdfReader fdf) throws IOException
fdf
- the FDF fileIOException
- on errorpublic void setOutlines(List outlines)
SimpleBookmark
.outlines
- the bookmarks or null
to remove anypublic void setThumbnail(Image image, int page) throws DocumentException
image
- the imagepage
- the pagePdfException
- on errorDocumentException
- on errorpublic boolean partialFormFlattening(String name)
name
to 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.
name
- the field nametrue
if the field exists, false
otherwisepublic void addJavaScript(String js)
js
- the JavaScript codepublic void addFileAttachment(String description, byte[] fileStore, String file, String fileDisplay) throws IOException
description
- the file descriptionfileStore
- an array with the file. If it's null
the file will be read from the diskfile
- the path to the file. It will only be used if
fileStore
is not null
fileDisplay
- the actual file name stored in the pdfIOException
- on errorpublic void addFileAttachment(String description, PdfFileSpecification fs) throws IOException
description
- the file descriptionfs
- the file specificationIOException
public void makePackage(PdfName initialView)
initialView
- can be PdfName.D, PdfName.T or PdfName.Hpublic void makePackage(PdfCollection collection)
collection
- the new collection dictionary.public void setViewerPreferences(int preferences)
setViewerPreferences
in interface PdfViewerPreferences
preferences
- the viewer preferencesPdfViewerPreferences.setViewerPreferences(int)
public void addViewerPreference(PdfName key, PdfObject value)
addViewerPreference
in interface PdfViewerPreferences
key
- a key for a viewer preferencevalue
- the value for the viewer preferencePdfViewerPreferences.addViewerPreference(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject)
public void setXmpMetadata(byte[] xmp)
xmp
- PdfWriter.setXmpMetadata(byte[])
public boolean isFullCompression()
true
if the 1.5 compression is onpublic void setFullCompression()
public void setPageAction(PdfName actionType, PdfAction action, int page) throws PdfException
actionType
- the action type. It can be PdfWriter.PAGE_OPEN
or PdfWriter.PAGE_CLOSE
action
- the action to performpage
- the page where the action will be applied. The first page is 1PdfException
- if the action type is invalidpublic void setDuration(int seconds, int page)
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 1public void setTransition(PdfTransition transition, int page)
transition
- the transition object. A null
removes the transitionpage
- the page where the transition will be applied. The first page is 1public static PdfStamper createSignature(PdfReader reader, OutputStream os, char pdfVersion, File tempFile, boolean append) throws DocumentException, IOException
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();
reader
- the original documentos
- the output stream or null
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 unless os
is null.
In that case the document can be retrieved directly from the temporary file. If it's null
no temporary file will be created and memory will be usedappend
- if true
the signature and all the other content will be added as a
new revision thus not invalidating existing signaturesPdfStamper
DocumentException
- on errorIOException
- on errorpublic static PdfStamper createSignature(PdfReader reader, OutputStream os, char pdfVersion) throws DocumentException, IOException
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();
reader
- the original documentos
- the output streampdfVersion
- the new pdf version or '\0' to keep the same version as the original
documentPdfStamper
DocumentException
- on errorIOException
- on errorpublic static PdfStamper createSignature(PdfReader reader, OutputStream os, char pdfVersion, File tempFile) throws DocumentException, IOException
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();
reader
- the original documentos
- the output stream or null
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 unless os
is null.
In that case the document can be retrieved directly from the temporary file. If it's null
no temporary file will be created and memory will be usedPdfStamper
DocumentException
- on errorIOException
- on errorpublic Map getPdfLayers()
public void setIncludeFileID(boolean includeFileID)
includeFileID
- PdfName.ID
public boolean isIncludeFileID()
PdfName.ID
public void setOverrideFileId(PdfObject overrideFileId)
overrideFileId
- PdfName.ID
public PdfObject getOverrideFileId()
PdfName.ID
public Calendar getEnforcedModificationDate()
PdfName.MODDATE
public void setEnforcedModificationDate(Calendar modificationDate)
modificationDate
- enforced modification date.PdfName.MODDATE
Copyright © 2018. All rights reserved.