docx_file_viewer

pub package Flutter License: MIT

A high-fidelity native Flutter DOCX viewer that renders Word documents using pure Flutter widgets. No WebView, no PDF conversionβ€”just native rendering for maximum performance and cross-platform compatibility.

Example

✨ Features

Feature Description
🎯 Native Flutter Rendering Pure Flutter widgets, no WebView or PDF conversion required
πŸ“„ View Modes Continuous scroll or paged (print layout) view modes
πŸ“– Full DOCX Support Paragraphs, tables, lists, images, shapes, headers, footers
πŸ” Text Search Find and highlight text with navigation controls
πŸ”Ž Pinch-to-Zoom Smooth zoom with configurable min/max scales
βœ‚οΈ Text Selection Select and copy text from documents
🎨 Theming Light/dark themes with full customization
πŸ”€ Embedded Fonts OOXML font loading with deobfuscation support
πŸ“ Footnotes & Endnotes Interactive references with tap-to-view dialogs
πŸ–ΌοΈ Floating Images Left/right image positioning with text wrap

πŸ“¦ Installation

Add docx_file_viewer to your pubspec.yaml:

dependencies:
  docx_file_viewer: ^1.0.5

Then run:

flutter pub get

πŸš€ Quick Start

import 'package:docx_file_viewer/docx_file_viewer.dart';

// From file
DocxView.file(myFile)

// From bytes
DocxView.bytes(docxBytes)

// From path
DocxView.path('/path/to/document.docx')

// With configuration
DocxView(
  file: myFile,
  config: DocxViewConfig(
    enableSearch: true,
    enableZoom: true,
    pageMode: DocxPageMode.paged,
    theme: DocxViewTheme.light(),
  ),
)

On the Web

Browsers have no file system, so file doesn't work there:

  • Pass the document as bytes. With file_picker, use withData: true and pass PlatformFile.bytes.
  • path loads a Flutter asset on the web (for example DocxView.path('assets/sample.docx')).
  • file fails with a message explaining to pass bytes instead.

Native platforms are unchanged.

πŸ“– Usage Examples

Basic Viewer

Scaffold(
  body: DocxView.file(
    File('document.docx'),
    config: DocxViewConfig(
      enableZoom: true,
      backgroundColor: Colors.white,
    ),
  ),
)

Paged View (Print Layout)

DocxView(
  bytes: docxBytes,
  config: DocxViewConfig(
    pageMode: DocxPageMode.paged,  // Print-style page layout
    pageWidth: 794,                 // A4 width in pixels
    pageHeight: 1123,               // A4 height in pixels
  ),
)
Scaffold(
  body: DocxViewWithSearch(
    file: myDocxFile,
    config: DocxViewConfig(
      enableSearch: true,
      searchHighlightColor: Colors.yellow,
      currentSearchHighlightColor: Colors.orange,
    ),
  ),
)

Dark Theme

DocxView(
  bytes: docxBytes,
  config: DocxViewConfig(
    theme: DocxViewTheme.dark(),
    backgroundColor: Color(0xFF1E1E1E),
  ),
)

Programmatic Search Control

final searchController = DocxSearchController();

// Widget
DocxView(
  file: myFile,
  searchController: searchController,
)

// Control search programmatically
searchController.search('keyword');
searchController.nextMatch();
searchController.previousMatch();
searchController.clear();

// Listen to search changes
searchController.addListener(() {
  print('Found ${searchController.matchCount} matches');
  print('Current: ${searchController.currentMatchIndex + 1}');
});

With Callbacks

DocxView(
  file: myFile,
  onLoaded: () {
    print('Document loaded successfully');
  },
  onError: (error) {
    print('Failed to load document: $error');
  },
)

βš™οΈ Configuration Options

Property Type Default Description
enableSearch bool true Enable text search with highlighting
enableZoom bool true Enable pinch-to-zoom
enableSelection bool true Enable text selection
minScale double 0.5 Minimum zoom scale
maxScale double 4.0 Maximum zoom scale
pageMode DocxPageMode paged Layout mode (continuous/paged)
pageWidth double? null Fixed page width (paged mode)
pageHeight double? null Fixed page height (paged mode)
padding EdgeInsets 16.0 Document content padding
backgroundColor Color? null Viewer background color
showPageBreaks bool true Show visual page break separators
showDebugInfo bool false Show debug placeholders for unsupported elements
searchHighlightColor Color Yellow Background color for search matches
currentSearchHighlightColor Color Orange Background for current match
customFontFallbacks List<String> ['Roboto', 'Arial', 'Helvetica'] Font fallback chain
theme DocxViewTheme? Light Document rendering theme
showFootnotes bool true Show the footnotes section and allow tapping footnote references
showEndnotes bool true Show the endnotes section and allow tapping endnote references

