通过 Maven 仓库安装 Spire 系列 Java 产品
import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;
import java.util.EnumSet;
public class Test {
public static void main(String[] args) {
// 创建PdfDocument实例
PdfDocument doc = new PdfDocument();
// 加载PDF文件
doc.loadFromFile("D:/var/sample.pdf");
// 添加一个空页(配合remove去除水印Evaluation Warning : The document was created with Spire.PDF for Java)
doc.getPages().add();
// 加密PDF文件
PdfEncryptionKeySize keySize = PdfEncryptionKeySize.Key_128_Bit;
String openPassword = "111"; // 打开文档时,仅用于查看文档
String permissionPassword = "222"; // 打开文档时,可编辑文档
EnumSet flags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Fill_Fields);
doc.getSecurity().encrypt(openPassword, permissionPassword, flags, keySize);
System.out.println("页数:" + doc.getPages().getCount());
// 移除第一个页
doc.getPages().remove(doc.getPages().get(doc.getPages().getCount()-1));
// 保存文件
doc.saveToFile("D:/var/Encrypt.pdf");
doc.close();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mavenTest</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf</artifactId>
<version>3.11.6</version>
</dependency>
</dependencies>
</project>