如何使用 Apache PDFBox 从 PDF 中的按钮图标提取图像?

2024-04-10

我想使用 java netbeans 从 pdf 中的按钮获取图像图标,并将其放在某个面板中。 然而我在这里碰了砖头。 我使用 PDFBox 作为我的 PDF 导出器,但我似乎理解不够。 我已经成功地从表单字段中读取内容,但是只要我尝试在 PDFBox 中找到它,就没有按钮提取器。 我该怎么做呢?是否可以使用这种方法,或者有其他方法吗? 提前致谢。

编辑 : 我已经发现使用以下代码来使用示例实用程序中的图像来提取图像:

       File myFile = new File(filename);
        try { 

            //PDDocument pdDoc = PDDocument.loadNonSeq( myFile, null );
            PDDocument pdDoc = null;
            pdDoc = PDDocument.load( myFile );
            PDDocumentCatalog pdCatalog = pdDoc.getDocumentCatalog();
            PDAcroForm pdAcroForm = pdCatalog.getAcroForm();
            // dipakai untuk membaca isi file

            List pages = pdDoc.getDocumentCatalog().getAllPages();
            Iterator iter = pages.iterator();
             while( iter.hasNext() )
             {
                 PDPage page = (PDPage)iter.next();
                 PDResources resources = page.getResources();
                 Map images = resources.getImages();
                 if( images != null )
                 {
                     Iterator imageIter = images.keySet().iterator();
                     while( imageIter.hasNext() )
                     {
                         String key = (String  )imageIter.next();
                         PDXObjectImage image = (PDXObjectImage)images.get(key);
                         BufferedImage imagedisplay= image.getRGBImage();
                         jLabel5.setIcon(new ImageIcon(imagedisplay)); // NOI18N                                 
                     }
                 }
             }


        } catch (Exception e) {
               JOptionPane.showMessageDialog(null, "error " + e.getMessage());


        }

但是我仍然无法读取按钮图像。 顺便说一句,我阅读了本页的教程,将按钮图像添加到 pdf 中。https://acrobatusers.com/tutorials/how-to-create-a-button-form-field-to-insert-a-pdf-file https://acrobatusers.com/tutorials/how-to-create-a-button-form-field-to-insert-a-pdf-file
第二次编辑: 在这里我还为您提供了带有图标的 pdf 的链接。PDF Link http://www.docdroid.net/TDGVQzg/imageicon.pdf.html。 先感谢您。


我认为当你谈论时你指的是交互式表单按钮PDF 中的按钮.

一般来说

PDFBox 中的按钮没有明确的图标提取器。但是,由于带有自定义图标的按钮(以及一般的注释)将这些图标定义为其外观的一部分,因此可以简单地(递归地)遍历注释外观的资源并收集XObject带有子类型的 sImage:

public void extractAnnotationImages(PDDocument document, String fileNameFormat) throws IOException
{
    List<PDPage> pages = document.getDocumentCatalog().getAllPages();
    if (pages == null)
        return;

    for (int i = 0; i < pages.size(); i++)
    {
        String pageFormat = String.format(fileNameFormat, "-" + i + "%s", "%s");
        extractAnnotationImages(pages.get(i), pageFormat);
    }
}

public void extractAnnotationImages(PDPage page, String pageFormat) throws IOException
{
    List<PDAnnotation> annotations = page.getAnnotations();
    if (annotations == null)
        return;

    for (int i = 0; i < annotations.size(); i++)
    {
        PDAnnotation annotation = annotations.get(i);
        String annotationFormat = annotation.getAnnotationName() != null && annotation.getAnnotationName().length() > 0
                ? String.format(pageFormat, "-" + annotation.getAnnotationName() + "%s", "%s")
                : String.format(pageFormat, "-" + i + "%s", "%s");
        extractAnnotationImages(annotation, annotationFormat);
    }
}

public void extractAnnotationImages(PDAnnotation annotation, String annotationFormat) throws IOException
{
    PDAppearanceDictionary appearance = annotation.getAppearance();
    extractAnnotationImages(appearance.getDownAppearance(), String.format(annotationFormat, "-Down%s", "%s"));
    extractAnnotationImages(appearance.getNormalAppearance(), String.format(annotationFormat, "-Normal%s", "%s"));
    extractAnnotationImages(appearance.getRolloverAppearance(), String.format(annotationFormat, "-Rollover%s", "%s"));
}

public void extractAnnotationImages(Map<String, PDAppearanceStream> stateAppearances, String stateFormat) throws IOException
{
    if (stateAppearances == null)
        return;

    for (Map.Entry<String, PDAppearanceStream> entry: stateAppearances.entrySet())
    {
        String appearanceFormat = String.format(stateFormat, "-" + entry.getKey() + "%s", "%s");
        extractAnnotationImages(entry.getValue(), appearanceFormat);
    }
}

public void extractAnnotationImages(PDAppearanceStream appearance, String appearanceFormat) throws IOException
{
    PDResources resources = appearance.getResources();
    if (resources == null)
        return;
    Map<String, PDXObject> xObjects = resources.getXObjects();
    if (xObjects == null)
        return;

    for (Map.Entry<String, PDXObject> entry : xObjects.entrySet())
    {
        PDXObject xObject = entry.getValue();
        String xObjectFormat = String.format(appearanceFormat, "-" + entry.getKey() + "%s", "%s");
        if (xObject instanceof PDXObjectForm)
            extractAnnotationImages((PDXObjectForm)xObject, xObjectFormat);
        else if (xObject instanceof PDXObjectImage)
            extractAnnotationImages((PDXObjectImage)xObject, xObjectFormat);
    }
}