🎨 Theming

Create a custom theme for consistent document styling:

DocxViewTheme(
  backgroundColor: Colors.white,
  defaultTextStyle: TextStyle(fontSize: 14, color: Colors.black87, height: 1.5),
  headingStyles: {
    1: TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
    2: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
    3: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
    4: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
    5: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
    6: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
  },
  codeBlockBackground: Color(0xFFF5F5F5),
  codeTextStyle: TextStyle(fontFamily: 'monospace', fontSize: 13),
  blockquoteBackground: Color(0xFFF9F9F9),
  blockquoteBorderColor: Color(0xFFCCCCCC),
  tableBorderColor: Color(0xFFDDDDDD),
  tableHeaderBackground: Color(0xFFEEEEEE),
  linkStyle: TextStyle(color: Colors.blue, decoration: TextDecoration.underline),
  bulletColor: Color(0xFF333333),
)

// Or use presets
DocxViewTheme.light()
DocxViewTheme.dark()

πŸ“‹ Supported DOCX Elements

Element Status Notes
Text Formatting
Bold, Italic, Underline βœ… Full support
Strikethrough βœ… Single and double
Superscript/Subscript βœ…
Text Colors βœ… Including theme colors
Highlight Colors βœ… All standard colors
Font Families βœ… With fallback chain
Font Sizes βœ… Half-point precision
Paragraph Formatting
Headings (H1-H6) βœ… Mapped from outline levels
Text Alignment βœ… Left, center, right, justify
Line Spacing βœ… Single, 1.5, double, exact
Indentation βœ… Left, right, first-line, hanging
Paragraph Borders βœ… All sides with colors; dotted/dashed styles render as solid (Flutter has no dashed BorderSide)
Paragraph Shading βœ… Background colors
Drop Caps βœ… With text wrap
Lists
Bullet Lists βœ… Multiple bullet styles
Numbered Lists βœ… Multiple numbering formats
Nested Lists βœ… Multi-level indentation
Custom Markers βœ… Image bullets supported
Tables
Basic Tables βœ… Rows, columns, cells
Cell Merging βœ… Horizontal and vertical
Cell Borders βœ… All sides with colors; dotted/dashed styles render as solid
Cell Shading βœ… Background colors
Conditional Formatting βœ… First/last row/col, banding
Images & Shapes
Inline Images βœ… Embedded and linked
Floating Images βœ… Left/right positioning
Basic Shapes βœ… Rectangles, text boxes
Document Structure
Headers βœ… First page, odd/even
Footers βœ… First page, odd/even
Footnotes βœ… Interactive with dialog
Endnotes βœ… Interactive with dialog
Page Breaks βœ… Visual separators
Section Breaks βœ… Page size changes
Links
Hyperlinks βœ… External URL support
Bookmarks πŸ”„ Partial support
Other
Embedded Fonts βœ… OOXML deobfuscation
Style Inheritance βœ… Full cascade support
Checkboxes βœ… Checked/unchecked states

πŸ”— Integration with docx_creator

This package uses docx_creator for parsing DOCX files:

import 'package:docx_creator/docx_creator.dart';
import 'package:docx_file_viewer/docx_file_viewer.dart';

// Create a document
final doc = docx()
  .h1('My Document')
  .p('This is a paragraph with some text.')
  .table([
    ['Header 1', 'Header 2'],
    ['Cell 1', 'Cell 2'],
  ])
  .build();

// Export to bytes
final bytes = await DocxExporter().exportToBytes(doc);

// View immediately
DocxView.bytes(Uint8List.fromList(bytes))

πŸ—οΈ Rendering architecture (groundwork for an editor)

This package currently composes Flutter's own text widgets (RichText/ SelectableText.rich) for paragraph text. That's fine for a read-only viewer, but it's a real obstacle to building an editor on top: those two widgets are backed by different render objects (RenderParagraph vs. RenderEditable) with incompatible APIs for the same question β€” "what text position is under this point," "where does the caret go" β€” so any hit-testing code has to branch on which one a given paragraph happens to use.

