fumiama / go-docx

One of the most functional libraries to partially read and write .docx files (a.k.a. Microsoft Word documents or ECMA-376 Office Open XML) in Go.
GNU Affero General Public License v3.0
109 stars 14 forks source link

Still need help appending files... #14

Closed timohahaa closed 9 months ago

timohahaa commented 9 months ago

Hello! I'll try my best to make this issue the last one, so I won't litter issues with my questions that much. Thanks for the help in advance!!! code:

    readFile, err := os.Open(filename)
        if err != nil {
            slog.Error("error while oppening docx file", "unit_guid", devInfo.UnitGuid, "err", err)
        }
        fileinfo, err := readFile.Stat()
        if err != nil {
            slog.Error("error while reading docx file stat file", "unit_guid", devInfo.UnitGuid, "err", err)
        }
        size := fileinfo.Size()
        oldDoc, err := docx.Parse(readFile, size)
        if err != nil {
            slog.Error("error while parsing docx file", "unit_guid", devInfo.UnitGuid, "err", err)
        }
        newDoc := docx.NewA4()
        p := newDoc.AddParagraph()
        p.AddText(text).Size("10")
        // ADD OLD FILE CONTENT HERE
        newDoc.AppendFile(oldDoc)
        if err != nil {
            slog.Error("error while creating file", "unit_guid", devInfo.UnitGuid, "err", err)
        }
        _, err = newDoc.WriteTo(readFile)
        if err != nil {
            slog.Error("error while writing file", "unit_guid", devInfo.UnitGuid, "err", err)
        }
        err = readFile.Close()
        if err != nil {
            slog.Error("error while saving file", "unit_guid", devInfo.UnitGuid, "err", err)
        }

this whole block of code is executed about 3-4 times, and should add one line to the file at a time however, after the program exits, the created file has only one out of 3-4 lines it should I tried literally everything at this point, but still cant get it to work...

fumiama commented 9 months ago

Actually, it is not an issue caused by this lib but some common programming sense. But well, I would not refuse to offer some help. You cannot just write something back to the original file because docx file is actually a zip. It will ignore what you had appended/overlapped after the package. What you should do is moving the file I/O out of your block and use os.Create to create a new file to write to. You can refer to this minimized code:

f, err := os.Create(name)
if err != nil {
    panic(err)
}
newFile := docx.NewA4()
// your loop
for i := 0; i < 10; i++ {
    newFile.AppendFile(doc)
}
// write it at last, only once
_, err = io.Copy(f, newFile)
if err != nil {
    panic(err)
}