最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dart - Flutter docx_template removes tab spaces when replacing placeholders - Stack Overflow

programmeradmin4浏览0评论

I'm using the docx_template: ^0.4.0 package in my Flutter app to replace placeholders in a .docx file while preserving the original format. The issue is that tab spaces between fields are getting removed when generating the final document.

For example, my source file contains: First name: {first_name} (tab space) Last name: {last_name}

After replacement, it becomes: First name: JohnLast name: Doe

The tab space is missing.

How can I ensure that tab spaces and formatting are preserved when replacing placeholders in the .docx file? Is there a way to handle this within docx_template or another approach to maintain the document’s structure?

Any help would be appreciated!

Future<void> _generateDocument() async {
setState(() {
  isGenerating = true;
});

try {
  final basePath = await _getAppDataPath();
  final employeeGenDir =
      Directory('$basePath/generated_documents/${widget.employee['id']}');
  if (!await employeeGenDir.exists()) {
    await employeeGenDir.create(recursive: true);
  }

  final selectedDocInfo = documents.firstWhere(
    (doc) => doc['document_name'] == selectedDocument,
  );

  final templateFile = File(selectedDocInfo['document_path']);
  final templateBytes = await templateFile.readAsBytes();
  final docx = await DocxTemplate.fromBytes(templateBytes);

  final Map<String, String> contentMap = {};
  for (var mapping in selectedDocumentMappings) {
    final key = mapping.replaceAll(RegExp(r'[{}]'), '');
    contentMap[key] = mappingInputs[mapping] ?? '';
  }

  Content content = Content();
  contentMap.forEach((key, value) {
    content.add(TextContent(key, value));
  });

  final generatedBytes = await docx.generate(content);
  if (generatedBytes == null) {
    throw Exception('Failed to generate document');
  }

  final now = DateTime.now();
  final timestamp =
      '${now.year}${now.month}${now.day}_${now.hour}${now.minute}${now.second}';
  final outputFile =
      File('${employeeGenDir.path}/${selectedDocument}_$timestamp.docx');
  await outputFile.writeAsBytes(generatedBytes);

  if (mounted) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content:
            Text('Document generated successfully at ${outputFile.path}'),
        backgroundColor: Colors.green,
      ),
    );
  }
} catch (e) {
  print('Error generating document: $e');
  if (mounted) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Error generating document'),
        backgroundColor: Colors.red,
      ),
    );
  }
} finally {
  setState(() {
    isGenerating = false;
  });
}

}

I tried using docx_template to replace placeholders like {first_name} while keeping the document's original formatting. I expected the generated .docx to preserve tab spaces, but they were removed, making the text run together. I also checked if extra spaces or formatting options in the .docx could help, but the issue persists, it keeps saying flutter: Error generating document: Unsupported operation: Cannot modify an unmodifiable list

I'm using the docx_template: ^0.4.0 package in my Flutter app to replace placeholders in a .docx file while preserving the original format. The issue is that tab spaces between fields are getting removed when generating the final document.

For example, my source file contains: First name: {first_name} (tab space) Last name: {last_name}

After replacement, it becomes: First name: JohnLast name: Doe

The tab space is missing.

How can I ensure that tab spaces and formatting are preserved when replacing placeholders in the .docx file? Is there a way to handle this within docx_template or another approach to maintain the document’s structure?

Any help would be appreciated!

Future<void> _generateDocument() async {
setState(() {
  isGenerating = true;
});

try {
  final basePath = await _getAppDataPath();
  final employeeGenDir =
      Directory('$basePath/generated_documents/${widget.employee['id']}');
  if (!await employeeGenDir.exists()) {
    await employeeGenDir.create(recursive: true);
  }

  final selectedDocInfo = documents.firstWhere(
    (doc) => doc['document_name'] == selectedDocument,
  );

  final templateFile = File(selectedDocInfo['document_path']);
  final templateBytes = await templateFile.readAsBytes();
  final docx = await DocxTemplate.fromBytes(templateBytes);

  final Map<String, String> contentMap = {};
  for (var mapping in selectedDocumentMappings) {
    final key = mapping.replaceAll(RegExp(r'[{}]'), '');
    contentMap[key] = mappingInputs[mapping] ?? '';
  }

  Content content = Content();
  contentMap.forEach((key, value) {
    content.add(TextContent(key, value));
  });

  final generatedBytes = await docx.generate(content);
  if (generatedBytes == null) {
    throw Exception('Failed to generate document');
  }

  final now = DateTime.now();
  final timestamp =
      '${now.year}${now.month}${now.day}_${now.hour}${now.minute}${now.second}';
  final outputFile =
      File('${employeeGenDir.path}/${selectedDocument}_$timestamp.docx');
  await outputFile.writeAsBytes(generatedBytes);

  if (mounted) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content:
            Text('Document generated successfully at ${outputFile.path}'),
        backgroundColor: Colors.green,
      ),
    );
  }
} catch (e) {
  print('Error generating document: $e');
  if (mounted) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Error generating document'),
        backgroundColor: Colors.red,
      ),
    );
  }
} finally {
  setState(() {
    isGenerating = false;
  });
}

}

I tried using docx_template to replace placeholders like {first_name} while keeping the document's original formatting. I expected the generated .docx to preserve tab spaces, but they were removed, making the text run together. I also checked if extra spaces or formatting options in the .docx could help, but the issue persists, it keeps saying flutter: Error generating document: Unsupported operation: Cannot modify an unmodifiable list

Share Improve this question edited Feb 18 at 19:48 Imad Eddine asked Feb 17 at 6:53 Imad EddineImad Eddine 112 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

The docx_template package removes tab spaces because it processes placeholders as plain text. Here are some ways to preserve formatting:

Solutions

Use Explicit Tab Characters (\t)Add a tab manually when assigning values:

data = {'first_name': 'John\t', 'last_name': 'Doe'};

Use StyledText to Preserve Formatting

content.add(TextContent('first_name', 'John'));
content.add(TextContent('last_name', 'Doe'));

Insert a {tab} Placeholder in the .docx TemplateModify the template like this:

First name: {first_name}   {tab}   Last name: {last_name}

Then replace {tab} in your code:

data = {'first_name': 'John', 'tab': '\t', 'last_name': 'Doe'};

Use a Table in .docxInstead of relying on spaces, use a table to align fields properly.

Try an Alternative LibraryIf the issue persists, consider docx_rw or python-docx for better formatting control.

发布评论

评论列表(0)

  1. 暂无评论