Building a Multi-Format Document Reader on Mobile: A Technical Breakdown

    This article explains how to build a multi-format document reading capability on mobile devices, where the core challenge is reconciling heterogeneous input formats with a consistent reading experience. It walks through a layered parsing pipeline that turns containers into a unified intermediate representation, a dual-mode layout engine that switches between fixed-layout rendering and reflowable text, techniques for inferring reading order during conversion, engineering essentials for text-to-speech, and a decoupled annotation model for stable persistence and sync. It also covers performance, security, and how to leverage general-purpose cloud capabilities so engineering effort stays focused on parsing and layout.

    1. The Problem: Technical Challenges of Reading on Mobile

    Building a general-purpose document reader on mobile devices is fundamentally about resolving the tension between heterogeneous input formats and a consistent reading output. Files come from many sources—academic papers, e-books, scanned materials, or office documents—and differ in container format, compression, and font embedding strategy. The display side, however, is a single area with limited size, variable brightness, and touch interaction.

    The core goals of the implementation can be summarized in three points:

    • Abstract different formats into a renderable intermediate representation.
    • Convert fixed-layout content into streamable content that adapts to the screen.
    • Extend visual information into multi-channel information that supports audio and annotation.

    2. Parsing Layer: From Container to a Unified Intermediate Representation

    Differences between document formats mainly appear across three dimensions: container structure, text encoding, and layout description. A layered parsing strategy is typically used in engineering.

    Layer 1: Container identification and unpacking. Most e-books and office documents are essentially a compressed archive plus descriptor files, containing a content manifest, a resource directory, and style definitions. The parser must first validate the file header and integrity, then read the manifest to build a “resource table” that registers text streams, images, and style sheets separately.

    Layer 2: Text extraction and structure restoration. Plain text alone is not enough. Semantic structures such as heading levels, paragraph boundaries, lists, tables, and footnotes must be preserved; otherwise, subsequent reflow and sentence segmentation for read-aloud will be distorted. A common approach is to build a document tree:

    1. Document
    2. ├── Section(chapter)
    3. │ ├── Heading(level=1)
    4. │ ├── Paragraph
    5. │ │ ├── TextRun(text, styleRef)
    6. │ │ └── InlineImage(resourceId)
    7. │ └── Table(rows, cols)
    8. └── Metadata(title, author, language)

    Layer 3: Style parsing and font handling. Fonts referenced in the style sheet may not be embedded. In that case, fall back to system fonts and dispatch fonts by the language range each character belongs to, avoiding missing glyphs (tofu boxes) or abrupt weight changes. For scanned content, optical character recognition (OCR) can be introduced as an optional supplementary path, with coordinate information retained for layout restoration.

    3. Layout Engine: A Dual-Mode Design for Fixed Layout and Reflow

    Fixed-layout documents (such as academic papers and reports with complex figures) require faithful rendering and usually cache drawing instructions per page, while content like novels is better suited to reflow. A mature approach is a dual-mode engine with automatic selection: based on features such as text density per page, number of floating elements, and column count, it produces a reflow feasibility score, and falls back to paginated mode when the score is below a threshold.

    The key to reflow lies in line-breaking and pagination algorithms. Line breaking must handle mixed Chinese and Western text, punctuation rules (avoiding line-start and line-end violations), hyphenation, and non-breaking spaces. Pagination must balance page fill under the constraint of proper start and end, avoiding a lone line on the last page. Line spacing, font size, and page margins should be externalized as theme parameters so that only the layout tree is rebuilt at runtime without re-parsing the document—this is what makes reading-parameter adjustments respond in real time.

    4. Document Conversion: From Fixed Layout to a Reflowable Structure

    The difficulty of converting fixed-layout content into a streamable format lies not in text extraction but in reading order inference. With multi-column layouts, headers and footers, and captions interleaved with body text, simple coordinate sorting scrambles the semantics. A viable path is to first cluster text blocks, then build a reading-order graph based on geometric relationships between blocks and font-size hierarchy, and finally output a streamable document with chapter structure. The conversion result should retain references to original resources and bookmark anchors, and record a conversion confidence score, prompting users to review low-confidence regions.

    5. Read-Aloud: Engineering Essentials for Text to Speech

    Read-aloud is not just calling an API; it requires both preprocessing and scheduling. Preprocessing handles text normalization: expanding numbers, dates, units, and abbreviations; disambiguating polyphonic characters; and joining sentences across paragraphs. The scheduling part splits long text into sentence-level tasks and uses a producer–consumer model to synthesize sequentially while prefetching subsequent segments, keeping playback continuous.

    1. def split_for_tts(text, max_chars=120):
    2. sentences, buf = [], ""
    3. for ch in text:
    4. buf += ch
    5. if ch in "。!?;.!?;" and len(buf) >= 20:
    6. sentences.append(buf.strip()); buf = ""
    7. elif len(buf) >= max_chars:
    8. sentences.append(buf.strip()); buf = ""
    9. if buf.strip():
    10. sentences.append(buf.strip())
    11. return sentences

    Engineering also needs to handle background playback, audio focus contention, lock-screen controls, and speech rate and pitch adjustment. If cloud-based synthesis is used, local caching and weak-network fallback should be implemented to avoid traffic and latency affecting the experience.

    6. Annotation and Data Persistence

    The value of highlights, notes, and bookmarks depends on whether they can be reliably restored across devices and versions. It is recommended to model annotations as a structure decoupled from content anchors: record the document’s unique identifier, chapter path, paragraph index, and character offset, and save a summary of the selected original text as a fallback. The data layer can use a local database plus incremental sync, merging on conflict by update timestamp and version number; export should support a common markup format to ease user migration. Storage and sync can be carried by general-purpose cloud capabilities such as object storage, message queues, and logging services to enable backup and cross-device consistency.

    7. Performance, Security, and Local Implementation Choices

    Performance optimization focuses on memory and rendering: downsample images to display size, use a virtual list for long documents to keep layout only for the visible area, and move parsing and synthesis to background threads to avoid blocking the main thread. For security, validate archive paths against path traversal, limit oversized files and decompression ratios, and isolate external links and script-like resources.

    For a quick start, you can consult the general technical documentation and developer support on platforms such as Baidu AI Cloud for how to integrate foundational capabilities like containerized deployment, object storage, and monitoring and alerting, keeping your effort focused on the modules that create real differentiation—parsing and the layout engine. Overall, the competitive barrier of multi-format reading lies not in the number of formats, but in the accuracy of structure restoration, reflow quality, and the coordination of multi-channel information organization.