001/* 002 * (C) Copyright 2002-2007 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Nuxeo - initial API and implementation 016 * 017 */ 018package org.nuxeo.ecm.core.convert.plugins.text.extractors; 019 020import java.io.File; 021import java.io.FileInputStream; 022import java.io.FileOutputStream; 023import java.io.IOException; 024import java.io.InputStream; 025import java.io.OutputStream; 026import java.io.Serializable; 027import java.util.Map; 028 029import org.apache.poi.POITextExtractor; 030import org.apache.poi.extractor.ExtractorFactory; 031import org.apache.poi.openxml4j.exceptions.OpenXML4JException; 032import org.apache.xmlbeans.XmlException; 033import org.nuxeo.ecm.core.api.Blob; 034import org.nuxeo.ecm.core.api.Blobs; 035import org.nuxeo.ecm.core.api.blobholder.BlobHolder; 036import org.nuxeo.ecm.core.convert.api.ConversionException; 037import org.nuxeo.ecm.core.convert.cache.SimpleCachableBlobHolder; 038import org.nuxeo.ecm.core.convert.extension.Converter; 039import org.nuxeo.ecm.core.convert.extension.ConverterDescriptor; 040 041public class MSOffice2TextConverter implements Converter { 042 043 @Override 044 public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException { 045 046 File f = null; 047 OutputStream fas = null; 048 049 try { 050 POITextExtractor extractor = ExtractorFactory.createExtractor(blobHolder.getBlob().getStream()); 051 // TODO: find a way to distinguish headings from paragraphs using 052 // WordExtractor#getParagraphText()? 053 054 // Get extracted text with Unix end of line characters 055 String extractedText = extractor.getText().replace("\r\n", "\n"); 056 057 byte[] bytes = extractedText.getBytes("UTF-8"); 058 f = File.createTempFile("po-msoffice2text", ".txt"); 059 fas = new FileOutputStream(f); 060 fas.write(bytes); 061 062 try (InputStream is = new FileInputStream(f)) { 063 Blob blob = Blobs.createBlob(is, "text/plain", "UTF-8"); 064 return new SimpleCachableBlobHolder(blob); 065 } 066 } catch (IOException | OpenXML4JException | XmlException e) { 067 throw new ConversionException("Error during MSOffice2Text conversion", e); 068 } finally { 069 if (fas != null) { 070 try { 071 fas.close(); 072 } catch (IOException e) { 073 } 074 } 075 if (f != null) { 076 f.delete(); 077 } 078 } 079 } 080 081 @Override 082 public void init(ConverterDescriptor descriptor) { 083 } 084 085}