【问题标题】:Jpg with black background (or completely white) when extracted via PDFBox from a PDF file通过 PDFBox 从 PDF 文件中提取时具有黑色背景(或完全白色)的 Jpg
【发布时间】:2015-11-29 10:24:27
【问题描述】:

我需要从 PDF 中提取图像,我是通过 PDFBox (v 1.8.9) 来完成的。 它适用于 90% 的情况,但我有一些图像在提取时以黑色背景(或完全白色)保存,即使它们在原始 pdf 中看起来非常好。我想这与那些 jpgs 文件有关。我应该在 jpg 中检查什么? 我正在尝试查看是否可以上传示例 pdf

这是相关的(相当标准的)代码...

    String pdfFile = promptForPDFFile(jf, "Select PDF file");
    // Load pdf file
    PDDocument document=PDDocument.load(pdfFile);
    //Get the pdf pages
    List pages = document.getDocumentCatalog().getAllPages();
    Iterator iter = pages.iterator();
    int pagetot = pages.size();

    int pagenum = 1;
    while( iter.hasNext() )
    {
        // Cycle on the pages for the images
        PDPage page = (PDPage)iter.next();

        PDResources resources = page.getResources();
        PDFTextStripper textStripper=new PDFTextStripper(); 
        textStripper.setStartPage(pagenum);
        textStripper.setEndPage(pagenum);
        Map images = resources.getImages();

        // Get page text content and use it as file name
        String pagecontent= textStripper.getText(document); 
        pagecontent = pagecontent.replaceAll("\n", "");
        pagecontent = pagecontent.replaceAll("\r", "");
        if( images != null )
        {
            Iterator imageIter = images.keySet().iterator();
            while( imageIter.hasNext() )
            {
                String key = (String)imageIter.next();
                PDXObjectImage image = (PDXObjectImage)images.get( key );
                File tempdir = new File(tempPath+"/temp/");
                tempdir.mkdirs();

                String name = tempPath+"/temp/"+pagecontent;
                //System.out.println( "Writing image:" + name );


                //Write the image to file
                image.write2file( name );


            }
        }
        pagenum ++;
        if (pagenum % 10 ==0)
        {
            System.out.print("\n--- "+ pagenum +"/"+pagetot);
        }
    }

提前致谢

【问题讨论】:

  • 请在某处上传 PDF,并说明哪些图像不正确。确保 jai_imageio.jar 和 levigo 插件在你的类路径中。即便如此,CMYK 色彩空间图像仍可能存在问题。在未发布的 2.0 版本中已经解决了这个问题。
  • 它们是来自客户的图像。如果可能的话,我更愿意通过邮件向您发送 pdf(如果这不违反 SO 政策)...您能给我发一封电子邮件,我会给您发送一份工作的 pdf 和一份不工作的。同时,我会查看您对插件的建议。
  • 当然,发送给 snafu dot de 的 tilman。如果可能,请发送一个小文件,即整个邮件不应大于 5MB。只需要非工作 PDF。提及细节,即您没有正确获取哪些图像。
  • 我已将 pdf 文件发送给您。仅供参考,这似乎与您在第一条评论中指出的两个插件无关。我已将它们添加到我的类路径中,但没有任何明显的改进。
  • 我正在写答案。你可能会喜欢它。

标签: java image pdf jpeg pdfbox


【解决方案1】:

我针对您发送给我的两个文件运行了ExtractImages.java。问题文件有 CMYK 图像,从 PDFDebugger 的截图可以看出:

问题是1.8版本不能正确处理CMYK图像。

但是有一个技巧: 图像使用 DCTDecode 过滤器进行编码,该过滤器是 JPEG。 PDF 中有“真正的 JPEG”。

我可以通过使用该工具的“-directJPEG”选项正确提取您的图像,该选项绕过 PDFBox 的解码机制,并“按原样”保存 JPEG 文件。

请注意,虽然这适用于您的文件,但如果图像具有在 PDF 中指定的外部色彩空间,它就无法正常工作。

