All Downloads are FREE. Search and download functionalities are using the official Maven repository.

nl.siegmann.epublib.epub.Epub3Writer Maven / Gradle / Ivy

The newest version!
package nl.siegmann.epublib.epub;

import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.xml.parsers.ParserConfigurationException;

import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlSerializer;

/**
 * Generates an epub file. Not thread-safe, single use object.
 *
 * @author paul
 *
 */
public class Epub3Writer extends AbstractEpubWriter {

    private final static Logger log = LoggerFactory.getLogger(Epub3Writer.class);

    public Epub3Writer() {
        super();
    }

    public Epub3Writer(BookProcessor bookProcessor) {
        super(bookProcessor);
    }

    @Override
    public void write(Book book, OutputStream out) throws IOException {
        book = processBook(book);
        ZipOutputStream resultStream = new ZipOutputStream(out);
        writeMimeType(resultStream);
        writeContainer(resultStream);
        initTOCResource(book);
        writeResources(book, resultStream);
        try {
            writePackageDocument(book, resultStream);
        } catch (IllegalArgumentException ex) {
            java.util.logging.Logger.getLogger(Epub3Writer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalStateException ex) {
            java.util.logging.Logger.getLogger(Epub3Writer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            java.util.logging.Logger.getLogger(Epub3Writer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            java.util.logging.Logger.getLogger(Epub3Writer.class.getName()).log(Level.SEVERE, null, ex);
        }
        resultStream.close();
    }

    private void initTOCResource(Book book) {
        Resource tocResource;

        try {
            tocResource = NavDocument.createNavResource(book);
            initTOCResource(book, tocResource);
        } catch (Exception e) {
            log.error("Error writing table of contents: " + e.getClass().getName() + ": " + e.getMessage());
        }
    }

    private void writePackageDocument(Book book, ZipOutputStream resultStream) throws IOException, IllegalArgumentException, IllegalStateException, ParserConfigurationException, SAXException {
        resultStream.putNextEntry(new ZipEntry("OEBPS/content.opf"));
        XmlSerializer xmlSerializer = EpubProcessorSupport.createXmlSerializer(resultStream);
        Epub3PackageDocumentWriter.write(this, xmlSerializer, book);
        xmlSerializer.flush();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy