您的位置 首页 java

Java 加密解密PowerPoint文档

在日常办公时,我们常会用PowerPoint幻灯片来制作设计方案、年终总结等。这类幻灯片中的内容大多会涉及一些重要的数据信息,为了避免泄露造成损失,我们时常需要对其进行加密保护。本教程将演示如何在Java程序中给PowerPoint文档加密、设置幻灯片为只读、修改加密文档的密码以及解密文档。

测试环境

在运行代码前,需要搭建测试环境。在电脑上安装JDK和IntelliJ IDEA,然后通过 E-iceblue中文官网 下载 Free Spire.Presentation for Java 控件,解压后将lib文件夹下的Spire.Presentation.jar手动导入IDEA。

代码示例

加密保护PowerPoint文档

 import com.spire.presentation.*;

public class Encrypt {
    public static void main(String[] args) throws Exception {
        //加载PowerPoint示例文档
        Presentation presentation = new Presentation();
        presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");

        //设置密码加密文档
        presentation.encrypt("abc123");

        //保存结果文档
        presentation.saveToFile("output/encrypt_output.pptx", FileFormat.PPTX_2013);
        presentation.dispose();
    }
}  

运行以上代码后,需输入设置的密码才能打开PowerPoint文档进行查看和编辑操作。如下图所示

设置PowerPoint幻灯片为只读

Free Spire.Presentation for Java还提供了Protect方法来保护文档。使用该保护方式后,用户需输入密码才能对文档内容进行编辑、打印等一系列操作,而无密码用户只能选择在只读模式下查看文档。

 import com.spire.presentation.*;
public class ReadOnly {
    public static void main(String[] args) throws Exception {
        //加载PowerPoint示例文档
        Presentation presentation = new Presentation();
        presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");

        //设置密码保护文档
        presentation.protect("hij789");

        //保存结果文档
        presentation.saveToFile("output/setDocumentReadOnly_output.pptx", FileFormat.PPTX_2013);
        presentation.dispose();
    }
}  

修改加密文档的密码

Free Spire.Presentation for Java支持使用RemoveEncryption方法来解除加密,再调用加密方法设置新密码来加密文档。

 import com.spire.presentation.*;
public class ModifyPassword {
    public static void main(String[] args) throws Exception {
        //加载受密码保护的PowerPoint示例文档
        Presentation presentation = new Presentation();
        presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\encrypt_output.pptx", "abc123");

        //移除密码
        presentation.removeEncryption();

        //重新设置新密码保护文档
        presentation.protect("def456");

        //保存结果文档
        presentation.saveToFile("output/modifyPasswordOfEncryptedPPT.pptx", FileFormat.PPTX_2013);
    }
}  

解密文档

 import com.spire.presentation.*;

public class RemoveEncryption {
    public static void main(String[] args) throws Exception {
        //加载受密码保护的PowerPoint示例文档
        Presentation presentation = new Presentation();
        presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\encrypt_output.pptx", "abc123");

        //移除密码
        presentation.removeEncryption();

        //保存结果文档
        presentation.saveToFile("output/removeEncryption.pptx", FileFormat.PPTX_2013);
    }
}
  

文章来源:智云一二三科技

文章标题:Java 加密解密PowerPoint文档

文章地址:https://www.zhihuclub.com/172040.shtml

关于作者: 智云科技

热门文章

网站地图