How to Convert an Excel XLSX Spreadsheet to PDF using Go
PDFs are beyond ubiquitous and need little introduction. However, it’s always worth noting just how effective this format is when it comes to storing, sharing, and presenting multi-faceted content across platforms. Exporting your Excel Spreadsheet as a PDF is a no-brainer when you want to maintain the integrity of your document, as it affords a stable viewing portal for downstream viewers while ensuring that those same users can’t make changes to your data. The question is, how can you take control of this conversion process at scale, to avoid manually exporting a multitude of spreadsheets one by one?
Our XLSX to PDF API is an effective solution for that problem. Using the ready-to-run, copy & paste code examples provided below in Go, you can incorporate this API into your application with zero hassle and put your conversion needs to rest. This API will simply return the encoding for a new PDF file; one for each worksheet in your input workbook (and it supports both XLSX and XLSB Excel formats). All you’ll need to complete your API call is a Cloudmersive API key, which you can get by registering a free account on our website.
Calling this API in Go is a simple, one-step process. Just copy the below code into your file, configure your file path & API key fields, and call the function:
package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)func main() {url := "https://api.cloudmersive.com/convert/xlsx/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))
}
After that, you’re all set. Nice & straightforward!