lib/src/rendering/render_docx_paragraph.dart starts replacing that with a custom RenderDocxParagraph built directly on TextPainter, the same primitive RenderParagraph uses internally, exposing one real API β€” getPositionForOffset, getCaretRect, getBoxesForSelection β€” under our control. ParagraphBuilder uses it for the default (non-selectable) case, including paragraphs containing a WidgetSpan (inline image/shape/math, or the first-line-indent spacer): RenderDocxParagraph lays those out as real child render objects via RenderInlineChildrenContainerDefaults β€” the same mixin RenderParagraph itself uses β€” and DocxParagraphRenderWidget extracts each WidgetSpan's child with WidgetSpan.extractFromInlineSpan (also what RichText uses), so this isn't a parallel reimplementation of that machinery, just the same building blocks under our own render object.

lib/src/rendering/render_docx_list_item.dart extends the same core to list items: RenderDocxListItem lays out a marker column (bullet/number/image) and a content column β€” reusing RenderDocxParagraph for each rather than reimplementing text layout β€” instead of Row(SizedBox, Expanded). ListBuilder uses it under the same conditions ParagraphBuilder uses RenderDocxParagraph: no WidgetSpan in the item's content, selection off.

What's NOT on it yet β€” these keep rendering through the existing Flutter-widget composition, and are the natural next steps:

  • A list item's content row containing a WidgetSpan (inline image/shape/ math) still falls back to Row(SizedBox, Expanded) β€” RenderDocxParagraph itself handles WidgetSpan children now (see above), but ListBuilder/RenderDocxListItem hasn't been updated to pass them through yet; containsWidgetSpan still gates that path off for list items specifically.
  • OS-level text selection (DocxViewConfig(enableSelection: true), the default) still uses SelectableText.rich β€” an editor built on this core will want to manage its own caret/selection rather than the OS's, so migrating this path is deferred until that's needed.
  • Tables, images, floating layouts, and drop caps β€” all still Flutter-widget composition (floats/drop-caps also still draw their own images directly rather than going through a paragraph row at all). Nested list levels and lists inside table cells route through the same _buildListItem, so they already get the render-object path when eligible β€” no separate work needed there.

πŸ” Search API

The DocxSearchController provides full control over document search:

final controller = DocxSearchController();

// Properties
controller.query;              // Current search query
controller.matches;            // All found matches
controller.matchCount;         // Number of matches
controller.currentMatchIndex;  // Current match index (0-based)
controller.currentMatch;       // Current SearchMatch object
controller.isSearching;        // Whether search is active

// Methods
controller.search('text');     // Search for text
controller.nextMatch();        // Go to next match
controller.previousMatch();    // Go to previous match
controller.clear();            // Clear search
controller.getBlockText(idx);  // Get text at block index

// Listen to changes
controller.addListener(() => print('Search updated'));

✏️ Editor groundwork (lib/src/editing/)

This is a read-only viewer. lib/src/editing/ is the first-stage groundwork for a future docx_file_editor built on top of it β€” not an editor itself. It covers, for a top-level paragraph with no floating image/shape:

  • Hit-testing (DocxHitTester.resolve) β€” maps a screen position to a DocxTextPosition (which paragraph, which character offset), using DocxNodeBound (see below) to find the source DocxNode for a rendered widget.
  • Pure edit operations (docx_edit_ops.dart) β€” insertText, deleteRange, splitParagraph (Enter), mergeWithPrevious (Backspace at offset 0). Each takes a DocxBuiltDocument and returns a new one; the AST stays immutable.
  • Undo/redo (DocxEditCommandStack) β€” a simple whole-document history stack over those operations.

Not covered yet: editing inside table cells, list items, or floated paragraphs; selection-wide formatting commands (bold/italic toggle); IME composition; collaborative editing.

DocxNodeBound (lib/src/widgets/docx_node_bound.dart) wraps each top-level block DocxWidgetGenerator.generateWidget renders, so DocxNodeBound.of(context) recovers the DocxNode a widget came from.

πŸ“± Platform Support

Platform Support
iOS βœ…
Android βœ…
Web βœ…
macOS βœ…
Windows βœ…
Linux βœ…

🀝 Contributing

Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.

πŸ“„ License

MIT License - see LICENSE for details.

Libraries

docx_file_viewer
docx_viewer - Native Flutter DOCX Viewer