universal_document_viewer 0.3.1
universal_document_viewer: ^0.3.1 copied to clipboard
Open and read PDF, Word (.docx), Excel (.xlsx), CSV, PowerPoint (.pptx) Markdown and text documents in Flutter, with its own document engines.
Changelog #
0.3.1 #
Additive: nothing changes for existing code. No new dependency.
PdfView.pageOverlayBuilderdraws something over each page: the builder gets the page index and the page's size in PDF points and returns a widget that fills the page's own box, so it stays on the page as the page scrolls and zooms, and it takes no touches. For an app's own marks on a page (a scan effect, stamps, highlights it keeps); the page's text, search hits and selection are unchanged.PdfPageOverlayBuilderis its type.
0.3.0 #
Additive: nothing from 0.2 changes or is removed. No new dependency.
- Select and copy text.
- Word, plain text, Markdown and slides use Flutter's selection (
SelectionArea), so the platform's own toolbar, right-click menu and keys apply. - PDF gets a text layer: drag with the mouse (double click a word, triple click a line, Ctrl or Cmd+C / +A, Esc, right-click menu, drag past the edge to scroll), or long-press with drag handles and a floating toolbar on touch. Dragging over blank paper still pans.
PdfView.selectionMenuItemsadds your own items (highlight, bookmark) to the menu. The selection lives in the controller, so it spans pages and survives scrolling.
- Word, plain text, Markdown and slides use Flutter's selection (
DocumentControllergains optional selection members, inert unless a view supplies them, so existing subclasses still compile:hasSelection,selectedText(),clearSelection(),selectAll(),copySelection(),allText(),copyAllText().SpreadsheetControllerkeeps its own behaviour (selectedText()is now an override with the same result).SlideCardhas an optionalselectionController.- OCR for pages with no text layer (scans). The package has no recognizer and adds no dependency: implement
TextRecognizer(import 'package:universal_document_viewer/ocr.dart', also exported bypdf.dart) with your platform's text recognition and pass it asPdfController(textRecognizer: ...). ThencanRecognize,pageNeedsOcr(page),recognizePage(page),cancelOcr(page),ocrStatusOf(page)andocrErrorOf(page)drive it, and the recognised text becomes selectable and copyable like any page's text (a page that has text and pictures keeps its own text and gains only what was in the pictures).PdfiumDocument.renderPagePngrenders a page for a recognizer. OCR text is not searchable. PdfPageText.sidewayssays whether a page is turned 90 or 270 degrees.- One new string,
DocumentViewerStrings.copiedText.
0.2.2 #
- Markdown: every fenced code block in the preview has a copy button (tooltip from
DocumentViewerStrings.copy); it shows a check for two seconds after copying.
0.2.1 #
- Markdown:
MarkdownControllerandMarkdownView(inmarkdown.dart) show.mdfiles as a rendered preview, highlighted source with line numbers, or both side by side.MarkdownStatscounts words, headings, links, images and reading time. New dependency:markdown.DocumentViewerStrings.markdownPreviewTruncatedis the one new string.TextLinesController(decoding, zoom, search over lines) is now the shared base ofPlainTextControllerandMarkdownController;PlainTextController's API is unchanged.
0.2.0 #
0.2.0 gives every format the same API and makes the package cleaner to use and to contribute to. It breaks 0.1 code; the tables below say what to change.
One controller contract: DocumentController #
Every format's controller extends DocumentController, so one toolbar, search bar and position display serve them all:
- loading:
loadFile(path),loadBytes(bytes),status(DocumentStatus.idle,loading,ready,failed),error(DocumentLoadError); - where the reader is:
location(aValueListenable<DocumentLocation>: current, count and unit, which is page, slide, row, line or percent),goTo(number), andposition/onPositionChangedto save and restore it; - zoom:
zoom,minZoom,maxZoom,canZoomIn,canZoomOut,zoomIn(),zoomOut(),setZoom(zoom); - search:
search(query),nextMatch(),previousMatch(),clearSearch(), andsearchState(aValueListenable<DocumentSearchState>: query, match count, current match). Search now counts occurrences in every format (spreadsheets count matching cells, as Excel's Find does), and the current match is highlighted apart from the others.
Breaking: names #
Every format now has a <Format>Controller and a <Format>View, and each library is named for its format. universal_document_viewer.dart exports everything, so one import is enough; each format library also exports the shared contract.
| 0.1 | 0.2 |
|---|---|
import '…/docx.dart' or '…/word.dart' |
import '…/word.dart' |
import '…/sheets.dart' |
import '…/spreadsheet.dart' |
import '…/text.dart' |
import '…/plain_text.dart' |
PdfDocumentController, PdfDocumentView |
PdfController, PdfView |
PdfReaderViewMode |
PdfViewMode |
WordDocumentController, WordDocumentView |
WordController, WordView |
SheetGrid |
SpreadsheetView |
SlideDeckController, SlideDeckView |
SlidesController, SlidesView |
TextDocumentController, TextDocumentView |
PlainTextController, PlainTextView |
BorderLine, CellBorders (Word model) |
WordBorderLine, WordCellBorders (the spreadsheet model keeps BorderLine and CellBorders) |
Breaking: behaviour and members #
| 0.1 | 0.2 |
|---|---|
controller.load(bytes), loadXlsx(bytes), loadCsv(bytes) |
controller.loadBytes(bytes), or controller.loadFile(path), which checks the size before reading |
PdfView(path: …, passwordProvider: …) |
PdfController(passwordProvider: …)..loadFile(path), then PdfView(controller: …) |
PdfController.open(path), isReady |
loadFile(path), status == DocumentStatus.ready |
PdfController.error (the engine's exception) |
error is a DocumentLoadError; the exception is errorDetail |
PdfView.errorBuilder: (context, Object error) |
(context, DocumentLoadError error) |
rejectAsTooLarge(), rejectAsCorrupted() |
markFailed(DocumentLoadError.tooLarge) (or .corrupted) |
SpreadsheetController.goTo('B3') |
goToCell('B3'); goTo(row) scrolls to a row |
Word goToPage(n), currentPage, progress, pageCount.value |
goTo(n), location.value, pageCount (an int?) |
SlidesController.matches (slide indexes), PlainTextController.matches (line indexes) |
lists of SlideMatch and TextMatch: one per occurrence |
static minZoom, maxZoom, zoomStep |
instance getters on each controller |
PlainTextView(wrap: …, fontSize: 14) |
PlainTextController.wrap; PlainTextView(fontSize: 16) is the size at zoom 1 |
pdfSearchStatusLabel(…) |
DocumentViewerStrings.of(context).searchStatus(controller.searchState.value) |
SlideNavigationBar, showGoToDialog, the sheet's zoom buttons (showZoomControls) |
removed from the format views: build them from the controller, or use DocumentViewer's toolbar. The example app has a go-to-cell dialog to copy. |
WordSearchController, PdfSearchController (controller.searchController) |
internal: use searchState |
PositionKeys.zoom is gone: no reader wrote or read it.
These are no longer exported (they were implementation details): WordScope, WordBlockView, WordDocumentLayout, WordPage, WordPagination, SheetGeometry, TextLineMetrics, showCellDetail, SelectionSummary, and pdf_layout.dart apart from PdfViewMode.
Added #
DocumentViewerhas a toolbar: where the reader is, previous and next for pages and slides, zoom, and search with match stepping (showToolbar: falsehides it).DocumentViewer.bytes(bytes, format: …)shows a document held in memory.DocumentViewerStringsholds every text the widgets show (English by default). Subclass it and provide it withDocumentViewerStringsScopeto translate or reword.DocumentViewerTheme, aThemeExtension, sets the search highlight colours.- PDF:
loadBytesopens a PDF held in memory. - Spreadsheets:
SpreadsheetController(format: …)says whetherloadBytesgets a workbook or CSV; left null, it tells from the bytes. - Word: zoom (the text reflows in the continuous layout, and pages scale and pan sideways in print layout), page tracking in print layout, and
WordPageThumbnailfor page previews. - PowerPoint: zoom.
- For contributors: CONTRIBUTING, a code of conduct, a security policy, issue and pull-request templates, CI (format, analyze, test, pub.dev score), an architecture guide (
doc/architecture.md), and contract tests that every format's controller passes. The code followsflutter_lintsand one formatting width.
Spreadsheets: selection, search, reading gaps, accessibility #
Selection (new, and exported again as GridSelection):
- Cells, ranges, whole rows and columns, and select all, with
SpreadsheetController.selection,select,clearSelection,selectAll,moveSelectionandrevealCell. Mouse: click, drag, Shift+click, header and corner clicks. Keyboard: arrows, Shift+arrows, Tab, Enter, Home/End, PgUp/PgDn, Ctrl/Cmd+A, Esc. Touch: tap selects, long press starts a range with two drag handles and edge auto-scroll, pinch zooms, and a swipe still scrolls. - Behaviour change: a first tap selects the cell; a second tap on the active cell opens the cell sheet (link, formula, note). A tap used to open it at once.
- Copy (Ctrl/Cmd+C and the bar) as tab-separated text with spreadsheet quoting; copy the address. Clipboard writes are awaited and a refusal is reported instead of "copied".
- The status bar shows size, Count, Numbers, Sum, Avg, Min and Max. Dates are never added, and results keep a shared number format (10% + 20% is 30%). Ranges over 100,000 cells are not totalled.
Reading:
.xlsm(macros are never read or run) and.tsv(split on tabs) are supported formats, with their MIME types.- A password-protected workbook fails with
DocumentLoadError.passwordRequiredinstead of "damaged" (ZipSafetyGuard.isEncryptedOfficeFile). It is detected, not decrypted. SpreadsheetController.hiddenSheetNamesnames the sheets the author hid.Worksheet.unshown(UnshownContent) reports what a sheet holds that is not drawn: pictures, charts, tables, pivot tables, data validation, formula-based conditional formatting, sparklines, chart sheets.- A hyperlink over a range now links every cell of it (up to 100,000 cells per sheet).
- Rows without a stored height grow to show their wrapped text (up to Excel's 409 pt; the first 2,000 wrapped cells of a sheet are measured).
Search:
SpreadsheetController.searchOptions(SheetSearchOptions): match case, entire cell, formulas, all sheets.CellMatch.sheetsays which sheet a match is on; next and previous move across sheets.- Big workbooks (over 200,000 cells in scope) are searched in slices after a 200 ms pause, and a newer query cancels the old one (
isSearching,DocumentSearchState.isSearching).
Accessibility:
- Cells have screen-reader labels ("B2, value 40, formula, has note, selected",
DocumentViewerStrings.cellDescription); the grid shows a focus ring while the keyboard drives it; jumps do not animate when the system asks for reduced motion. - Behaviour change: the column-header row is 44 px tall (was 36), for touch.
Spreadsheets: cell look and density #
- Lighter selection: selected cells keep their own fill and text under a light tint of the selection colour (14%), with an outline round the range and a border on the active cell, instead of a dark block.
SpreadsheetView(selectionColor: …)sets the colour (default: the theme's primary). Row and column headers the selection touches get a tint, accent text and a bar on their inner edge. - Density:
SheetDensity.touch(36 px rows, 44 px headers, 104 px columns, 40 px row numbers, 6/4 padding) andSheetDensity.compact(28 px rows and headers, 100 px columns, 44 px row numbers, 6/2 padding), withSheetMetrics.SpreadsheetController(density: …)fixes it; left null, a desktop with a mouse is compact and a phone is touch, and a touch screen on a desktop switches to touch when the finger lifts (and back when the mouse moves). The row at the top stays in view when it changes. Behaviour change: touch columns are 104 px (were 110), row numbers 40 px wide (were 48), vertical cell padding 4 (was 2);SpreadsheetController.cellWidth,cellHeight,headerHeight,rowHeaderWidthare the touch values. - Ghost grid: faint gridlines and a header bar continue past a small sheet's data, so it fills the view.
- Numbers that do not fit show
#marks (as Excel does) instead of a shortened figure; text still ends in an ellipsis. - Scrollbars:
SpreadsheetView(showScrollbars: true)(default): draggable ones in a gutter on a desktop, thumbs that fade on a phone. - Desktop pointer: hover tint on cells; drag a column's right edge to resize it, or double-click it to fit its text (view only: the file is untouched, and widths reset when another file loads:
setColumnWidth,autoFitColumn,hasColumnWidthOverride); right-click a cell for Copy, Copy address and Details. - Touch selection reworked: a tapped cell or range shows two corner handles at once (no long press first); drag one to grow or shrink the selection. A long press still selects and the same finger drags on. Scrolling is off only while a finger holds a handle or drags after a long press, so a swipe scrolls as usual with a selection showing. Grabbing a handle never moves the selection (the corner follows the finger from where it touched), a light haptic tick marks each cell the selection grows by, and the status bar always keeps its Copy, Copy address and Clear buttons. Behaviour change: the touch toolbar with Done is gone.
- Resize a column by touch (this view only; the file is untouched): tap a column header and drag the grip that appears on its right edge, or long-press the edge between two headers and drag with the same finger (a guide line shows the new edge, a haptic tick marks the start). Double-tap the grip, or use the new column-width menu in the status bar, to fit the column to its text or go back to the file's width. Scrolling is off only while a finger holds the grip.
autoFitColumn(column, baseStyle: …)measures with the text style the cells inherit. - Mouse and keyboard on a touch device: the layout follows the input in use, on every platform. A mouse over the grid (a tablet with a mouse attached) gives compact rows, draggable scrollbars, resize handles and hover; a finger gives the touch layout again, with handles. A mouse never shows handles. Ctrl/Cmd with
+,-and0zoom from the keyboard. - Gridlines are one physical pixel (never thinner than a hairline), selection handles are smaller dots (same 48 px touch area), and text never drops below 11 px when zoomed out.
Architecture #
- Parsers and models all live under
src/engines/(the PPTX parser moved there;engines/sheetsis nowengines/spreadsheet), and the test builders undersrc/testing/. The public libraries and their names are unchanged. - A
Finalizercloses aPdfiumDocumentthat's garbage-collected withoutclose(). looksLikeBinary(inuniversal_document_viewer.dart) is the binary-file check the plain-text and CSV readers share;PlainTextController.looksBinaryforwards to it.- Tests now check every entry point's exports, the import rules between modules (documented in
doc/architecture.md), and that XML entities declared in a DTD aren't expanded.
Fixed #
goTobefore the document is loaded or its view has laid it out is no longer lost: it takes effect once the view is ready, for every format (it was dropped for plain text, spreadsheets and Word's continuous layout). A PDF zoom set before its view exists is applied the same way, andzoomreports it meanwhile.- A
PdfViewbuilt after its controller had opened the document (asDocumentViewerdoes) showed a spinner forever. - Giving a
WordVieworPlainTextViewanother controller kept the old document's layout state (Word's mode, zoom and pages; plain text's scroll listener); aSpreadsheetViewdidn't restore the new controller's scroll position. - Spreadsheets: a cancelled pointer (a scroll that takes over a touch) no longer flips a desktop to the touch layout, and the focus ring appears only after a key press, not after a click.
- A damaged
.xlsxis reported as damaged instead of opening as a CSV of its bytes; binary content in a.csvis refused.
Changed #
- Plain text: more space between lines and wider margins.
- The search status reads "2 of 4" (was "2 of 4 result(s)").
0.1.4 #
Desktop PDF reading.
PdfView(showScrollbar: true): a draggable vertical scrollbar in its own gutter at the right edge, following the view's position and size; click the track to jump. Off by default, meant for mouse-driven desktops. Only applies to the vertical (continuous) layout.- Touchpad scrolling no longer zooms the PDF on Windows, Linux and macOS. A precision touchpad reports a two-finger scroll as a pan-zoom gesture with a little scale noise, and
InteractiveViewerreads any scale other than 1 as a pinch, so a plain scroll also zoomed. On those platforms its own scale is now off and a deliberate trackpad pinch (a scale change past 6%) still zooms. Ctrl + wheel, double-click and the controller's zoom are unchanged. Touch pinch on Android and iOS is unchanged; a touch screen on a desktop OS no longer pinches inPdfView.
0.1.1 #
- Screenshots on pub.dev and in the README.
- The example app's home screen is a grid of document cards with large thumbnails and format badges, and its sample documents read like real ones (a guide PDF, a quarterly report, a sales workbook).
- README: a "Coming soon" section for legacy
.xls,.docand.pptfiles. - No changes to the package's code.
0.1.0 #
First release.
universal_document_viewer reads every format with its own engines: PDF through its own bindings to PDFium (downloaded at build time from bblanchon/pdfium-binaries, pinned release and SHA-256), and Word, Excel, CSV and PowerPoint with Dart readers written for the package from the file-format specifications.
- Any file:
DocumentViewer.file(path)picks the reader by file type, restoresinitialPosition, reportsonPositionChangedand takes anerrorBuilderand apasswordProviderfor encrypted PDFs. - PDF:
PdfDocumentControllerandPdfDocumentView. Continuous or horizontal layout, pinch/double-tap/wheel zoom with tiled rendering, password-protected files, search with highlights and a text-layer check, web and page links. - Word (.docx):
WordDocumentControllerandWordDocumentView. Parsed off the UI isolate; continuous layout or print layout with measured pages, headers, footers and page numbers; styles, lists, tables with merged cells, images, links, footnotes and endnotes; search. The engine on its own is inword.dart(DocxReader,WordDocument). - Spreadsheets (.xlsx, CSV):
SpreadsheetControllerandSheetGrid, a lazy 2D grid. Column widths and row heights from the file, hidden rows/columns/sheets, frozen panes, merged cells, text and number formatting, links, search, zoom, row/column Count/Sum/Average.- Cell borders, conditional formatting and comments, as the author set them up:
- Conditional formatting: comparisons, text matches, blanks, errors, top/bottom N, above/below average, duplicates, colour scales and data bars. Rules that need a formula evaluated are left out.
- Comments: shown as notes, with a corner marker.
- Tapping a cell shows its formula, as Excel's formula bar does, and its note. A formula filled down a column shows in each cell with its references moved.
SpreadsheetController.goToandshowGoToDialogjump to a cell (D120,Sheet2!B3) or a sheet by name, and mark the cell.freezeTopRowkeeps the header row on screen in a sheet whose file froze none. It's saved in the position asfreeze_top_row.
- Cell borders, conditional formatting and comments, as the author set them up:
- Thumbnails:
DocumentThumbnails.render(path, width:)draws the first page of any supported file as a PNG. Given a savedposition:, it draws the page reading resumes on. The Word and text readers report the paragraph or line at the top (PositionKeys.paragraph,PositionKeys.line) for this. - PowerPoint (.pptx):
SlideDeckController,SlideDeckViewandSlideNavigationBar. Titles, paragraphs, tables and pictures; search. - Text (.txt, .md):
TextDocumentControllerandTextDocumentView. UTF-8 with a Latin-1 fallback, binary-file check, search. - Shared:
DocumentFormat(from extension, path or MIME type),ZipSafetyGuardfor Office files (with a file-size ceiling checked before reading, and parts never inflated past their declared size), reading positions as JSON-safe maps (ReadingPosition,PositionKeys), typed load errors (DocumentLoadError), andtesting.dartbuilders for in-memory test documents. - Platforms: Android, iOS, macOS, Windows and Linux. Web is not supported yet.
