How to Convert a Document to PDF Format using Go

There are dozens of unique file conversion services available through the Cloudmersive Document Conversion API endpoint. Some of these services are highly specific (for example, our DOCX to PDF conversion API), and some are intended for a more broadly focused use-case. In this article, I’ll demonstrate a free-to-use API solution which fits into the latter category.

Our Document to PDF API can automatically detect over 100 common file types (including Word, Excel, PowerPoint, HTML, and dozens of common image formats) and quickly & securely convert them to PDF format. To use this API, all you need to do is follow instructions below to structure your API call using Go code examples, and then authenticate the service with a free-tier Cloudmersive API key (visit our website to register a free account; this will yield a limit of 800 API calls per month with no additional commitments).

To call this API, all you need to do is copy the below code into your file, configure your API key & file input headers, and you’re all done:

package main

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

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))
}

The operation will return the encoding for your new PDF file, which can be used to generate your file elsewhere. That’s all there is to it!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cloudmersive

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