Search code examples
itext7

iText7 Encryption PdfDocument


In upgrading iText7 I see there need to be a EncryptionConstants.ENCRYPTION_AES_128 Is that correct. I am also not seeing how to add the writerProperties to my PdfDocument

Old Version

pdfDocument.Writer.SetEncryption(true, null, null, PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING);

New Version

WriterProperties writerProperties = new WriterProperties();
writerProperties.SetStandardEncryption(null, null, EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_COPY, EncryptionConstants.ENCRYPTION_AES_128);

Solution

  • Please check the below code of iText 7 for adding or encrypting pdf files with owner and user password.

    public class EncryptPdf
    {
        public static readonly String DEST = "results/sandbox/security/encrypt_pdf.pdf";
        public static readonly String SRC = "../../../resources/pdfs/hello.pdf";
    
        public static readonly String OWNER_PASSWORD = "World";
        public static readonly String USER_PASSWORD = "Hello";
    
        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
    
            new EncryptPdf().ManipulatePdf(DEST);
        }
    
        protected void ManipulatePdf(String dest)
        {
            PdfDocument document = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest,
                new WriterProperties().SetStandardEncryption(
                    Encoding.UTF8.GetBytes(USER_PASSWORD),
                    Encoding.UTF8.GetBytes(OWNER_PASSWORD),
                    EncryptionConstants.ALLOW_PRINTING,
                    EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA
                )));
            document.Close();
        }
    }