本教程将指导您如何使用 Java 从 PDF 中删除图像。您将获得设置 IDE 的详细信息、步骤列表和示例代码,以在选定页面上使用 Java 从 PDF 中删除所有图像。您可以根据图像索引值从页面中删除所有或选定的图像。
使用 Java 从 PDF 中删除图像的步骤
- 配置 IDE 以使用 Aspose.PDF for Java 从 PDF 中删除图像
- 将源 PDF 文件加载到 Document 对象中,用于删除图片
- 从已加载的包含图像的 PDF 访问目标页面
- 从选定页面访问 resources
- 获取资源中的图像数量并遍历所有图像
- 对集合中的每个图像调用 delete() 方法
- 保存输出 PDF 文件,其中选定的页面上没有图像
按照以下步骤了解如何使用 Java 从 PDF 中删除图像。每个 PDF 页面都包含资源中的图像集合,其中包含从集合中删除图像的方法。访问每个图像并使用 delete() 方法将其删除。
使用 Java 从 PDF 中删除 PIC 的代码
import com.aspose.pdf.*; | |
public class Main | |
{ | |
public static void main(String[] args) throws Exception // Delete PDF image in Java | |
{ | |
// Set the licenses | |
new License().setLicense("License.lic"); | |
// Open the document | |
Document pdfDocument = new Document("sample.pdf"); | |
// Delete all pictures | |
Page page = pdfDocument.getPages().get_Item(1); | |
Resources resources = page.getResources(); | |
int iSize = resources.getImages().size(); | |
for( int i = iSize ; i > 0; i-- ) | |
resources.getImages().delete(i); | |
// Save the PDF | |
pdfDocument.save("DeleteImages.pdf"); | |
System.out.println("PDF image deleted successfully"); | |
} | |
} |
This code demonstrates how to remove an image from a PDF using Java and repeat this process to remove all the images from a page. You may iterate through all the pages in the PDF starting from page 1 and remove all or selected images from the collection starting from index 1. 请注意,使用此功能时,您不能将索引 1 用于页面和图像。
本文教我们如何从 PDF 文件中删除页面。如果您想反转此过程(即插入图像),请参阅 如何使用 Java 将图像插入 PDF 上的文章。