这是完整的源代码。有关原始提取详细信息,请参见 writeJpeg2file()。

public class ExtractImages
{
    private int imageCounter = 1;

    private static final String PASSWORD = "-password";
    private static final String PREFIX = "-prefix";
    private static final String ADDKEY = "-addkey";
    private static final String NONSEQ = "-nonSeq";
    private static final String DIRECTJPEG = "-directJPEG";

    private static final List<String> DCT_FILTERS = new ArrayList<String>();

    static
    {
        DCT_FILTERS.add( COSName.DCT_DECODE.getName() );
        DCT_FILTERS.add( COSName.DCT_DECODE_ABBREVIATION.getName() );
    }

    private ExtractImages()
    {
    }

    /**
     * This is the entry point for the application.
     *
     * @param args The command-line arguments.
     *
     * @throws Exception If there is an error decrypting the document.
     */
    public static void main( String[] args ) throws Exception
    {
        ExtractImages extractor = new ExtractImages();
        extractor.extractImages( args );
    }

    private void extractImages( String[] args ) throws Exception
    {
        if( args.length < 1 || args.length > 4 )
        {
            usage();
        }
        else
        {
            String pdfFile = null;
            String password = "";
            String prefix = null;
            boolean addKey = false;
            boolean useNonSeqParser = false;
            boolean directJPEG = false;
            for( int i=0; i<args.length; i++ )
            {
                if( args[i].equals( PASSWORD ) )
                {
                    i++;
                    if( i >= args.length )
                    {
                        usage();
                    }
                    password = args[i];
                }
                else if( args[i].equals( PREFIX ) )
                {
                    i++;
                    if( i >= args.length )
                    {
                        usage();
                    }
                    prefix = args[i];
                }
                else if( args[i].equals( ADDKEY ) )
                {
                    addKey = true;
                }
                else if( args[i].equals( NONSEQ ) )
                {
                    useNonSeqParser = true;
                }
                else if( args[i].equals( DIRECTJPEG ) )
                {
                    directJPEG = true;
                }
                else
                {
                    if( pdfFile == null )
                    {
                        pdfFile = args[i];
                    }
                }
            }
            if(pdfFile == null)
            {
                usage();
            }
            else
            {
                if( prefix == null && pdfFile.length() >4 )
                {
                    prefix = pdfFile.substring( 0, pdfFile.length() -4 );
                }

                PDDocument document = null;

                try
                {
                    if (useNonSeqParser)
                    {
                        document = PDDocument.loadNonSeq(new File(pdfFile), null, password);
                    }
                    else
                    {
                        document = PDDocument.load( pdfFile );

                        if( document.isEncrypted() )
                        {
                            StandardDecryptionMaterial spm = new StandardDecryptionMaterial(password);
                            document.openProtection(spm);
                        }
                    }
                    AccessPermission ap = document.getCurrentAccessPermission();
                    if( ! ap.canExtractContent() )
                    {
                        throw new IOException(
                            "Error: You do not have permission to extract images." );
                    }

                    List pages = document.getDocumentCatalog().getAllPages();
                    Iterator iter = pages.iterator();
                    while( iter.hasNext() )
                    {
                        PDPage page = (PDPage)iter.next();
                        PDResources resources = page.getResources();
                        // extract all XObjectImages which are part of the page resources
                        processResources(resources, prefix, addKey, directJPEG);
                    }
                }
                finally
                {
                    if( document != null )
                    {
                        document.close();
                    }
                }
            }
        }
    }

    public void writeJpeg2file(PDJpeg image, String filename) throws IOException
    {
        FileOutputStream out = null;

        try
        {
            out = new FileOutputStream(filename + ".jpg");
            InputStream data = image.getPDStream().getPartiallyFilteredStream(DCT_FILTERS);
            byte[] buf = new byte[1024];
            int amountRead;
            while ((amountRead = data.read(buf)) != -1)
            {
                out.write(buf, 0, amountRead);
            }
            IOUtils.closeQuietly(data);
            out.flush();
        }
        finally
        {
            if (out != null)
            {
                out.close();
            }
        }
    }

