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.IOException;
023import java.io.InputStream;
024import java.io.Serializable;
025import java.util.Map;
026
027import javax.swing.text.BadLocationException;
028import javax.swing.text.Document;
029import javax.swing.text.rtf.RTFEditorKit;
030
031import org.nuxeo.common.utils.FileUtils;
032import org.nuxeo.ecm.core.api.Blob;
033import org.nuxeo.ecm.core.api.Blobs;
034import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
035import org.nuxeo.ecm.core.convert.api.ConversionException;
036import org.nuxeo.ecm.core.convert.cache.SimpleCachableBlobHolder;
037import org.nuxeo.ecm.core.convert.extension.Converter;
038import org.nuxeo.ecm.core.convert.extension.ConverterDescriptor;
039
040public class RTF2TextConverter implements Converter {
041
042    @Override
043    public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException {
044
045        File f = null;
046        try {
047            RTFEditorKit rtfParser = new RTFEditorKit();
048            Document document = rtfParser.createDefaultDocument();
049            rtfParser.read(blobHolder.getBlob().getStream(), document, 0);
050            String text = document.getText(0, document.getLength());
051            f = File.createTempFile("swing-rtf2text", ".txt");
052            FileUtils.writeFile(f, text);
053            Blob blob;
054            try (InputStream in = new FileInputStream(f)) {
055                blob = Blobs.createBlob(in, "text/plain");
056            }
057            return new SimpleCachableBlobHolder(blob);
058        } catch (IOException | BadLocationException e) {
059            throw new ConversionException("Error during Word2Text conversion", e);
060        } finally {
061            if (f != null) {
062                f.delete();
063            }
064        }
065    }
066
067    @Override
068    public void init(ConverterDescriptor descriptor) {
069    }
070
071}