How to Split a Single DOCX Document into Separate Documents (By Page) Using Go
Combining and splitting documents programmatically can save a lot of manual document administration work. Thankfully, via the Cloudmersive Document Conversion API endpoint, it’s easy to build either of those operations into your application as independent API services.
For instance, using only the code examples provided below (and a free-tier Cloudmersive API key, obtainable on our website), you can build our Split DOCX API iteration into your application, securing control a useful, scalable document management service for the long haul. As the title suggests, this API will divide a multi-page input document into a series of new DOCX documents (one per page of the original) and return the encoding for each one (labeled as “DocumentContents” in response body).
To structure your API call, simply add the below code examples to your file, supply your API key & DOCX file path in their respective fields, 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/split/docx"
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("returnDocumentContents", "<boolean>")
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))
}