How to Convert a Word File to PDF in Go

Cloudmersive
2 min readMay 14, 2021

--

The Microsoft Word and PDF file types each have their own claims to fame; Word documents are easy to use, edit, and design, while PDF files provide high display fidelity in an easy to share and widely compatible format. When you need to share a contract or important document with a client, the PDF format is the clear winner, but the majority of documents are created in a different application. If the original document is a DOCX file, it can be a real pain to convert it to a PDF manually due to the complexity of the DOCX design. By integrating the following API in Go, you can automatically convert DOCX documents to PDF without the hassle of parsing the files.

To perform the conversion function, simply input the target DOCX file into the below code:

package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)
func main() {url := "https://api.cloudmersive.com/convert/docx/to/pdf"
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))
}

With this simple process, you will be able to seamlessly transform your Word docs into PDF files. To retrieve your API key, visit the Cloudmersive website to register for a free account; this will provide access to 800 monthly calls across all our APIs.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet