amiremohamadi / DuckX

C++ library for creating and modifying Microsoft Word (.docx) files
MIT License
426 stars 110 forks source link

Create docx files #60

Open peterwei272 opened 4 years ago

peterwei272 commented 4 years ago

Does DuckX support to create new docx files? The README file says that it supports to create docx files, but I can only get damaged files after calling the Save function. Maybe I made some mistakes. Could you give me a sample of create new docx files? Thanks a lot.

phuongtran7 commented 4 years ago

I looked into this awhile a go and it seems that currently DuckX cannot create a docx file right now according to this: https://github.com/amiremohamadi/DuckX/issues/23

One hacky way to get around is you can read an empty docx file, created by word or something, into a byte array then write that byte array into a header, basically embedded the empty docx file into your C++ program. After that just write back that byte array into file every time you want to create a new docx file, and then use DuckX to modify it.

mosolovsa commented 3 months ago

You could create empty docx in MS Word and use it's bytes to initialize C uint8_t array to write it's content to file as a workaround:

static const unsigned char EMPTY_DOCX_BYTES[] = { ... };

// add method to duckx::Document that writes empty docx to filesystem
// TODO: handle errors :)
int duckx::Document::create_empty() {
    FILE* file = std::fopen(this->directory.c_str(), "wb");
    std::fwrite(EMPTY_DOCX_BYTES, sizeof(EMPTY_DOCX_BYTES), 1, file);
    std::fflush(file);
    std::fclose(file);
}

Now if you want to create new docx you could:

    duckx::Document doc("test.docx");
    doc.create_empty();
    doc.open();