How to Easily Convert Documents to PDF in Go

Cloudmersive
2 min readJun 3, 2024

--

Converting documents to PDF is as boring as it is necessary. With one solution to convert multiple formats to PDF, we can save a lot of time.

Using the below code, we can call a free API in our Go application that autodetects input file formats (via the file extension) and converts those files to PDF. We can use this for all major Office formats (DOCX, XLSX, PPTX, etc.), over 100 image formats, and even HTML files.

Our request will return our PDF file encoding string, and we can simply write that string to a new PDF file in a location of our choosing. With ready-to-run code examples to work with, the hard part is already taken care of, and we can focus our attention on more pressing aspects of our Go projects.

To begin structuring our API call, let’s first declare the package our Go file belongs to & import the necessary packages:

package main

import (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)

Next, let’s use the below examples to call our conversion function. We’ll perform a POST request to the endpoint URL string in url : with our uploaded file (note that requests are performed in-memory, and memory is dumped upon task completion):

func main() {

url := "https://api.cloudmersive.com/convert/autodetect/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))
}

To authorize our API calls, we’ll need to get a free Cloudmersive API key (this allows up to 800 API calls per month with no additional commitments) and replace the “YOUR-API-KEY-HERE” string in the appropriate request header.

Errors will print to our console via if err !. If we want to improve error handling in our own app, we can choose to return errors to the caller, log errors for debugging, or even pass errors up the call stack.

--

--

Cloudmersive

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