// Most modern office formats are xml based and can be unarchived.
// .docm and .xlsm files are comprised of xml, and a binary blob for the macro code
// Zip archives require random access for reading, so it's hard to stream bytes. Solution seems to be to use a buffer.
// See https://stackoverflow.com/questions/16946978/how-to-unzip-io-readcloser
b:=new(bytes.Buffer)
b.ReadFrom(decodedAttachment)
zipReader,err:=zip.NewReader(bytes.NewReader(b.Bytes()),int64(b.Len()))// Create a new zip reader from the file
iferr!=nil{
returnnil,err
}
newZipArchive:=new(bytes.Buffer)
zipWriter:=zip.NewWriter(newZipArchive)// For writing the new archive
// i. Read each file from the Word document archive
// ii. Apply the template to it
// iii. Add the templated content to a new zip Word archive
a.vanillaFile=true
for_,zipFile:=rangezipReader.File{
ff,err:=zipFile.Open()
iferr!=nil{
returnnil,err
}
deferff.Close()
contents,err:=ioutil.ReadAll(ff)
iferr!=nil{
returnnil,err
}
subFileExtension:=filepath.Ext(zipFile.Name)
vartFilestring
ifsubFileExtension==".xml"||subFileExtension==".rels"{// Ignore other files, e.g binary ones and images
// First we look for instances where Word has URL escaped our template variables. This seems to happen when inserting a remote image, converting {{.Foo}} to %7b%7b.foo%7d%7d.
// See https://stackoverflow.com/questions/68287630/disable-url-encoding-for-includepicture-in-microsoft-word