1、导包

如果用的是maven,在pom.xml中这么写:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>tools</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <!-- 使用java17 -->
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- ePublib库,提供处理EPUB格式的功能 -->
        <dependency>
            <groupId>com.positiondev.epublib</groupId>
            <artifactId>epublib-core</artifactId>
            <version>3.1</version>
        </dependency>
    </dependencies>
</project>

2、使用java生成EPUB格式的示例代码:

import nl.siegmann.epublib.domain.Author;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.epub.EpubWriter;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 使用java创建Epub格式文件的例子。
 */

public class CreateEpub {
    // 标题
    private static final String TITLE = "标题";
    // 作者
    private static final String AUTHOR = "作者";
    // 编码格式
    private static final String CHARSET = "UTF-8";

    public static void main(String[] args) {
        try {
            // 创建一个新的 EPUB 文档
            Book book = new Book();

            // 设置元数据
            book.getMetadata().addTitle(TITLE); // 设置标题
            book.getMetadata().addAuthor(new Author(AUTHOR)); // 设置作者

            // 添加第一章
            String chapter1Title = "第一章";
            String chapter1Content = "第一章内容:This is the content of chapter 1.";
            addChapter(book, chapter1Title, chapter1Content);

            // 添加第二章
            String chapter2Title = "第二章";
            String chapter2Content = "第二章内容:This is the content of chapter 2.";
            addChapter(book, chapter2Title, chapter2Content);

            // 将 EPUB 文档写入到文件中
            EpubWriter epubWriter = new EpubWriter();
            FileOutputStream outputStream = new FileOutputStream("output.epub");
            epubWriter.write(book, outputStream);
            outputStream.close();

            System.out.println("EPUB文件创建成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void addChapter(Book book, String title, String content) {
        try {
            // 创建章节资源
            Resource resource = new Resource(content.getBytes(CHARSET), "chapter" + book.getContents().size() + ".html");
            // 添加章节到书籍
            book.addSection(title, resource);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}