本快速教程通过分享配置详细信息和完成任务的分步过程来指导如何从 Java 中的 PDF 文件中删除水印。它还包含一个可运行的示例代码,用于在 Java 中从 PDF 中删除水印,其中以简单的方式演示了完整的过程。您还将了解访问 PDF 页面上不同类型工件的过程。
用Java从PDF中删除水印的步骤
- 设置环境使用 Aspose.PDF for Java 删除水印
- 将目标 PDF 文件加载到其中几乎没有水印的 Document 对象中
- 创建一个列表来保存要删除的目标 Artifacts 的引用
- 解析所有页面及其各自的工件集合以检查水印
- 保存列表中的所有水印工件
- 删除所有选定的工件并保存生成的 PDF 文件
这些步骤描述了从 Java 中的 PDF 文档中删除水印的过程,方法是共享编写应用程序所需的资源,然后是一步一步的程序流程以及对重要类的介绍。在这个过程中,我们必须识别每个页面的所有水印工件,然后在最后删除它们。处理完所有页面或选定页面后,生成的 PDF 文件将保存在磁盘上。
用Java从PDF中删除所有水印的代码
import com.aspose.pdf.Document; | |
import com.aspose.pdf.Artifact; | |
import com.aspose.pdf.License; | |
import com.aspose.pdf.Page; | |
import java.util.*; | |
public class AsposeTest { | |
public static void main(String[] args) throws Exception {//Main function to remove watermark from PDF file in Java | |
// Instantiate the license | |
License lic = new License(); | |
lic.setLicense("Aspose.Total.lic"); | |
// Load the PDF | |
Document document = new Document("watermark.pdf"); | |
// Create a list | |
List<Artifact> artifactsToBeDeleted = new ArrayList<Artifact>(); | |
// Iterate through the pages of the PDF | |
for (Page page : document.getPages()) | |
{ | |
// Iterate the artifacts of the current page | |
for (Artifact item : page.getArtifacts()) | |
{ | |
// Check for the watermark type artifacts | |
if (item.getSubtype() == Artifact.ArtifactSubtype.Watermark) | |
{ | |
// Save reference of the artifact | |
artifactsToBeDeleted.add(item); | |
} | |
} | |
// Iterate the list of target artifacts | |
for (Artifact item : artifactsToBeDeleted) | |
{ | |
// Delete the artifact | |
page.getArtifacts().delete(item); | |
} | |
} | |
// Save the output PDF | |
document.save("withoutWatermark.pdf"); | |
System.out.println("Done"); | |
} | |
} |
此代码演示了从 Java 中的 PDF 中删除背景水印的过程。它使用 Page 类的 getArtifacts() 来访问所有工件,然后针对枚举器 Artifact.ArtifactSubtype.Watermark 测试它们以进行删除。您还可以为不同的操作获取其他类型的工件,例如页眉、页脚和背景。
这篇文章教我们用 Java 擦除 PDF 中的水印。如果您有兴趣了解添加水印的过程,请参阅 如何使用Java为PDF添加水印 上的文章。