试图解析二进制数据......在我的情况下,它主要是pdf

AKI*_*WEB 2 java parsing apache-tika

这段代码出了什么问题...我正在尝试解析pdf文件并从中提取文本...但是对于某些pdf我能够提取文本...而对于一些它会抛出错误

Invalid dictionary, found: '' but expected: '/'
org.apache.tika.exception.TikaException: Unexpected RuntimeException from org.apache.tika.parser.pdf.PDFParser@67fb878
Run Code Online (Sandbox Code Playgroud)

而且我也没有在某些pdf的md变量中获得任何元数据值......但是对于Some,我得到了......

这是我的代码.. !! ByteArray的一些问题??

    private BinaryParser binaryParser;
    binaryParser.parse(page.getBinaryData());


    public void parse(byte[] data) {
            InputStream is = null;
            try {
                is = new ByteArrayInputStream(data);
                text = null;
                Metadata md = new Metadata();
                metaData = new HashMap<String, String>();
                text = tika.parseToString(is, md).trim();
                processMetaData(md);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(is);
            }
        }

private void processMetaData(Metadata md){
        if ((getMetaData() == null) || (!getMetaData().isEmpty())) {
            setMetaData(new HashMap<String, String>());
        }
        for (String name : md.names()){
            getMetaData().put(name.toLowerCase(), md.get(name));
        }
    }
Run Code Online (Sandbox Code Playgroud)

sch*_*mmd 5

蒂卡并不完美.它会在许多PDF文件上出现问题(除非去年有很多变化).确保您使用的是Tika的更新版本.当我使用Tika时,它的版本是0.8(9个月前).此版本存在一个错误,导致PDF解析特别成问题.我通过使用Apache Tika包装的PDFBox来回避这个问题.如果您决定尝试此路线,我的一些代码会在本文末尾包装PDFBox.

如果不出意外,直接使用PDFBox可以让您更好地控制参数.一个这样的参数是处理"串珠"文本.例如,带有列的报纸是串珠的,而字母则不是.PDFBox可以尝试保持写作流程,但它并不总是做得很好.如果您不从非串珠PDF中提取文本,则可能需要禁用此功能.

您可能还想尝试pdftotext程序.再次确保您拥有最新版本.使用所有PDF到文本转换器,性能随版本快速变化!

import org.apache.pdfbox.util.PDFTextStripper;

PDFTextStripper stripper = new PDFTextStripper;

public static String pdfbox(InputStream is, Writer writer) throws IOException, ConversionException {
        Boolean force = true;

        PDDocument document = null;
        try {
            document = PDDocument.load(is, force); // force extraction

            stripper.setForceParsing(force); // continue when errors are encountered.
            stripper.setSortByPosition(false); // text may not be in visual order.
            stripper.setShouldSeparateByBeads(true); // beads are columns, attempt to handle them.

            stripper.writeText(document, writer);
        }
        finally {
            try {
                if (document != null) {
                    document.close();
                }
            }
            catch (Exception e) {
                throw new ConversionException(e);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)