Class PdfStamper
- Namespace
- iTextSharp.text.pdf
- Assembly
- iTextSharp.LGPLv2.Core.dll
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)
public class PdfStamper : IPdfViewerPreferences, IPdfEncryptionSettings, IDisposable
- Inheritance
-
PdfStamper
- Implements
- Inherited Members
Constructors
PdfStamper(PdfReader, Stream)
Starts the process of adding extra content to an existing PDF document. @throws DocumentException on error @throws IOException on error
public PdfStamper(PdfReader reader, Stream os)
Parameters
PdfStamper(PdfReader, Stream, char)
Starts the process of adding extra content to an existing PDF document. document @throws DocumentException on error @throws IOException on error
public PdfStamper(PdfReader reader, Stream os, char pdfVersion)
Parameters
reader
PdfReaderthe original document. It cannot be reused
os
Streamthe output stream
pdfVersion
charthe new pdf version or '\0' to keep the same version as the original
PdfStamper(PdfReader, Stream, char, bool)
Starts the process of adding extra content to an existing PDF document, possibly as a new revision. document only useful for multiple signatures as nothing is gained in speed or memory @throws DocumentException on error @throws IOException on error
public PdfStamper(PdfReader reader, Stream os, char pdfVersion, bool append)
Parameters
reader
PdfReaderthe original document. It cannot be reused
os
Streamthe output stream
pdfVersion
charthe new pdf version or '\0' to keep the same version as the original
append
boolif true appends the document changes as a new revision. This is
Fields
Stamper
The writer
protected PdfStamperImp Stamper
Field Value
Properties
AcroFields
Gets the AcroFields object that allows to get and set field values and to merge FDF forms.
public AcroFields AcroFields { get; }
Property Value
- AcroFields
the AcroFields object
FormFlattening
Determines if the fields are flattened on close. The fields added with {@link #addAnnotation(PdfAnnotation,int)} will never be flattened. to keep the fields
public bool FormFlattening { set; }
Property Value
FreeTextFlattening
Determines if the FreeText annotations are flattened on close. (the default) to keep the FreeText annotations as active content.
public bool FreeTextFlattening { set; }
Property Value
FullCompression
Gets the 1.5 compression status.
public bool FullCompression { get; }
Property Value
- bool
true if the 1.5 compression is on
JavaScript
Adds a JavaScript action at the document level. When the document opens all this JavaScript runs. The existing JavaScript will be replaced.
public string JavaScript { set; }
Property Value
MoreInfo
Gets the optional String map to add or change values in the info dictionary.
public INullValueDictionary<string, string> MoreInfo { get; set; }
Property Value
- INullValueDictionary<string, string>
the map or null
Outlines
Sets the bookmarks. The list structure is defined in {@link SimpleBookmark}.
public IList<INullValueDictionary<string, object>> Outlines { set; }
Property Value
Reader
Gets the underlying PdfReader.
public PdfReader Reader { get; }
Property Value
- PdfReader
the underlying PdfReader
RotateContents
Checks if the content is automatically adjusted to compensate the original page rotation.
public bool RotateContents { get; set; }
Property Value
- bool
the auto-rotation status
SignatureAppearance
Gets the signing instance. The appearances and other parameters can the be set.
public PdfSignatureAppearance SignatureAppearance { get; }
Property Value
- PdfSignatureAppearance
the signing instance
ViewerPreferences
Sets the viewer preferences. @see PdfViewerPreferences#setViewerPreferences(int)
public virtual int ViewerPreferences { set; }
Property Value
Writer
Gets the underlying PdfWriter.
public PdfWriter Writer { get; }
Property Value
- PdfWriter
the underlying PdfWriter
XmpMetadata
Sets the XMP metadata. @see PdfWriter#setXmpMetadata(byte[])
public byte[] XmpMetadata { set; }
Property Value
- byte[]
Methods
AddAnnotation(PdfAnnotation, int)
Adds an annotation of form field in a specific page. This page number can be overridden with {@link PdfAnnotation#setPlaceInPage(int)}.
public void AddAnnotation(PdfAnnotation annot, int page)
Parameters
annot
PdfAnnotationthe annotation
page
intthe page
AddComments(FdfReader)
Adds the comments present in an FDF file. @throws IOException on error
public void AddComments(FdfReader fdf)
Parameters
fdf
FdfReaderthe FDF file
AddFileAttachment(string, byte[], string, string)
Adds a file attachment at the document level. Existing attachments will be kept. the file will be read from the disk fileStore is not null @throws IOException on error
public void AddFileAttachment(string description, byte[] fileStore, string file, string fileDisplay)
Parameters
description
stringthe file description
fileStore
byte[]an array with the file. If it's null
file
stringthe path to the file. It will only be used if
fileDisplay
stringthe actual file name stored in the pdf
AddFileAttachment(string, PdfFileSpecification)
Adds a file attachment at the document level. Existing attachments will be kept.
public void AddFileAttachment(string description, PdfFileSpecification fs)
Parameters
description
stringthe file description
fs
PdfFileSpecificationthe file specification
AddSignature(string, int, float, float, float, float)
Adds an empty signature. @since 2.1.4
public PdfFormField AddSignature(string name, int page, float llx, float lly, float urx, float ury)
Parameters
name
stringthe name of the signature
page
intthe page number
llx
floatlower left x coordinate of the signature's position
lly
floatlower left y coordinate of the signature's position
urx
floatupper right x coordinate of the signature's position
ury
floatupper right y coordinate of the signature's position
Returns
- PdfFormField
a signature form field
AddViewerPreference(PdfName, PdfObject)
public virtual void AddViewerPreference(PdfName key, PdfObject value)
Parameters
Close()
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 error @throws IOException on error
public void Close()
CreateSignature(PdfReader, Stream, char)
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(); document @throws DocumentException on error @throws IOException on error
public static PdfStamper CreateSignature(PdfReader reader, Stream os, char pdfVersion)
Parameters
reader
PdfReaderthe original document
os
Streamthe output stream
pdfVersion
charthe new pdf version or '\0' to keep the same version as the original
Returns
- PdfStamper
a PdfStamper
CreateSignature(PdfReader, Stream, char, string)
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(); document 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 used @throws DocumentException on error @throws IOException on error
public static PdfStamper CreateSignature(PdfReader reader, Stream os, char pdfVersion, string tempFile)
Parameters
reader
PdfReaderthe original document
os
Streamthe output stream or null to keep the document in the temporary file
pdfVersion
charthe new pdf version or '\0' to keep the same version as the original
tempFile
stringlocation of the temporary file. If it's a directory a temporary file will be created there.
Returns
- PdfStamper
a PdfStamper
CreateSignature(PdfReader, Stream, char, string, bool)
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(); document 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 used new revision thus not invalidating existing signatures @throws DocumentException on error @throws IOException on error
public static PdfStamper CreateSignature(PdfReader reader, Stream os, char pdfVersion, string tempFile, bool append)
Parameters
reader
PdfReaderthe original document
os
Streamthe output stream or null to keep the document in the temporary file
pdfVersion
charthe new pdf version or '\0' to keep the same version as the original
tempFile
stringlocation of the temporary file. If it's a directory a temporary file will be created there.
append
boolif true the signature and all the other content will be added as a
Returns
- PdfStamper
a PdfStamper
Dispose()
public void Dispose()
GetImportedPage(PdfReader, int)
Gets a page from other PDF document. Note that calling this method more than once with the same parameters will retrieve the same object.
public PdfImportedPage GetImportedPage(PdfReader reader, int pageNumber)
Parameters
reader
PdfReaderthe PDF document where the page is
pageNumber
intthe page number. The first page is 1
Returns
- PdfImportedPage
the template representing the imported page
GetOverContent(int)
Gets a PdfContentByte to write over the page of the original document. the original document
public PdfContentByte GetOverContent(int pageNum)
Parameters
pageNum
intthe page number where the extra content is written
Returns
- PdfContentByte
a PdfContentByte to write over the page of
GetPdfLayers()
Gets the PdfLayer objects in an existing document as a Map with the names/titles of the layers as keys. @since 2.1.2
public INullValueDictionary<string, PdfLayer> GetPdfLayers()
Returns
- INullValueDictionary<string, PdfLayer>
a Map with all the PdfLayers in the document (and the name/title of the layer as key)
GetUnderContent(int)
Gets a PdfContentByte to write under the page of the original document. the original document
public PdfContentByte GetUnderContent(int pageNum)
Parameters
pageNum
intthe page number where the extra content is written
Returns
- PdfContentByte
a PdfContentByte to write under the page of
InsertPage(int, Rectangle)
Inserts a blank page. All the pages above and including pageNumber will be shifted up. If pageNumber is bigger than the total number of pages the new page will be the last one.
public void InsertPage(int pageNumber, Rectangle mediabox)
Parameters
pageNumber
intthe page number position where the new page will be inserted
mediabox
Rectanglethe size of the new page
MakePackage(PdfName)
This is the most simple way to change a PDF into a portable collection. Choose one of the following names: PdfName.D (detailed view) PdfName.T (tiled view) PdfName.H (hidden) Pass this name as a parameter and your PDF will be a portable collection with all the embedded and attached files as entries.
public void MakePackage(PdfName initialView)
Parameters
initialView
PdfNamecan be PdfName.D, PdfName.T or PdfName.H
MakePackage(PdfCollection)
Adds or replaces the Collection Dictionary in the Catalog.
public void MakePackage(PdfCollection collection)
Parameters
collection
PdfCollectionthe new collection dictionary.
PartialFormFlattening(string)
Adds 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.
public bool PartialFormFlattening(string name)
Parameters
name
stringthe field name
Returns
- bool
true if the field exists, false otherwise
ReplacePage(PdfReader, int, int)
Replaces a page from this document with a page from other document. Only the content is replaced not the fields and annotations. This method must be called before getOverContent() or getUndercontent() are called for the same page.
public void ReplacePage(PdfReader r, int pageImported, int pageReplaced)
Parameters
r
PdfReaderthe PdfReader from where the new page will be imported
pageImported
intthe page number of the imported page
pageReplaced
intthe page to replace in this document
SetDuration(int, int)
Sets the display duration for the page (for presentations)
public void SetDuration(int seconds, int page)
Parameters
seconds
intthe number of seconds to display the page. A negative value removes the entry
page
intthe page where the duration will be applied. The first page is 1
SetEncryption(X509Certificate[], int[], int)
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 @throws DocumentException if the encryption was set too late
public void SetEncryption(X509Certificate[] certs, int[] permissions, int encryptionType)
Parameters
certs
X509Certificate[]the public certificates to be used for the encryption
permissions
int[]the user permissions for each of the certicates
encryptionType
intthe type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.
SetEncryption(bool, string, string, int)
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. @throws DocumentException if anything was already written to the output
public void SetEncryption(bool strength, string userPassword, string ownerPassword, int permissions)
Parameters
strength
booltrue for 128 bit key length, false for 40 bit key length
userPassword
stringthe user password. Can be null or empty
ownerPassword
stringthe owner password. Can be null or empty
permissions
intthe user permissions
SetEncryption(byte[], byte[], int, bool)
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. @throws DocumentException if anything was already written to the output
public void SetEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, bool strength128Bits)
Parameters
userPassword
byte[]the user password. Can be null or empty
ownerPassword
byte[]the owner password. Can be null or empty
permissions
intthe user permissions
strength128Bits
booltrue for 128 bit key length, false for 40 bit key length
SetEncryption(byte[], byte[], int, int)
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. Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext @throws DocumentException if the document is already open
public void SetEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType)
Parameters
userPassword
byte[]the user password. Can be null or empty
ownerPassword
byte[]the owner password. Can be null or empty
permissions
intthe user permissions
encryptionType
intthe type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.
SetEncryption(int, string, string, int)
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. Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext @throws DocumentException if the document is already open
public void SetEncryption(int encryptionType, string userPassword, string ownerPassword, int permissions)
Parameters
encryptionType
intthe type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.
userPassword
stringthe user password. Can be null or empty
ownerPassword
stringthe owner password. Can be null or empty
permissions
intthe user permissions
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.
public void SetFullCompression()
SetPageAction(PdfName, PdfAction, int)
Sets the open and close page additional action. or PdfWriter.PAGE_CLOSE @throws PdfException if the action type is invalid
public void SetPageAction(PdfName actionType, PdfAction action, int page)
Parameters
actionType
PdfNamethe action type. It can be PdfWriter.PAGE_OPEN
action
PdfActionthe action to perform
page
intthe page where the action will be applied. The first page is 1
SetThumbnail(Image, int)
Sets the thumbnail image for a page. @throws PdfException on error @throws DocumentException on error
public void SetThumbnail(Image image, int page)
Parameters
SetTransition(PdfTransition, int)
Sets the transition for the page
public void SetTransition(PdfTransition transition, int page)
Parameters
transition
PdfTransitionthe transition object. A null removes the transition
page
intthe page where the transition will be applied. The first page is 1