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.extractor.POITextExtractor; 032import org.apache.poi.ooxml.extractor.ExtractorFactory; 033import org.apache.poi.openxml4j.exceptions.OpenXML4JException; 034import org.apache.xmlbeans.XmlException; 035import org.nuxeo.ecm.core.api.Blob; 036import org.nuxeo.ecm.core.api.Blobs; 037import org.nuxeo.ecm.core.api.blobholder.BlobHolder; 038import org.nuxeo.ecm.core.convert.api.ConversionException; 039import org.nuxeo.ecm.core.convert.cache.SimpleCachableBlobHolder; 040import org.nuxeo.ecm.core.convert.extension.Converter; 041import org.nuxeo.ecm.core.convert.extension.ConverterDescriptor; 042import org.nuxeo.runtime.api.Framework; 043 044public class MSOffice2TextConverter implements Converter { 045 046 @Override 047 public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException { 048 049 File f = null; 050 051 try (POITextExtractor extractor = ExtractorFactory.createExtractor(blobHolder.getBlob().getStream())) { 052 // TODO: find a way to distinguish headings from paragraphs using 053 // WordExtractor#getParagraphText()? 054 055 // Get extracted text with Unix end of line characters 056 String extractedText = extractor.getText().replace("\r\n", "\n"); 057 058 byte[] bytes = extractedText.getBytes("UTF-8"); 059 f = Framework.createTempFile("po-msoffice2text", ".txt"); 060 try (OutputStream fas = new FileOutputStream(f)) { 061 fas.write(bytes); 062 } 063 064 try (InputStream is = new FileInputStream(f)) { 065 Blob blob = Blobs.createBlob(is, "text/plain", "UTF-8"); 066 return new SimpleCachableBlobHolder(blob); 067 } 068 } catch (IOException | OpenXML4JException | XmlException e) { 069 throw new ConversionException("Error during MSOffice2Text conversion", blobHolder, e); 070 } finally { 071 if (f != null) { 072 f.delete(); 073 } 074 } 075 } 076 077 @Override 078 public void init(ConverterDescriptor descriptor) { 079 } 080 081}