DEV Community

Cover image for epub_rtl: a pure-Flutter EPUB parser and reader for right-to-left books
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

epub_rtl: a pure-Flutter EPUB parser and reader for right-to-left books

An EPUB file is a zip archive of XHTML chapters with a manifest, a reading order and a table of contents. For an Arabic book, a reader has more to get right than opening the zip. The book declares that its pages progress from right to left, and the reader has to swipe the other way. A paragraph mixes Arabic with an English word or a number, and the bidi algorithm needs the right isolates to keep the sentence in order. The table of contents should open from the right side. The body text needs an Arabic font.

On the Flutter side, the README notes the state of the usual packages: epubx has had no release since June 2023, and epub_view depends on it and on the archived scrollable_positioned_list.

epub_rtl is a pure-Flutter EPUB 2/3 parser and reader that handles right-to-left books. It is built for Arabic and other RTL texts, and it uses no WebView.

What it does

The package has three layers. You can use the parser alone, the parser with the content model, or all three.

The parser

It is pure Dart and depends only on archive and xml.

  • It finds the package document through META-INF/container.xml, then reads the OPF: metadata (titles, creators with role and file-as, languages, identifiers, publisher, date, description, dcterms:modified and the cover image), the manifest, and the spine with linear and page-progression-direction.
  • EpubBook.isRtl uses the spine direction, and falls back to the book language when the spine declares none.
  • For navigation, it reads the EPUB 3 nav document (toc, landmarks, page-list), and falls back to the EPUB 2 NCX with the guide element as landmarks.
  • Content is read by href, with relative paths, percent-encoding and fragments resolved.
  • Reading is lazy. Only the zip directory is read up front. Each chapter or resource is inflated when it is requested, and it is not cached. EpubBook.openFile reads entries from disk on demand.

Malformed books throw a typed EpubException with an EpubErrorKind. With lenient: true, the parser recovers from common real-world errors and records them in warnings: a missing or misplaced mimetype, a missing NCX or nav document, missing or unknown media types, dangling spine references and wrong letter case in paths.

A book with DRM listed in META-INF/encryption.xml is refused with EpubErrorKind.encrypted. A book whose only encrypted resources are obfuscated fonts opens in lenient mode, and those fonts are unreadable.

The content model

EpubChapter turns a chapter's XHTML into a flat list of blocks. Each id maps to a block index, which is what locations point to.

  • Blocks: headings, paragraphs, pre, images (including SVG-wrapped covers), lists, blockquotes, basic tables and rules.
  • Inline content: emphasis, bold, underline, strike, sup/sub, code, links and basic ruby.
  • dir and lang are inherited, and dir="auto" uses the first strong character.
  • Inline dir is wrapped in bidi isolates (LRI/RLI … PDI), bdi in FSI … PDI, and bdo in LRO/RLO … PDF.
  • A CSS subset is read from linked stylesheets, style elements and style attributes: text-align, font-style, font-weight, margins, text-indent, direction and display: none, with tag, class, id and descendant selectors.

The reader

EpubReaderView is a Flutter widget with two modes. scroll is one continuous vertical scroll through the whole book. paginated shows one chapter per page, swiped in the book's reading direction, so RTL books advance with a right swipe.

The reading position is an EpubLocation: spine index, element index and an offset fraction. You can serialise it with toJson or encode, restore it with initialLocation, and follow it through onLocationChanged and the controller.

EpubReaderController has jumpTo, jumpToHref (for TOC entries and internal links), nextChapter and previousChapter. EpubTocDrawer is a table-of-contents drawer laid out in the book's direction.

EpubReaderSettings covers font size and line height, light, sepia and dark themes, justification, and arabicFontFamily, which is used for RTL-language runs and placed first in the fallback list.

Internal links jump inside the book, and external links go to your onExternalLink callback. Jumps inside a chapter use GlobalKeys and Scrollable.ensureVisible, so the package does not depend on scrollable_positioned_list.

How to use it

Add it from GitHub:

dependencies:
  epub_rtl:
    git: https://github.com/AbdeldjalilChougui/epub_rtl
Enter fullscreen mode Exit fullscreen mode

It needs Flutter 3.24 or later. A complete reader screen, from the README:

