pavels0 / docx_template_dart Goto Github PK
View Code? Open in Web Editor NEWA Docx template engine
License: Apache License 2.0
A Docx template engine
License: Apache License 2.0
final data = await rootBundle.load('assets/template.docx');
final bytes = data.buffer.asUint8List();
final docx = await DocxTemplate.fromBytes(bytes);
ByteData byteData = await rootBundle.load('assets/logo.png');
Uint8List testFileContent = byteData.buffer.asUint8List();
final listNormal = ['Foo', 'Bar', 'Baz'];
final listBold = ['ooF', 'raB', 'zaB'];
final contentList = <Content>[];
final b = listBold.iterator;
for (var n in listNormal) {
b.moveNext();
final c = PlainContent("value")
..add(TextContent("normal", n))
..add(TextContent("bold", b.current));
contentList.add(c);
}
Content c = Content();
c
..add(TextContent("docname", "Dodument Name"))
..add(TextContent("passport", "Passport NE0323 4456673"))
..add(TableContent("table", [
RowContent()
..add(TextContent("key1", "Viberg"))
..add(TextContent("key2", "Viberg"))
..add(TextContent("key3", "Engineer"))
..add(ImageContent('img', testFileContent)),
RowContent()
..add(TextContent("key1", "Alex"))
..add(TextContent("key2", "Houser"))
..add(TextContent("key3", "CEO & Founder"))
..add(ListContent("tablelist", [
TextContent("value", "Mercedes-Benz C-Class S205"),
TextContent("value", "Lexus LX 570")
]))
..add(ImageContent('img', testFileContent))
]))
..add(ListContent("list", [
TextContent("value", "Engine")
..add(ListContent("listnested", contentList)),
TextContent("value", "Gearbox"),
TextContent("value", "Chassis")
]))
..add(ListContent("plainlist", [
PlainContent("plainview")
..add(TableContent("table", [
RowContent()
..add(TextContent("key1", "Paul"))
..add(TextContent("key2", "Viberg"))
..add(TextContent("key3", "Engineer")),
RowContent()
..add(TextContent("key1", "Alex"))
..add(TextContent("key2", "Houser"))
..add(TextContent("key3", "CEO & Founder"))
..add(ListContent("tablelist", [
TextContent("value", "Mercedes-Benz C-Class S205"),
TextContent("value", "Lexus LX 570")
]))
])),
PlainContent("plainview")
..add(TableContent("table", [
RowContent()
..add(TextContent("key1", "Nathan"))
..add(TextContent("key2", "Anceaux"))
..add(TextContent("key3", "Music artist"))
..add(ListContent(
"tablelist", [TextContent("value", "Peugeot 508")])),
RowContent()
..add(TextContent("key1", "Louis"))
..add(TextContent("key2", "Houplain"))
..add(TextContent("key3", "Music artist"))
..add(ListContent("tablelist", [
TextContent("value", "Range Rover Velar"),
TextContent("value", "Lada Vesta SW Sport")
]))
])),
]))
..add(ListContent("multilineList", [
PlainContent("multilinePlain")
..add(TextContent('multilineText', 'line 1')),
PlainContent("multilinePlain")
..add(TextContent('multilineText', 'line 2')),
PlainContent("multilinePlain")
..add(TextContent('multilineText', 'line 3'))
]))
..add(TextContent('multilineText2', 'line 1\nline 2\n line 3'))
..add(ImageContent('img', testFileContent));
final d = await docx.generate(c);
final dbBytes = await rootBundle.load('assets/generated.docx');
final of = await writeToFile(dbBytes);
if (d != null) await of.writeAsBytes(d);
And use this metod:
Future<File> writeToFile(ByteData data) async {
final buffer = data.buffer;
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
var filePath = tempPath + '/new.docx';
print(filePath);
final bytes = data.buffer.asUint8List();
return new File(filePath).writeAsBytes(bytes);
}
Great package everything works
Would be a nice addition to be able to export or "print" the document in PDF format after the generation
I don't find any docx file reader in pub.dev. Please support this if possible. Simply I need plain text from docx. Or please suggest if any other solution available to get text content from docx.
Hello, I am trying to open generated.docx but I am seeing corrupted word file. and I can't opening.
can you help me?
I try using this function but it doesn't work
Future<void> _saveFile() async {
final data = await rootBundle.load('assets/template.docx');
final bytes = data.buffer.asUint8List();
final docx = await DocxTemplate.fromBytes(bytes);
Content c = Content();
c.add(TextContent("content", contentController.text));
final d = await docx.generate(c);
List<StorageInfo> storageInfo = await PathProviderEx2.getStorageInfo();
var root = storageInfo[0].rootDir; // root of the "external storage"
final directory = Directory("$root/Download");
final file = File('${directory.path}/${nameController.text}.docx');
if (d != null) await file.writeAsBytes(d);
}
Hi,
I have this list :
Task:
I don't know how to have the bold side and the normal side text .
If you can help me please.
Thank you for your work !
It would be possible to convert a docx to PDF by programming ?
I try to create a new doc file, but when I invoke DocxTemplate.fromBytes(await f.readAsBytes())
, get error
[VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: FormatException: Could not find End of Central Directory Record
here is my code
final f = await LLCFileUtil.getLocalFile('test', 'template.docx');
if (!f.existsSync()) {
f.createSync();
}
final byte = await f.readAsBytes();
final docx = await DocxTemplate.fromBytes(byte);
and the f.path
was /var/mobile/Containers/Data/Application/AB671DDF-9D0E-4B40-B7A9-2252E71F433E/Documents/test/template.docx
file:
view.dart
function;
void _updateRText(....
Line 149:
r.children.insert(pasteIndex++, _brElement());
must be changed to:
if (l != lines.last) { r.children.insert(pasteIndex++, _brElement()); }
Hi, in many cases when I use a table with text content inside, the result is that the rows are duplicated or/and the keys are not substituted by the values.
Any idea?
The example works properly for me, but in most cases tables don't. I'm using Office2013
im getting this error
E/flutter ( 4561): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Concurrent modification during iteration: Instance(length:4) of '_GrowableList'.
``` what is happening?
Hi,
can you update your dependency to the xml package to the newest version.
Hi, i get this error :
E/flutter (16144): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'TextContent' is not a subtype of type 'PlainContent?' of 'c'
but i read that you said youu fixed it in commit a864546 but it still don't work for me
code.. throws this error when i do "await docx.generate(c);"
..add(ListContent("multilineList", [
PlainContent("multilinePlain")
..add(TextContent('multilineText', 'line 1')),
PlainContent("multilinePlain")
..add(TextContent('multilineText', 'line 2')),
PlainContent("multilinePlain")
..add(TextContent('multilineText', 'line 3'))
]))
..add(TextContent('multilineText2', 'line 1\nline 2\n line 3'))
..add(ImageContent('img', testFileContent));
final d = await docx.generate(c);
Hi,
I try to create a document like this dynamically :
Title :
// dynamically
Thank you for you work on this package !
Hi,
how is it possible to insert an image into a table which keeps its original aspect ratio?
Expected Behaviour
I want to add images of varying aspect ratio into a table. I would expect the image width to adjust to the width of the row and the height should vary depending on the aspect ratio.
Current Behaviour:
However, when inserting an image it is inserted into exactly the same aspect ratio as defined in the template. So when using the example template, my image is inserted into a square with equal dimensions, so that the image distorted.
Regards
Fabian
Hi, Awesome library for docx.
Actually, I want a normal paragraph with text style like bold and Color of text which is possible with this library. if yes then you saved my day thanks.
When trying to run the example on , I get FormatException: Could not find End of Central Directory Record. This is the code that I specifically used:
final data = await rootBundle.load('lib\\assets\\template.docx');
final bytes = data.buffer.asUint8List();
final docx = await DocxTemplate.fromBytes(bytes);
Hi, first i want to give thanks for developing this.
i am currently using it to generate word data for my app.
i have only one question: can i edit the layout like font style, color and such thing?
Many thanks for your great plugins.
i've facing issue when create content within table which is created dynamically
need your suggesstion what i'm missing?
here is my error
I/flutter ( 2617): NoSuchMethodError: The method 'add' was called on null.
I/flutter ( 2617): Receiver: null
I/flutter ( 2617): Tried calling: add(Instance of 'RowContent')
here is my code
List<RowContent> aRow;
for (int i = 0; i < data3.length; i++) {
aRow.add(
RowContent()
..add(TextContent("xxNo", i + 1))
..add(TextContent("xxJenis", data3[i]['xJenis']))
..add(TextContent("xxMerk", "---")),
);
}
c
..add(TableContent("table", aRow));
final docx = await DocxTemplate.fromBytes(bytes);
List<RowContent> rows = [];
for (int i = 0; i < test.testQuestions.length; i++) {
rows.add(RowContent()
..add(TextContent("key1", "${i + 1}"))
..add(TextContent("key2", test.testQuestions[i].text)));
for (int j = 0; j < test.testQuestions[i].questionAnswers.length; j++) {
if (test.testQuestions[i].questionAnswers[j].correct == true &&
test.testQuestions[i].questionAnswers[j].checked == true) {
// ako je user odgovorio tacno
rows.add(RowContent()
..add(TextContent(
"key2", setAnswerOrder(j) + test.testQuestions[i].questionAnswers[j].text))
..add(TextContent("key3", "x")));
} else if (test.testQuestions[i].questionAnswers[j].correct == false &&
test.testQuestions[i].questionAnswers[j].checked == true) {
rows.add(RowContent()
..add(TextContent(
"key2", setAnswerOrder(j) + test.testQuestions[i].questionAnswers[j].text))
..add(TextContent("key4", "x")));
} else {
rows.add(RowContent()
..add(TextContent(
"key2", setAnswerOrder(j) + test.testQuestions[i].questionAnswers[j].text)));
}
}
}
Content c = Content();
c
..add(TextContent("training", training.name))
..add(TextContent("name", "${user.firstName} ${user.lastName}"))
..add(TextContent("username", user.userName))
..add(TextContent("workPosition", user.jobPosition))
..add(TextContent("department", user.departmentName))
..add(TableContent("table", rows));
**final d = await docx.generate(c);** LINE WITH ERROR
var dir = await getExternalStorageDirectory();
print('PUTANJA: ${dir.path}');
Excuse me. Can I add a hyperlink to a Word document that leads to an online file? I'm wondering whether this feature is supported. Thanks.
Hello, thanks for the package.
Can you please tell me if there is a way to change the Header and footer parts as for the moment it seems that only the body of the document is concidered.
Thanks in advance for your help.
I have a template file from which i generate a new file, not all tags are filled so i save them with the new tag policy. after that i generate another file from the previous generated file, when i do this i get a corrupted error in word. it doesnt seem to actually affect the contents of the file but i still get the error.
Can we avoid using File or have alternate logic of using File using https://pub.dev/packages/file_access instead of dart:io's File .
An 'Unsupported operation: Cannot modify an unmodifiable list' is raised on arch.files[_index] = ArchiveFile(_name, data.length, data);
I created a unit test following the example.
final file = File('test_resources/template.docx');
final docx = await DocxTemplate.fromBytes(await file.readAsBytes());
Content content = Content();
content
..add(TextContent("header", "Nice header"))
..add(TextContent("footer", "Nice footer"))
..add(TextContent("docname", "Simple docname"))
..add(TextContent("passport", "Passport NE0323 4456673"));
final docGenerated = await docx.generate(content);
final fileGenerated = File('test_resources/generated.docx');
if (docGenerated != null) await fileGenerated.writeAsBytes(docGenerated);
});
In this example an unmodifiable list exception is raised:
dart:_internal UnmodifiableListMixin.[]=
package:docx_template/src/docx_entry.dart 29:17 DocxEntry._updateData
package:docx_template/src/docx_entry.dart 58:7 DocxXmlEntry._updateArchive
package:docx_template/src/docx_entry.dart 185:13 DocxManager.updateArch.
dart:collection _LinkedHashMapMixin.forEach
package:docx_template/src/docx_entry.dart 184:10 DocxManager.updateArch
package:docx_template/src/template.dart 95:14 DocxTemplate.generate
test\utils\cv_generator_test.dart 18:37 main.
Unsupported operation: Cannot modify an unmodifiable list
I used version 0.3.6 of docx_template. I upgraded to 0.4.0 but that didn't solve the issue.
final d = await docx.generate(c);
return getCrc32(file.content as List); line 91
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'List' in type cast
#0 ZipEncoder.getFileCrc32
package:archive/src/zip_encoder.dart:91
@PavelS0 Is is possible to have a table than have a row that is spit in two rows?
You can see example in docx
example.docx
Hello , I try to use package for flutter, when I run command flutter pub get
I get this error
Running "flutter pub get" in wordtemplate...
Because every version of flutter from sdk depends on meta 1.1.8 and xml >=4.3.0 depends on meta ^1.2.0, flutter from sdk is incompatible with xml >=4.3.0.
And because docx_template >=0.2.1 depends on xml ^4.4.0, flutter from sdk is incompatible with docx_template >=0.2.1.
So, because wordtemplate depends on both flutter any from sdk and docx_template ^0.2.1, version solving failed.
pub get failed (1; So, because wordtemplate depends on both flutter any from sdk and docx_template ^0.2.1, version solving failed.)
exit code 1
I resolve it by changing to this version
xml: ^3.7.0
meta: ^1.1.8
docx_template: ^0.2.0
so my new problem about this version is not compatible with web.
and I ask if you can to provide us example in flutter. I think your package is good but the documentation It lacks a detailed explanation
https://stackoverflow.com/questions/66770150/dart-generated-docx-file-gets-corrupted
I have left this question, i dont know if it is an issue with my code or with the package and i would appriciate it if someone could take a look at it.
Hey!
I encountered a problem when using keys. Maybe I'm doing something wrong?
code:
final content = Content()
..add(TextContent('number', requisites.number))
..add(TextContent('date', requisites.date))
..add(TextContent('name', requisites.name))
..add(TextContent('address', requisites.address))
..add(TextContent('inn', requisites.inn))
..add(TextContent('kpp', requisites.kpp))
..add(TextContent('accountNumber', requisites.account))
..add(TextContent('korrAccount', requisites.korrAccount))
..add(TextContent('bank', requisites.bank))
..add(TextContent('bik', requisites.bik))
..add(TextContent('shortName', requisites.name));
final d = await template.generate(content);
In my template I use variables in the following form: {number}, {date}, {name}, etc. Requisites parameters is not empty. But in content
output I see:
{number: {}, date: {}, name: {}, address: {}, inn: {}, kpp: {}, accountNumber: {}, korrAccount: {}, bank: {}, bik: {}, shortName: {}}
All parameters of requisites are String.
i want text only
Consider the following scenario:
Step 1: I load a docx file:
(...)
DocxTemplate? template;
(...)
final data = await rootBundle.load(file.path);
final bytes = data.buffer.asUint8List();
template = await DocxTemplate.fromBytes(bytes);
Step 2: Once the template is loaded, I get its tags to show to the user:
final formFields = widget.docController.template.getTags()
Step 3: After getting values of the tags, I try to use the same reference of template and save it:
final docGenerated = await widget.docController.template.generate(content);
final of = File(filePath);
await of.writeAsBytes(docGenerated);
The problem is that the doc file is corrupted. But, if I load the DocxTemplate instance once again using fromBytes, the document is generated correctly. Alternatively, I did another test: I commented out the line that getTags() and generated the docx without reloading the DocxTemplate instance once again using fromBytes, and it worked as expected. In other words, as the title of this issue says: when I call getTags and later try to use the template reference, it generates a corrupted docx file.
Any suggestion?
Thank you!
I always get the Error: Unsupported operation: _Namespace. As I understand it, dart:io doesn't work for the Web. How to work with Docx_Template on the Web?
i have a few tags which i dont want to get deleted when i dont fill them, enabling the option "never delete this tag" in word doesnt work, how can i do this?
I am trying to create word document in my app, but when I use this package first I got error that says
=> ConcurrentModificationError (Concurrent modification during iteration: Instance(length:0) of '_GrowableList'.)
Then I think that I might wrote something wrong, then I copied example code and tried to run it but there is another error now.
=> _TypeError (type 'TextContent' is not a subtype of type 'PlainContent?' of 'c')
I did not change anything at all on the example code (just file paths)
I am using null safety pre-release because latest stable version gives version solving errors.
does not work with newer versions of Word, template file does not open
As I understand it, the structure has changed in the new version, it shows obsolete elements, you can add a definition of the template version
Hi,
I'm trying to add images dynamically into a list.
final listImages = <Content>[];
for (var i = 0; i < 10; i++)
listImages.add(ImageContent("img", testFileContent));
Content c = Content();
c..add(TextContent("docname", "Simple test"))
..add(ListContent("list", listImages));
But it doesn't work :/
Hi,
It would be really useful to supporto also templates in .dot and .dotx
[#]The code :
DocxTemplate docx = DocxTemplate();
File f = File("assets/template.docx");
await docx.load(f);
Anybody help please. Thanks
If I add the images in RowContent plugin throws an exception
`
List rows = [];
for(int i=0; i <report.summaryOfSightings.length; i++){
final element = report.summaryOfSightings[i];
// list.add();
rows.add(
RowContent()
..add(TextContent("key2", element.comment))
..add(ImageContent("image", element.pdfImage))
);
}
`
E/flutter ( 1387): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type 'ImageContent' is not a subtype of type 'TableContent' of 'c' E/flutter ( 1387): #0 RowView.produce (package:docx_template/src/view.dart) E/flutter ( 1387): #1 ViewManager._produceInner (package:docx_template/src/view_manager.dart:106:20) E/flutter ( 1387): #2 ListView.produce (package:docx_template/src/view.dart:327:14) E/flutter ( 1387): #3 ViewManager._produceInner (package:docx_template/src/view_manager.dart:104:20) E/flutter ( 1387): #4 ViewManager.produce (package:docx_template/src/view_manager.dart:95:9) E/flutter ( 1387): #5 DocxTemplate.generate (package:docx_template/src/template.dart:27:8) E/flutter ( 1387): #6 _AddFieldReportState.save (package:flutter_template/pages/inspection/add_field_report.dart:723:26) E/flutter ( 1387): <asynchronous suspension> E/flutter ( 1387):
If the method getTags is invoked in the template, the resulting document is corrupted and cannot be opened
Thanks for the plugin, but I was wondering if you have plans for web support? Currently you rely on dart.io which is non functional in web.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.