build method

Future<Uint8List> build()

Implementation

Future<Uint8List> build() async {
  // Pre-assegna gli ID a tutti i commenti e le reply
  final allComments = document.commentProvider?.exportComments() ?? [];
  for (final c in allComments) {
    if (c['resolved'] == true || c['orphan'] == true) continue;
    final docxId = _ensureDocxCommentId(c);
    final replies = (c['replies'] as List<dynamic>?) ?? [];
    for (var ri = 0; ri < replies.length; ri++) {
      final replyId = _commentIdCounter++;
      _replyDocxIds['${docxId}_$ri'] = replyId;
    }
  }

  final root = document.content;
  for (final node in root.nodes) {
    _writeNode(node);
  }

  final archive = Archive();

  // Embed system fonts
  for (final fontName in _fonts) {
    final bytes = await _findSystemFontBytes(fontName);
    if (bytes != null) {
      final fileName = 'font${_mediaCounter++}.ttf';
      archive
          .addFile(ArchiveFile('word/fonts/$fileName', bytes.length, bytes));
      _addRel(
          'http://schemas.openxmlformats.org/officeDocument/2006/relationships/font',
          'fonts/$fileName');
    }
  }

  if (_numDefs.isNotEmpty) {
    _add(archive, 'word/numbering.xml', _numberingXml());
    _addRel(
        'http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering',
        'numbering.xml');
  }

  if (_docxComments.isNotEmpty) {
    _add(archive, 'word/comments.xml', _commentsXml());
    _add(archive, 'word/commentsExtended.xml', _commentsExtendedXml());
    _addRel(
        'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments',
        'comments.xml');
    _addRel(
        'http://schemas.microsoft.com/office/2011/relationships/commentsExtended',
        'commentsExtended.xml');
  }

  _add(archive, '[Content_Types].xml', _contentTypes());
  _add(archive, '_rels/.rels', _rootRels());
  _add(archive, 'word/document.xml', _documentXml());
  _add(archive, 'word/_rels/document.xml.rels', _documentRels());
  for (final e in _mediaBytes.entries) {
    archive
        .addFile(ArchiveFile('word/media/${e.key}', e.value.length, e.value));
  }
  return Uint8List.fromList(ZipEncoder().encode(archive)!);
}