import 'package:epub_rtl/epub_rtl.dart';
import 'package:flutter/material.dart';

class ReaderScreen extends StatefulWidget {
  const ReaderScreen({super.key, required this.bytes, this.saved});

  final List<int> bytes;
  final String? saved; // a previously stored EpubLocation.encode()

  @override
  State<ReaderScreen> createState() => _ReaderScreenState();
}

class _ReaderScreenState extends State<ReaderScreen> {
  late final EpubBook book = EpubBook.fromBytes(widget.bytes, lenient: true);
  final controller = EpubReaderController();

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(title: Text(book.metadata.title)),
        drawer: EpubTocDrawer(book: book, controller: controller),
        body: EpubReaderView(
          book: book,
          controller: controller,
          mode: EpubReaderMode.paginated,
          settings: const EpubReaderSettings(
            fontSize: 20,
            theme: EpubReaderTheme.sepia,
            arabicFontFamily: 'Amiri', // bundle the font in your app
            justify: true,
          ),
          initialLocation:
              widget.saved == null ? null : EpubLocation.tryDecode(widget.saved!),
          onLocationChanged: (location) {
            // Persist location.encode() or location.toJson().
          },
          onExternalLink: (url) {
            // Open with url_launcher, for example.
          },
        ),
      );
}
Enter fullscreen mode Exit fullscreen mode

If you only need the parser:

final book = EpubBook.fromBytes(bytes);
print(book.metadata.title);
print(book.spine.pageProgressionDirection); // PageProgressionDirection.rtl
for (final entry in book.navigation.toc) {
  print('${entry.title} -> ${entry.href}');
}
final chapter = EpubChapter.fromBook(book, 0);
print(chapter.blocks.length);
Enter fullscreen mode Exit fullscreen mode

Coming from epubx or epub_view

The README has a mapping table. The main lines: EpubReader.readBook(bytes), which is async and loads everything, becomes EpubBook.fromBytes(bytes), which is sync and lazy. book.Title becomes book.metadata.title. chapter.HtmlContent becomes book.chapterHtml(i) or EpubChapter.fromBook(book, i). EpubView with its EpubController becomes EpubReaderView with an EpubReaderController, and EpubViewTableOfContents becomes EpubTocDrawer.

One thing does not carry over: locations are not EPUB CFIs. Saved epub_view CFIs cannot be converted.

Things to know

  • DRM-encrypted books are refused. Obfuscated embedded fonts are not de-obfuscated, and embedded fonts are not loaded. Use fontFamily and arabicFontFamily with fonts bundled in your app.
  • Paginated mode is one chapter per page. The page scrolls vertically. The text is not split into screen-sized pages.
  • The CSS support is a small subset. No floats, positioning, colours, font sizes from CSS, pseudo-classes, >/+/~ selectors or @media rules.
  • Tables are basic: no colspan or rowspan. Ruby is shown as annotation-over-base, without full ruby layout.
  • Not rendered: SVG images, audio, video, MathML and scripts. Fixed-layout EPUBs are rendered as reflowable text.
  • Long chapters cost more. Each chapter is built as one widget subtree so that element keys exist for jumps. Very long single chapters cost more to lay out.
  • Web. EpubBook.openFile needs dart:io and is not available on the web. Use fromBytes there.
  • Test data. No third-party book content is bundled. The test fixtures and the example's sample book are generated in code, with text written for the package.

Why I built it

The README states the problem in two sentences: the existing parser has had no release since June 2023, and the existing viewer depends on it and on an archived scrolling package.

For an Arabic book, direction is not a setting you add at the end. It decides which way a swipe goes, which side the drawer opens from, how a mixed Arabic and Latin sentence is isolated, and which font the text falls back to. So I wrote the reader with direction read from the book itself, from the spine first and the language second, and applied at every level: the page view, the drawer, the paragraph and the inline run. Doing it with Flutter widgets instead of a WebView keeps the whole thing in one rendering system, with a reading position that can be saved as a small string and restored.

Get the code

The source, the migration table, an example app with a generated sample book and the tests are on GitHub: https://github.com/AbdeldjalilChougui/epub_rtl. It is MIT licensed.


Originally published at abdeldjalilchougui.biz.

Top comments (0)