How to Convert a Word DOC to DOCX in Go
In 2003, Microsoft upgraded from their binary DOC format to the XML based DOCX format in order to keep up with the changing software world. Unfortunately, one of the inherent consequences is that when you open a Word file in a version other than the one with which it was originally created, it can cause an incorrect display of the document; this can result in skewing of fonts, bullets, and other formatting features. By using the following API in Go you can solve the issue of sharing a Word (97–2003) DOC file with a source using the modern DOCX format.
To call the document conversion function, simply input your target file into the following code:
package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)func main() {url := "https://api.cloudmersive.com/convert/doc/to/docx"
method := "POST"payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open("/path/to/file")
defer file.Close()
part1,
errFile1 := writer.CreateFormFile("inputFile",filepath.Base("/path/to/file"))
_, errFile1 = io.Copy(part1, file)
if errFile1 != nil {
fmt.Println(errFile1)
return
}
err := writer.Close()
if err != nil {
fmt.Println(err)
return
}client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "multipart/form-data")
req.Header.Add("Apikey", "YOUR-API-KEY-HERE")req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
And you’re done! The operation will instantly create a DOCX file for download.