public void extractAnnotationImages(PDXObjectForm form, String imageFormat) throws IOException
{
    PDResources resources = form.getResources();
    if (resources == null)
        return;
    Map<String, PDXObject> xObjects = resources.getXObjects();
    if (xObjects == null)
        return;

    for (Map.Entry<String, PDXObject> entry : xObjects.entrySet())
    {
        PDXObject xObject = entry.getValue();
        String xObjectFormat = String.format(imageFormat, "-" + entry.getKey() + "%s", "%s");
        if (xObject instanceof PDXObjectForm)
            extractAnnotationImages((PDXObjectForm)xObject, xObjectFormat);
        else if (xObject instanceof PDXObjectImage)
            extractAnnotationImages((PDXObjectImage)xObject, xObjectFormat);
    }
}

public void extractAnnotationImages(PDXObjectImage image, String imageFormat) throws IOException
{
    image.write2OutputStream(new FileOutputStream(String.format(imageFormat, "", image.getSuffix())));
}

(from ExtractAnnotationImageTest.java https://github.com/mkl-public/testarea-pdfbox1/blob/master/src/test/java/mkl/testarea/pdfbox1/extract/ExtractAnnotationImageTest.java)

不幸的是,OP没有提供示例PDF,所以我将代码应用到这个示例文件 http://examples.itextpdf.com/results/part2/chapter08/buttons.pdf

(存储为资源)如下所示:

/**
 * Test using <a href="http://examples.itextpdf.com/results/part2/chapter08/buttons.pdf">buttons.pdf</a>
 * created by <a href="http://itextpdf.com/examples/iia.php?id=154">part2.chapter08.Buttons</a>
 * from ITEXT IN ACTION — SECOND EDITION.
 */
@Test
public void testButtonsPdf() throws IOException
{
    try (InputStream resource = getClass().getResourceAsStream("buttons.pdf"))
    {
        PDDocument document = PDDocument.load(resource);
        extractAnnotationImages(document, new File(RESULT_FOLDER, "buttons%s.%s").toString());;
    }
}

(from ExtractAnnotationImageTest.java https://github.com/mkl-public/testarea-pdfbox1/blob/master/src/test/java/mkl/testarea/pdfbox1/extract/ExtractAnnotationImageTest.java)

并得到这些图像:

and

这里有两个问题:

  • 我们提取所有图片资源附加到注释外观并且不检查它们是否实际上是used外观流中的任何位置。因此,您可能会发现比预期更多的图标。在上面的情况下,第一个图像不用作单独的资源,而仅用作第二个图像的掩码。
  • 我们提取仅图片资源,不是内联图像,因此可能会丢失一些图像。

因此,请将此代码与您的 PDF 一起检查。如果需要的话,可以改进。

OP的文件

同时OP提供了一个示例文件图像图标.pdf https://github.com/mkl-public/testarea-pdfbox1/blob/master/src/test/resources/mkl/testarea/pdfbox1/extract/imageicon.pdf

像这样调用上面的方法

/**
 * Test using <a href="http://www.docdroid.net/TDGVQzg/imageicon.pdf.html">imageicon.pdf</a>
 * created by the OP.
 */
@Test
public void testImageiconPdf() throws IOException
{
    try (InputStream resource = getClass().getResourceAsStream("imageicon.pdf"))
    {
        PDDocument document = PDDocument.load(resource);
        extractAnnotationImages(document, new File(RESULT_FOLDER, "imageicon%s.%s").toString());;
    }
}

(from ExtractAnnotationImageTest.java https://github.com/mkl-public/testarea-pdfbox1/blob/master/src/test/java/mkl/testarea/pdfbox1/extract/ExtractAnnotationImageTest.java)

输出此图像:

因此,它工作得很好!

作为独立工具开始

OP 在评论中指出

使用 junit 测试方法仍然令人困惑,但是当我尝试将其调用到我的主程序中时,它总是返回“流关闭”错误。我已经将文件放在与我的 jar 相同的目录中,也尝试手动给出路径,但仍然出现相同的错误。

因此,我添加了一个main方法到类以允许它

  1. 无需 JUnit 框架即可启动
  2. 从本地文件系统中任意位置的 PDF 中提取,该文件名在命令行上给出。

In code:

public static void main(String[] args) throws IOException
{
    ExtractAnnotationImageTest extractor = new ExtractAnnotationImageTest();

    for (String arg : args)
    {
        try (PDDocument document = PDDocument.load(arg))
        {
            extractor.extractAnnotationImages(document, arg+"%s.%s");;
        }
    }
}

(from ExtractAnnotationImageTest.java https://github.com/mkl-public/testarea-pdfbox1/blob/master/src/test/java/mkl/testarea/pdfbox1/extract/ExtractAnnotationImageTest.java)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Apache PDFBox 从 PDF 中的按钮图标提取图像? 的相关文章

随机推荐