How to Convert DOCX Files to Rich Text Format (RTF) using Go
If we want to remove all formatting from our DOCX file, we’ll want to strip that text from the document into plaint text (TXT) format. If we want to preserve elements of the original formatting, however (such as italicized/bolded letters, various font sizes, etc.), we’ll want to use Rich Text Format (RTF) instead. All in all, RTF is the perfect format to use for transitioning DOCX files to new text-editing applications when we don’t want to lose all of the original aesthetics.
With our DOCX to RTF API, you can easily build this useful file conversion service into your application and avoid manual format transitions in the future. Below, I’ve provided ready-to-run code examples in Go to help you structure your API call. It’s completely free to use, too — you’ll just need to register a free account on our website and use your free-tier API key to authenticate the service (free-tier API keys come with a limit of 800 API calls per month & no additional commitments).
Calling this API is super straightforward. All we need to do is copy & paste the code below into our file & include our file input/API key in their respective fields (indicated in the code comments). After that, you’re all done:
package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)func main() {url := "https://api.cloudmersive.com/convert/docx/to/rtf"
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))
}
Nice & easy. Please note that this operation will return the encoding for a new RTF file, and will not provide a fully-realized downloadable file.