Apache Tika 1.6 能够从 PDF 文档中提取内联图像。然而,我一直在努力让它发挥作用。
我的用例是我需要一些代码来提取内容并从任何文档(不一定是 PDF)中分离图像。然后将其传递到 Apache UIMA 管道中。
我已经能够使用自定义解析器(基于 AutoParser 构建)从其他文档类型中提取图像,将文档转换为 HTML,然后单独保存图像。但当我尝试使用 PDF 时,标签甚至不会出现在 HTML 中,更不用说让我访问这些文件了。
有人可以建议我如何实现上述目标,最好提供一些如何使用 Tika 1.6 从 PDF 中进行内联图像提取的代码示例吗?
最佳答案
尝试下面的代码,ContentHandler 将包含您的 xml 内容。
public ContentHandler convertPdf(byte[] content, String path, String filename)throws IOException, SAXException, TikaException{
Metadata metadata = new Metadata();
ParseContext context = new ParseContext();
ContentHandler handler = new ToXMLContentHandler();
PDFParser parser = new PDFParser();
PDFParserConfig config = new PDFParserConfig();
config.setExtractInlineImages(true);
config.setExtractUniqueInlineImagesOnly(true);
parser.setPDFParserConfig(config);
EmbeddedDocumentExtractor embeddedDocumentExtractor =
new EmbeddedDocumentExtractor() {
@Override
public boolean shouldParseEmbedded(Metadata metadata) {
return true;
}
@Override
public void parseEmbedded(InputStream stream, ContentHandler handler, Metadata metadata, boolean outputHtml)
throws SAXException, IOException {
Path outputFile = new File(path+metadata.get(Metadata.RESOURCE_NAME_KEY)).toPath();
Files.copy(stream, outputFile);
}
};
context.set(PDFParser.class, parser);
context.set(EmbeddedDocumentExtractor.class,embeddedDocumentExtractor );
try (InputStream stream = new ByteArrayInputStream(content)) {
parser.parse(stream, handler, metadata, context);
}
return handler;
}
关于image - 使用 Apache Tika 从 PDF 中提取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25783212/