Class PdfStamper

  • All Implemented Interfaces:
    PdfEncryptionSettings, PdfViewerPreferences
    Direct Known Subclasses:
    PdfAStamper

    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.

    • Constructor Summary

      Constructors 
      Modifier Constructor Description
      protected PdfStamper()  
        PdfStamper​(PdfReader reader, java.io.OutputStream os)
      Starts the process of adding extra content to an existing PDF document.
        PdfStamper​(PdfReader reader, java.io.OutputStream os, char pdfVersion)
      Starts the process of adding extra content to an existing PDF document.
        PdfStamper​(PdfReader reader, java.io.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
      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​(java.lang.String description, byte[] fileStore, java.lang.String file, java.lang.String fileDisplay)
      Adds a file attachment at the document level.
      void addFileAttachment​(java.lang.String description, PdfFileSpecification fs)
      Adds a file attachment at the document level.
      void addJavaScript​(java.lang.String js)
      Adds a JavaScript action at the document level.
      void addJavaScript​(java.lang.String name, java.lang.String js)
      Adds a JavaScript action at the document level.
      boolean addNamedDestination​(java.lang.String name, int page, PdfDestination dest)  
      PdfFormField addSignature​(java.lang.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, java.io.OutputStream os, char pdfVersion)
      Applies a digital signature to a document.
      static PdfStamper createSignature​(PdfReader reader, java.io.OutputStream os, char pdfVersion, java.io.File tempFile)
      Applies a digital signature to a 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 createXmlSignature​(PdfReader reader, java.io.OutputStream os)  
      void createXmpMetadata()  
      void flush()
      Causes any pending changes to the direct under/over content (e.g.
      AcroFields getAcroFields()
      Gets the AcroFields object that allows to get and set field values and to merge FDF forms.
      PdfImportedPage getImportedPage​(PdfReader reader, int pageNumber)
      Gets a page from other PDF document.
      LtvVerification getLtvVerification()  
      java.util.Map<java.lang.String,​java.lang.String> 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.
      java.util.Map<java.lang.String,​PdfLayer> 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.
      XmlSignatureAppearance getXmlSignatureAppearance()
      Gets the xml signing instance.
      XmpWriter getXmpWriter()  
      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.
      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.
      void markUsed​(PdfObject obj)
      Marks the specified object as used or changed.
      (package private) void mergeVerification()  
      boolean partialFormFlattening​(java.lang.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 setAnnotationFlattening​(boolean flat)
      Flatten annotations with an appearance stream on close().
      void setDuration​(int seconds, int page)
      Sets the display duration for the page (for presentations)
      void setEncryption​(boolean strength, java.lang.String userPassword, java.lang.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​(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<java.lang.String,​java.lang.String> moreInfo)
      An optional String map to add or change values in the info dictionary.
      void setOutlines​(java.util.List<java.util.HashMap<java.lang.String,​java.lang.Object>> outlines)
      Sets the bookmarks.
      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.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • 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.

        The reader will be closed when this PdfStamper is closed

        Parameters:
        reader - the original document. It cannot be reused
        os - the output stream
        Throws:
        DocumentException - on error
        java.io.IOException - on error
      • PdfStamper

        public PdfStamper​(PdfReader reader,
                          java.io.OutputStream os,
                          char pdfVersion)
                   throws DocumentException,
                          java.io.IOException
        Starts the process of adding extra content to an existing PDF document.

        The reader will be closed when this PdfStamper is closed

        Parameters:
        reader - the original document. It cannot be reused
        os - the output stream
        pdfVersion - the new pdf version or '\0' to keep the same version as the original document
        Throws:
        DocumentException - on error
        java.io.IOException - on error
      • PdfStamper

        public PdfStamper​(PdfReader reader,
                          java.io.OutputStream os,
                          char pdfVersion,
                          boolean append)
                   throws DocumentException,
                          java.io.IOException
        Starts the process of adding extra content to an existing PDF document, possibly as a new revision.

        The reader will be closed when this PdfStamper is closed

        Parameters:
        reader - the original document. It cannot be reused
        os - the output stream
        pdfVersion - the new pdf version or '\0' to keep the same version as the original document
        append - if true 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 error
        java.io.IOException - on error
      • PdfStamper

        protected PdfStamper()
    • Method Detail

      • getMoreInfo

        public java.util.Map<java.lang.String,​java.lang.String> getMoreInfo()
        Gets the optional String map to add or change values in the info dictionary.
        Returns:
        the map or null
      • setMoreInfo

        public void setMoreInfo​(java.util.Map<java.lang.String,​java.lang.String> moreInfo)
        An optional String map to add or change values in the info dictionary. Entries with null values delete the key in the original info dictionary
        Parameters:
        moreInfo - additional entries to the info dictionary
      • replacePage

        public void replacePage​(PdfReader r,
                                int pageImported,
                                int pageReplaced)
        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.
        Parameters:
        r - the PdfReader from where the new page will be imported
        pageImported - the page number of the imported page
        pageReplaced - the page to replace in this document
        Since:
        iText 2.1.1
      • insertPage

        public void insertPage​(int pageNumber,
                               Rectangle mediabox)
        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.
        Parameters:
        pageNumber - the page number position where the new page will be inserted
        mediabox - 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
      • getXmlSignatureAppearance

        public XmlSignatureAppearance getXmlSignatureAppearance()
        Gets the xml signing instance. The appearances and other parameters can the be set.
        Returns:
        the xml signing instance
      • flush

        public void flush()
        Causes any pending changes to the direct under/over content (e.g. stamps) and page replacements to be applied to the output PDF. References to the adjusted content are released. If very large numbers of pages are being modified, call this method periodically to write the changes to the output PDF file and release the stamps from the heap. A few precautions about using this method: 1) After using flush() method, over/under content objects should be updated via getOverContent() or getUnderContent() calls respectively in case you want to make any further stamps to the same page; 2) PdfReader, that is associated with PdfStamper which is flushed, must not be used for any other purposes. This is due to the fact that after flush some new references in PdfReader's inner structure appear, but you won't be able to get actual objects behind those references.
      • 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 error
        java.io.IOException - on error
      • getUnderContent

        public PdfContentByte getUnderContent​(int pageNum)
        Gets a PdfContentByte to write under the page of the original document.
        Parameters:
        pageNum - the page number where the extra content is written
        Returns:
        a PdfContentByte to write under the page of the original document
      • getOverContent

        public PdfContentByte getOverContent​(int pageNum)
        Gets a PdfContentByte 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
      • 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 is true.
        Parameters:
        rotateContents - true to set auto-rotation, false otherwise
      • setEncryption

        public 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 empty
        ownerPassword - the owner password. Can be null or empty
        permissions - the user permissions
        strength128Bits - 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 interface PdfEncryptionSettings
        Parameters:
        userPassword - the user password. Can be null or empty
        ownerPassword - the owner password. Can be null or empty
        permissions - the user permissions
        encryptionType - the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128, ENCRYPTION_AES128 or ENCRYPTION_AES256. Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext
        Throws:
        DocumentException - if the document is already open
      • setEncryption

        public 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 length
        userPassword - the user password. Can be null or empty
        ownerPassword - the owner password. Can be null or empty
        permissions - the user permissions
        Throws:
        DocumentException - if anything was already written to the output
      • setEncryption

        public 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 cleartext
        userPassword - the user password. Can be null or empty
        ownerPassword - the owner password. Can be null or empty
        permissions - 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 interface PdfEncryptionSettings
        Parameters:
        certs - the public certificates to be used for the encryption
        permissions - the user permissions for each of the certificates
        encryptionType - the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128, ENCRYPTION_AES128 or ENCRYPTION_AES256.
        Throws:
        DocumentException - if the encryption was set too late
      • getImportedPage

        public PdfImportedPage getImportedPage​(PdfReader reader,
                                               int pageNumber)
        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 is
        pageNumber - the page number. The first page is 1
        Returns:
        the template representing the imported page
      • 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 the AcroFields 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 with addAnnotation(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.
      • setAnnotationFlattening

        public void setAnnotationFlattening​(boolean flat)
        Flatten annotations with an appearance stream on close().
        Parameters:
        flat - boolean to indicate whether iText should flatten annotations or not.
      • addAnnotation

        public void addAnnotation​(PdfAnnotation annot,
                                  int page)
        Adds an annotation of form field in a specific page. This page number can be overridden with PdfAnnotation.setPlaceInPage(int).
        Parameters:
        annot - the annotation
        page - the page
      • addSignature

        public PdfFormField addSignature​(java.lang.String name,
                                         int page,
                                         float llx,
                                         float lly,
                                         float urx,
                                         float ury)
        Adds an empty signature.
        Parameters:
        name - the name of the signature
        page - the page number
        llx - lower left x coordinate of the signature's position
        lly - lower left y coordinate of the signature's position
        urx - upper right x coordinate of the signature's position
        ury - upper right y coordinate of the signature's position
        Returns:
        a signature form field
        Since:
        2.1.4
      • addComments

        public void addComments​(FdfReader fdf)
                         throws java.io.IOException
        Adds the comments present in an FDF file.
        Parameters:
        fdf - the FDF file
        Throws:
        java.io.IOException - on error
      • setOutlines

        public void setOutlines​(java.util.List<java.util.HashMap<java.lang.String,​java.lang.Object>> outlines)
        Sets the bookmarks. The list structure is defined in SimpleBookmark.
        Parameters:
        outlines - the bookmarks or null to remove any
      • partialFormFlattening

        public boolean partialFormFlattening​(java.lang.String name)
        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.

        Parameters:
        name - the field name
        Returns:
        true if the field exists, false otherwise
      • addJavaScript

        public void addJavaScript​(java.lang.String js)
        Adds a JavaScript action at the document level. When the document opens all this JavaScript runs. The existing JavaScript will be replaced.
        Parameters:
        js - the JavaScript code
      • addJavaScript

        public void addJavaScript​(java.lang.String name,
                                  java.lang.String js)
        Adds a JavaScript action at the document level. When the document opens all this JavaScript runs. The existing JavaScript will be replaced.
        Parameters:
        name - the name for the JavaScript snippet in the name tree
        js - the JavaScript code
      • addFileAttachment

        public void addFileAttachment​(java.lang.String description,
                                      byte[] fileStore,
                                      java.lang.String file,
                                      java.lang.String fileDisplay)
                               throws java.io.IOException
        Adds a file attachment at the document level. Existing attachments will be kept.
        Parameters:
        description - the file description
        fileStore - an array with the file. If it's null the file will be read from the disk
        file - the path to the file. It will only be used if fileStore is not null
        fileDisplay - the actual file name stored in the pdf
        Throws:
        java.io.IOException - on error
      • addFileAttachment

        public 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 description
        fs - the file specification
        Throws:
        java.io.IOException
      • makePackage

        public void makePackage​(PdfName initialView)
        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.
        Parameters:
        initialView - can be PdfName.D, PdfName.T or PdfName.H
      • makePackage

        public void makePackage​(PdfCollection collection)
        Adds or replaces the Collection Dictionary in the Catalog.
        Parameters:
        collection - the new collection dictionary.
      • createXmpMetadata

        public void createXmpMetadata()
      • getXmpWriter

        public XmpWriter getXmpWriter()
      • isFullCompression

        public boolean isFullCompression()
        Gets the 1.5 compression status.
        Returns:
        true if the 1.5 compression is on
      • setFullCompression

        public void setFullCompression()
                                throws DocumentException
        Sets the document's compression to the new 1.5 mode with object streams and xref streams. Be attentive!!! If you want set full compression , you should set immediately after creating PdfStamper, before editing the document.It can be set once and it can't be unset.
        Throws:
        DocumentException
      • 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 be PdfWriter.PAGE_OPEN or PdfWriter.PAGE_CLOSE
        action - the action to perform
        page - 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 entry
        page - 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. A null removes the transition
        page - the page where the transition will be applied. The first page is 1
      • 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 document
        os - the output stream or null to keep the document in the temporary file
        pdfVersion - the new pdf version or '\0' to keep the same version as the original document
        tempFile - 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 used
        append - if true 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 error
        java.io.IOException - on error
      • createSignature

        public static PdfStamper createSignature​(PdfReader reader,
                                                 java.io.OutputStream os,
                                                 char pdfVersion)
                                          throws DocumentException,
                                                 java.io.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 document
        os - the output stream
        pdfVersion - the new pdf version or '\0' to keep the same version as the original document
        Returns:
        a PdfStamper
        Throws:
        DocumentException - on error
        java.io.IOException - on error
      • createSignature

        public static PdfStamper createSignature​(PdfReader reader,
                                                 java.io.OutputStream os,
                                                 char pdfVersion,
                                                 java.io.File tempFile)
                                          throws DocumentException,
                                                 java.io.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 document
        os - the output stream or null to keep the document in the temporary file
        pdfVersion - the new pdf version or '\0' to keep the same version as the original document
        tempFile - 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 used
        Returns:
        a PdfStamper
        Throws:
        DocumentException - on error
        java.io.IOException - on error
      • getPdfLayers

        public java.util.Map<java.lang.String,​PdfLayer> 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
      • markUsed

        public void markUsed​(PdfObject obj)
        Marks the specified object as used or changed. Used objects will be written to a new revision when using PdfStamper in append mode. The specified PdfObject needs to be an Indirect Reference or its getIndRef() method should not return null.
        Parameters:
        obj - the used PDF object
      • addNamedDestination

        public boolean addNamedDestination​(java.lang.String name,
                                           int page,
                                           PdfDestination dest)
                                    throws java.io.IOException
        Throws:
        java.io.IOException
      • mergeVerification

        void mergeVerification()
                        throws java.io.IOException
        Throws:
        java.io.IOException