Java API for encrypting / decrypting pdf files

后端 未结 3 2233
南方客
南方客 2020-12-28 22:27

I need to encrypt and decrypt pdf files. Is there a free or low cost Java API that does that ? Basically I need to hide files from normal users. Any other suggestion on achi

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-28 23:13

    Using PDFBox (based on Decrypt.java code) :

    PDDocument document = null;
    
    try
    {
        document = PDDocument.load( infile );
    
        if( document.isEncrypted() )
        {
            DecryptionMaterial decryptionMaterial = null;
            decryptionMaterial = new StandardDecryptionMaterial(password);
            document.openProtection(decryptionMaterial);
            AccessPermission ap = document.getCurrentAccessPermission();
            if(ap.isOwnerPermission())
            {
                document.setAllSecurityToBeRemoved(true);
                document.save( outfile );
            }
            else
            {
                throw new IOException(
                "Error: You are only allowed to decrypt a document with the owner password." );
            }
        }
        else
        {
            System.err.println( "Error: Document is not encrypted." );
        }
    }
    finally
    {
        if( document != null )
        {
            document.close();
        }
    }
    

提交回复
热议问题