    private void processResources(PDResources resources, String prefix, 
            boolean addKey, boolean directJPEG) throws IOException
    {
        if (resources == null)
        {
            return;
        }
        Map<String, PDXObject> xobjects = resources.getXObjects();
        if( xobjects != null )
        {
            Iterator<String> xobjectIter = xobjects.keySet().iterator();
            while( xobjectIter.hasNext() )
            {
                String key = xobjectIter.next();
                PDXObject xobject = xobjects.get( key );
                // write the images
                if (xobject instanceof PDXObjectImage)
                {
                    PDXObjectImage image = (PDXObjectImage)xobject;
                    String name = null;
                    if (addKey) 
                    {
                        name = getUniqueFileName( prefix + "_" + key, image.getSuffix() );
                    }
                    else 
                    {
                        name = getUniqueFileName( prefix, image.getSuffix() );
                    }
                    System.out.println( "Writing image:" + name );
                    if (directJPEG && "jpg".equals(image.getSuffix()))
                    {
                        writeJpeg2file((PDJpeg) image, name);
                    }
                    else
                    {
                        image.write2file(name);
                    }
                    image.clear(); // PDFBOX-2101 get rid of cache ASAP
                }
                // maybe there are more images embedded in a form object
                else if (xobject instanceof PDXObjectForm)
                {
                    PDXObjectForm xObjectForm = (PDXObjectForm)xobject;
                    PDResources formResources = xObjectForm.getResources();
                    processResources(formResources, prefix, addKey, directJPEG);
                }
            }
        }
        resources.clear();
    }

    private String getUniqueFileName( String prefix, String suffix )
    {
        String uniqueName = null;
        File f = null;
        while( f == null || f.exists() )
        {
            uniqueName = prefix + "-" + imageCounter;
            f = new File( uniqueName + "." + suffix );
            imageCounter++;
        }
        return uniqueName;
    }

    /**
     * This will print the usage requirements and exit.
     */
    private static void usage()
    {
        System.err.println( "Usage: java org.apache.pdfbox.ExtractImages [OPTIONS] <PDF file>\n" +
            "  -password  <password>        Password to decrypt document\n" +
            "  -prefix  <image-prefix>      Image prefix(default to pdf name)\n" +
            "  -addkey                      add the internal image key to the file name\n" +
            "  -nonSeq                      Enables the new non-sequential parser\n" +
            "  -directJPEG                  Forces the direct extraction of JPEG images regardless of colorspace\n" +
            "  <PDF file>                   The PDF document to use\n"
            );
        System.exit( 1 );
    }

}

【讨论】:

  • 谢谢......它工作得很好:) 现在我必须区分提取的 CMYK 图像和“非”CMYK 图像,因为我的工作还没有完成(我需要调整它们的大小......)。但这是另一个故事:)
  • java ImageIO 不是很好,无法读取 CMYK jpeg 文件...也许十二猴子可以提供帮助。 github.com/haraldk/TwelveMonkeys
  • 谢谢,我也会尝试这样做,因为在调整图像大小时,我得到了漂亮的鲑鱼背景色,这显然不是客户想要的......你认为这与它有关吗?
  • @vindalooman 我没有测试调整你的图片大小,所以我不能确定,我是用 IrfanView 查看的。然而,与 CMYK 图像相关的“鲑鱼背景”对我来说很熟悉 :-( 与 java ImageIO 不同的是,十二猴子的好处是它得到了积极的支持。
  • 使用 irfanview 调整大小确实效果很好......今天下午我会看看十二个猴子。
猜你喜欢
  • 2018-09-15
  • 2010-11-22
  • 2011-08-31
  • 1970-01-01
  • 2017-04-23
  • 2015-01-06
  • 2014-06-15
  • 1970-01-01
  • 2011-01-15
相关资源
最近更新 更多