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

Cant figure out how to append to an existing file, need help! #13

Closed timohahaa closed 9 months ago

timohahaa commented 9 months ago

I try to append new text to an existing docx file like this:

readFile, err := os.Open(filename)
if err != nil {
    // ...
}
fileinfo, err := readFile.Stat()
if err != nil {
    //...
}
size := fileinfo.Size()
oldDoc, err := docx.Parse(readFile, size)
if err != nil {
    //...
}
doc := docx.LoadBodyItems(oldDoc.Document.Body.Items, []docx.Media{})
p := doc.AddParagraph()
p.AddText(text).Size("10")
if err != nil {
    //...
}
_, err = doc.WriteTo(readFile)
if err != nil {
    //...
}
err = readFile.Close()
if err != nil {
    //...
}

but it just adds new content and erases the old file...

It also seems to ignore '\n' in the text - no new lines are made, how do I insert a new line?

fumiama commented 9 months ago

The issue is because that you used the LoadBodyItems function, which will clear the doc file. Actually I have written a function named func (f *Docx) AppendFile(af *Docx) for the file-appending. You can refer to the last few lines of the file structdoc.go.

fumiama commented 9 months ago

As for the \n, it is ignored by Word because it is replaced by just adding a new paragraph.

timohahaa commented 9 months ago

Thanks for the help!