001/* 002 * (C) Copyright 2006-2016 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Nuxeo - initial API and implementation 018 * 019 */ 020package org.nuxeo.ecm.core.convert.plugins.text.extractors; 021 022import java.io.File; 023import java.io.FileInputStream; 024import java.io.FileOutputStream; 025import java.io.IOException; 026import java.io.InputStream; 027import java.io.OutputStream; 028import java.io.Serializable; 029import java.util.Map; 030 031import org.apache.poi.POITextExtractor; 032import org.apache.poi.extractor.ExtractorFactory; 033import org.apache.poi.openxml4j.exceptions.OpenXML4JException; 034import org.apache.xmlbeans.XmlException; 035 036import org.nuxeo.ecm.core.api.Blob; 037import org.nuxeo.ecm.core.api.Blobs; 038import org.nuxeo.ecm.core.api.blobholder.BlobHolder; 039import org.nuxeo.ecm.core.convert.api.ConversionException; 040import org.nuxeo.ecm.core.convert.cache.SimpleCachableBlobHolder; 041import org.nuxeo.ecm.core.convert.extension.Converter; 042import org.nuxeo.ecm.core.convert.extension.ConverterDescriptor; 043import org.nuxeo.runtime.api.Framework; 044 045public class MSOffice2TextConverter implements Converter { 046 047 @Override 048 public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException { 049 050 File f = null; 051 052 try (POITextExtractor extractor = ExtractorFactory.createExtractor(blobHolder.getBlob().getStream())) { 053 // TODO: find a way to distinguish headings from paragraphs using 054 // WordExtractor#getParagraphText()? 055 056 // Get extracted text with Unix end of line characters 057 String extractedText = extractor.getText().replace("\r\n", "\n"); 058 059 byte[] bytes = extractedText.getBytes("UTF-8"); 060 f = Framework.createTempFile("po-msoffice2text", ".txt"); 061 try (OutputStream fas = new FileOutputStream(f)) { 062 fas.write(bytes); 063 } 064 065 try (InputStream is = new FileInputStream(f)) { 066 Blob blob = Blobs.createBlob(is, "text/plain", "UTF-8"); 067 return new SimpleCachableBlobHolder(blob); 068 } 069 } catch (IOException | OpenXML4JException | XmlException e) { 070 throw new ConversionException("Error during MSOffice2Text conversion", e); 071 } finally { 072 if (f != null) { 073 f.delete(); 074 } 075 } 076 } 077 078 @Override 079 public void init(ConverterDescriptor descriptor) { 080 } 081 082}