Code Monkey home page Code Monkey logo

docx_template_dart's People

Contributors

alexandremaillot avatar pavels0 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

docx_template_dart's Issues

If the sample code is not working try this

  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);
  }

NEW FEATURE - PDF Export

Would be a nice addition to be able to export or "print" the document in PDF format after the generation

Add support for reading docx file

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.

word file can't opening

Hello, I am trying to open generated.docx but I am seeing corrupted word file. and I can't opening.
can you help me?

How do I write the textform content into a docx file?

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);
  }

style of the text in a list

Hi,
I have this list :
Task:

  • task1 : task
  • task1 : task
  • task1 : 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 !

Convert docx

It would be possible to convert a docx to PDF by programming ?

How to create a new docs file

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

table does not work properly

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

Unhandled Exception: type 'TextContent' is not a subtype of type 'PlainContent?' of 'c'

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);

How to add TextContent dynamically

Hi,

I try to create a document like this dynamically :

Title :
// dynamically

  • TextContent()
  • TextContent()
  • TextContent()
    -// end

Thank you for you work on this package !

Wrong aspect ratio for images in table

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

FormatException: Could not find End of Central Directory Record

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);

Formatting layout

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?

Create row on table dynamically

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));

docx.generate(c) provide Exception: Concurrent modification during iteration: Instance(length:8) of '_GrowableList'.

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}');

Header and Footer modification

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.

file gets corrupted after generating multiple times

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.

Unsupported operation: Cannot modify an unmodifiable list exception

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.

Windows Error

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

not work with flutter

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

TextContent keys

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.

BUG: DocxTemplate loses reference after calling getTags

@PavelS0

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!

dart:io doesn't work for web

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?

Word file gets corrupted

I am trying to edit a very simple word file with 1 control tag.
Word file is fetched correctly and displayed, but when I use docGenerated = await docx.generate(c);

The file gets corrupted. I am using Office 2016 to create word files.

Screen Shot 2022-11-28 at 3 20 49 PM

Code:
Screen Shot 2022-11-28 at 3 21 16 PM

DOCX Template example is not working

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.

Error:
Screen Shot 2021-05-21 at 00 16 25

does not work with newer versions of Word

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

How to add ImageContent dynamically

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 :/

Error when try load template!!

[#]The code :

DocxTemplate docx = DocxTemplate();
File f = File("assets/template.docx");
await docx.load(f);

[#] The error:
E/flutter (18457): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Creation failed, path = 'docx_cache' (OS Error: Read-only file system, errno = 30)

Anybody help please. Thanks

Cannot add the images inside a table

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):

getTags() corrupt the file

If the method getTags is invoked in the template, the resulting document is corrupted and cannot be opened

Any chance of web support?

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.