Guide · Go
Merge PDFs and add a password in Go
An invoice, the terms and a data sheet should reach the customer as one file, and it should not be readable by anyone who finds it. This Go program joins documents you already rendered and encrypts the result, in two calls and without a PDF library.
Free plan with 100 units a month, no credit card
What you need
- An API key. Create one in the app under API keys and export it as
FORMFEED_API_KEY. A test key (ff_test_…) is right for trying things out. See the quick start. - Go. You need Go 1.21 or newer; the program uses the standard library only.
- The sources.
sources.jsonnext to the program: a JSON array of what goes into the document, in order. A render id (rnd_…) or the name of a PDF in the workspace library, two to fifty of them. - A password. In
FORMFEED_PDF_PASSWORD. Generate one per document and send it through a different channel than the file. - A plan with PDF tools. The tools are part of Starter and above.
The program
The program reads the sources, merges them into one PDF, encrypts that result with the password and saves the finished file.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
type render struct {
ID string `json:"id"`
DownloadURL string `json:"download_url"`
PageCount int `json:"page_count"`
Units float64 `json:"units"`
Title string `json:"title"`
Detail string `json:"detail"`
}
func api(path string, body any) render {
encoded, _ := json.Marshal(body)
request, _ := http.NewRequest("POST", "https://api-eu.formfeed.dev/v1"+path, bytes.NewReader(encoded))
request.Header.Set("Authorization", "Bearer "+os.Getenv("FORMFEED_API_KEY"))
request.Header.Set("Content-Type", "application/json")
response, err := http.DefaultClient.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
var answer render
json.NewDecoder(response.Body).Decode(&answer)
if response.StatusCode >= 400 {
fmt.Fprintf(os.Stderr, "%s: %s\n", answer.Title, answer.Detail)
os.Exit(1)
}
return answer
}
func main() {
file, err := os.ReadFile("sources.json")
if err != nil {
panic(err)
}
var sources []string
json.Unmarshal(file, &sources)
// 1. join the documents, in the order they are given
merged := api("/pdf/merge", map[string]any{"sources": sources, "filename": "bundle.pdf"})
// 2. encrypt the result; printing stays allowed, copying and editing do not
protected := api("/pdf/protect", map[string]any{
"source": merged.ID,
"user_password": os.Getenv("FORMFEED_PDF_PASSWORD"),
"permissions": []string{"print"},
})
answer, err := http.Get(protected.DownloadURL)
if err != nil {
panic(err)
}
defer answer.Body.Close()
out, _ := os.Create("bundle.pdf")
defer out.Close()
io.Copy(out, answer.Body)
fmt.Printf("%s %d page(s), %v unit(s)\n", protected.ID, protected.PageCount, protected.Units)
}Run it
It prints the render’s id, the page count and the units, and bundle.pdf lies next to the program. Opening it asks for the password; printing works, copying text does not.
export FORMFEED_API_KEY=ff_test_...
export FORMFEED_PDF_PASSWORD=$(openssl rand -base64 18)
go run main.goWhat is particular about Go
json.RawMessage. The sample data goes into the body as it is on disk, without being decoded into Go types first, so the program works for any template.- One struct for both answers. A render and a problem document are both JSON objects, so a single struct with
titleanddetailbeside the render fields decodes either. - Timeouts.
http.DefaultClienthas none. In a service, give the client aTimeouta little above 60 seconds: a synchronous render answers when the file is done, or after 60 seconds with202while it goes on in the background.
Why two calls
- Order matters. An encrypted PDF cannot be changed any more, so the password comes last. Merging an already protected document fails.
- Every step is a render. Merge and protect each produce a render of their own with an id, a download URL and a line in the render log; the second takes the first’s id as its source.
- Half a unit each. A tool costs 0.5 units on a live key, whatever the page count. The renders that produced the sources were counted when they ran.
- Or in one request. A render can carry the same steps as
postand do everything in one call. Use the tools when the documents already exist, andpostwhen you are rendering anyway. See PDF tools.
What the permissions do
Everything not listed in permissions is forbidden (leave the list out and all four of print, copy, modify and annotate are allowed): with ["print"] a reader may print but not copy text, edit or annotate. Without a user_password anyone can open the document and the permissions still apply, which is the right setting for a document that is public but should not be edited. An owner_password lifts the restrictions; a random one is used when you send none. PDF viewers honour the permissions, but they are no protection against someone who can open the file: confidentiality comes from the user_password.
When the API says no
- One shape for every error. Errors are problem documents (RFC 9457) with
type,title,status,detail, a stablecodeand therequest_idto quote to support; thetypeURL leads to a page about that error. The list is in the error reference. - The usual ones.
401 unauthorizedfor a missing or revoked key,404 template_not_foundfor a wrong template name,422 template_runtime_errorwhen the template fails on the data,429 rate_limitedabove the plan’s requests per second,402 quota_exceededwhen the Free plan’s units are used up (a paid plan bills extra units up to its hard cap). - Retry safely. Send an
Idempotency-Keyheader with the POST, and repeat the request with the same key when you do not know whether the first attempt arrived: for 24 hours the key returns the first answer instead of rendering and billing again. The answer is stored once the first attempt has been answered, so do not retry while it may still run; and problems below 500 are stored too, so a corrected request needs a new key.
The job around this program
This guide is one program. What the job needs around it, from the template to the limits and the price, is on the page Contract and agreement PDFs.
More Go guides
FAQ
- Where do the render ids come from?
- From the renders you made earlier: the
idof every answer. They must belong to the same workspace and their output must still exist. Files you uploaded to the library are named instead. - Which encryption is used?
- AES-256, done by qpdf. The password never appears in the render log, and it is not stored: lose it and the document cannot be opened.
- Can I watermark as well?
- Yes,
/pdf/watermarkis the third tool and takes a text or an image. Chain it before the password, like the merge. See PDF tools.