如何使用 PDFBox 从 PDF 中删除特定图像 [英] How to remove a specific image from a PDF with PDFBox

查看:50
本文介绍了如何使用 PDFBox 从 PDF 中删除特定图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据其元数据从 PDF 文件中删除特定图像.可悲.我在互联网上找到的所有例子都使用了废弃的方法.

I need to remove a specific image from PDF file according its metadata. Sadly. all examples I can find in Internet are using discarded methods.

我是这样写的:

try (PDDocument doc = PDDocument.load(new ByteArrayInputStream(pdf))) {
doc.getPages().forEach(page ->
{
    PDResources resources = page.getResources();
    List<COSName> itemsToRemove = new ArrayList<>();

    resources.getXObjectNames().forEach(propertyName -> {
        if(!resources.isImageXObject(propertyName)) {
            return;
        }
        PDXObject pdxObject = resources.getXObject(propertyName);
        PDImageXObject pdImageXObject = (PDImageXObject)pdxObject;
        PDMetadata metadata = pdImageXObject.getMetadata();
        if(checkMetadata(metadata)){
            // What should I use here?
            page.getCOSObject().removeItem(propertyName);
        }
    });
    // Should I use page.setResources(resources); ?
 });
doc.save(baos);
} catch (Exception e) {
//Code here

}

推荐答案

它的工作方式与示例 RemoveAllText.java 中的工作方式相同,只是使用了不同的标签.

It works same way like it does in example RemoveAllText.java, just with different tag.

使用此示例中的代码,只需使用Do"而不是Tj".

Use code from this example, just use "Do" instead of "Tj".

当然,如果您需要加载元数据等,您应该枚举并检查图像抛出的页面资源(如我的示例)

Of course, if you need to load metadata, etc, you should enumerate and check images threw page resources (like in my example)

这篇关于如何使用 PDFBox 从 PDF 中删除特定图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