How to Split a PDF File into Separate PDF Documents (One per Page) using Go
Please skip to the bottom of this article for direct access to the API demonstration.
Not every PDF document you receive is necessarily intended to be viewed as a coherent sum of its parts. Often, these documents are hastily stitched together to consolidate the number of files a downstream stakeholder needs to open to explore the various dimensions of a single subject. In short, each page may contain a completely unrelated subject to the one that came before or after it. As such, splitting PDF documents becomes as relevant a task as merging them in the first place, and thankfully, there’s another API for that.
With our Split PDF Document API, you can separate each page from a consolidated PDF file into its own independent document with only a single API call. The encoding for each new file will be returned (labeled “DocumentContents” within the response body) and can be used to subsequently generate a series of new PDF documents. For larger scale operations (PDFs with many pages), you can also elect to return your PDF contents only as temporary URLs by setting the returnDocumentContents field to “true” (default is “false”).
To take advantage of this API for free, all you need to do is register a free account on our website (this provides an API key with a limit of 800 API calls per month) and copy the below code examples into your file to structure your API call. The below code examples are supplied in Go; however, you may alternatively visit our API console page to find examples in several other common programming languages, including Java, Python, C#, and more.
Simply copy the below code into your environment, then include your API key & parse your file path in the appropriate fields, and you’re good to go:
package main
import (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)
func main() {
url := "https://api.cloudmersive.com/convert/split/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("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))
}