---
title: "Getting started with onepdf for Go"
url: https://recursiveai.org/onepdf/go/docs/getting-started/
description: "Install the Go modules, lay out a PDF, extract its text and words, split and merge it, redact a word, sign and verify it, and convert it to PDF/A."
version: "1.0.1"
---

# Getting started with onepdf for Go

Install onepdf for Go, lay out a PDF, extract its text and words, split and merge it, redact a word, sign and verify it, and convert it to PDF/A.

onepdf for Go reads, repairs and decrypts PDFs, extracts their text, edits, signs and redacts them, converts them to PDF/A and PDF/UA, and lays out new ones, in pure Go with no cgo. It never runs document scripts and never touches the network. Every sample on this page was compiled and run with Go 1.26.8 against `recursiveai.org/go/onepdf` v1.0.1 and `recursiveai.org/go/onepdf/fonts` v1.0.1 from the Go module proxy; the output under each one is what it printed, and each PDF it wrote was checked with Poppler (`pdfinfo`, `pdftotext`, `pdfsig`).

## Install

onepdf needs Go 1.24 or newer.

```sh
mkdir pdf-start && cd pdf-start
go mod init example.com/pdf-start
go get recursiveai.org/go/onepdf@v1.0.1 recursiveai.org/go/onepdf/fonts@v1.0.1
```

`recursiveai.org/go/onepdf` is the library. It has no third-party dependencies: it needs only our `recursiveai.org/go/onefont` module, which uses only the Go standard library, and `go get` adds it. `recursiveai.org/go/onepdf/fonts` is a separate module with substitute fonts (Liberation, Noto Sans Math and Symbols, under the SIL Open Font License 1.1), for laying out text without a font file of your own and for drawing fonts a PDF does not embed. onepdf is MIT or Apache-2.0, at your choice.

Each sample is a complete `main.go` in its own folder (`go run ./write`, `go run ./extract`, …), and every sample after the first reads the `letter.pdf` the first one writes.

## Lay out a PDF

The `layout` package builds a document in code and writes a tagged PDF. `fonts.LayoutFonts()` gives it the Liberation faces, so no font file is needed.

```go
package main

import (
	"log"
	"os"

	"recursiveai.org/go/onepdf/fonts"
	"recursiveai.org/go/onepdf/layout"
)

// heading is a tagged heading in bold.
func heading(level int, s string, size float64) layout.Element {
	p := layout.NewParagraph(s)
	p.Style = layout.TextStyle{Size: size, Weight: 700}
	return layout.Heading{Level: level, Child: &layout.TextBlock{Paragraph: p}}
}

func main() {
	doc := &layout.Document{
		Fonts:        fonts.LayoutFonts(), // Liberation Sans, Serif and Mono
		DefaultStyle: layout.TextStyle{Size: 12},
		Sections: []*layout.Section{{
			Size:   layout.A4,
			Margin: layout.All(layout.Mm(20)),
			Content: &layout.Column{Items: []layout.Element{
				heading(1, "Letter", 20),
				layout.Spacer{H: 12},
				layout.Text("Account 1234 is secret."),
				layout.PageBreak{},
				heading(2, "Terms", 16),
				layout.Spacer{H: 12},
				layout.Text("Payment is due in 30 days."),
			}},
		}},
	}
	f, err := os.Create("letter.pdf")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	if _, err := doc.WritePDF(f, layout.WithTitle("Letter"), layout.WithLanguage("en")); err != nil {
		log.Fatal(err)
	}
}
```

It prints nothing and writes `letter.pdf`. `pdfinfo letter.pdf` reports `Title: Letter`, `Tagged: yes`, `Pages: 2`, `Page size: 595.276 x 841.89 pts (A4)` and `PDF version: 1.7`.

## Extract text

`text.Plain` returns the text of every page in reading order. `onepdf.OpenBytes` opens a byte slice and `onepdf.Open` an `io.ReaderAt`.

```go
package main

import (
	"fmt"
	"log"

	"recursiveai.org/go/onepdf"
	"recursiveai.org/go/onepdf/text"
)

func main() {
	doc, err := onepdf.OpenFile("letter.pdf")
	if err != nil {
		log.Fatal(err)
	}
	// Reading order; text.Extract gives words, lines and blocks.
	s, err := text.Plain(doc)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(s)
}
```

```text
Letter

Account 1234 is secret.

Terms

Payment is due in 30 days.
```

## Words with positions

`text.Extract` returns each page as blocks, lines and words, each with its bounds in PDF points from the bottom-left corner of the page.

```go
package main

import (
	"fmt"
	"log"

	"recursiveai.org/go/onepdf"
	"recursiveai.org/go/onepdf/text"
)

func main() {
	doc, err := onepdf.OpenFile("letter.pdf")
	if err != nil {
		log.Fatal(err)
	}
	pages, err := text.Extract(doc)
	if err != nil {
		log.Fatal(err)
	}
	for i, p := range pages {
		for w := range p.Words() {
			b := w.Bounds
			fmt.Printf("page %d  %-9s x %6.1f  y %6.1f\n", i+1, w.Text, b.X0, b.Y0)
		}
	}
}
```

```text
page 1  Letter    x   56.7  y  762.3
page 1  Account   x   56.7  y  735.4
page 1  1234      x  103.4  y  735.4
page 1  is        x  133.4  y  735.4
page 1  secret.   x  145.4  y  735.4
page 2  Terms     x   56.7  y  766.8
page 2  Payment   x   56.7  y  740.2
page 2  is        x  107.4  y  740.2
page 2  due       x  119.4  y  740.2
page 2  in        x  142.7  y  740.2
page 2  30        x  155.4  y  740.2
page 2  days.     x  172.1  y  740.2
```

## Split and merge

`onepdf.Split` makes one document per page range and `onepdf.Merge` joins documents, keeping outlines, links and form fields.

```go
package main

import (
	"fmt"
	"log"

	"recursiveai.org/go/onepdf"
)

func main() {
	doc, err := onepdf.OpenFile("letter.pdf")
	if err != nil {
		log.Fatal(err)
	}
	// One document per page range: Start is zero-based.
	parts, err := onepdf.Split(doc, onepdf.PageRange{Start: 0, Count: 1}, onepdf.PageRange{Start: 1, Count: 1})
	if err != nil {
		log.Fatal(err)
	}
	for i, p := range parts {
		name := fmt.Sprintf("part-%d.pdf", i+1)
		if err := p.SaveFile(name); err != nil {
			log.Fatal(err)
		}
		fmt.Println(name, p.PageCount(), "page")
	}

	// Back together, second part first.
	merged, err := onepdf.Merge([]*onepdf.Document{parts[1], parts[0]})
	if err != nil {
		log.Fatal(err)
	}
	if err := merged.SetInfo("Title", "Merged"); err != nil {
		log.Fatal(err)
	}
	if err := merged.SaveFile("merged.pdf"); err != nil {
		log.Fatal(err)
	}
	fmt.Println("merged.pdf", merged.PageCount(), "pages")
}
```

```text
part-1.pdf 1 page
part-2.pdf 1 page
merged.pdf 2 pages
```

`pdftotext merged.pdf` reads “Terms” before “Letter”.

## Redact a word

`redact.Apply` removes the text, vector paths and image pixels under each area for good, not just covers them. A document must be opened with `onepdf.WithEditing()` to change it.

```go
package main

import (
	"fmt"
	"log"

	"recursiveai.org/go/onepdf"
	"recursiveai.org/go/onepdf/redact"
	"recursiveai.org/go/onepdf/text"
)

func main() {
	doc, err := onepdf.OpenFile("letter.pdf", onepdf.WithEditing())
	if err != nil {
		log.Fatal(err)
	}
	// Find the account number and redact the area under it.
	pages, err := text.Extract(doc)
	if err != nil {
		log.Fatal(err)
	}
	var regions []redact.Region
	for i, p := range pages {
		for w := range p.Words() {
			if w.Text == "1234" {
				regions = append(regions, redact.Region{Page: i, Rect: w.Bounds})
			}
		}
	}
	res, err := redact.Apply(doc, regions)
	if err != nil {
		log.Fatal(err)
	}
	if err := doc.SaveFile("redacted.pdf"); err != nil {
		log.Fatal(err)
	}
	fmt.Println("glyphs removed:", res.GlyphsRemoved)
}
```

```text
glyphs removed: 4
```

`pdftotext redacted.pdf` gives “Account” and “is secret.” with nothing between them.

## Sign and verify

`sign.Sign` writes a PAdES signature with your certificate and its RSA or ECDSA key. `sign.Verify` checks it against the trust anchors you pass and never downloads anything.

```go
package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"fmt"
	"log"
	"math/big"
	"os"
	"time"

	"recursiveai.org/go/onepdf"
	"recursiveai.org/go/onepdf/sign"
)

func main() {
	// A self-signed certificate stands in for your own.
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		log.Fatal(err)
	}
	tmpl := &x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject:      pkix.Name{CommonName: "Ada Lovelace"},
		NotBefore:    time.Now().Add(-time.Hour),
		NotAfter:     time.Now().Add(24 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
	if err != nil {
		log.Fatal(err)
	}
	cert, _ := x509.ParseCertificate(der)
	cred, err := sign.NewCredential(cert, key)
	if err != nil {
		log.Fatal(err)
	}

	doc, err := onepdf.OpenFile("letter.pdf", onepdf.WithEditing())
	if err != nil {
		log.Fatal(err)
	}
	out, err := os.Create("signed.pdf")
	if err != nil {
		log.Fatal(err)
	}
	if _, err := sign.Sign(doc, out, cred, sign.WithReason("I approve")); err != nil {
		log.Fatal(err)
	}
	out.Close()

	signed, err := onepdf.OpenFile("signed.pdf")
	if err != nil {
		log.Fatal(err)
	}
	report, err := sign.Verify(signed, sign.WithTrustAnchors(cert))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(report.Summary())
	fmt.Println("valid:", report.Signatures[0].IsValid)
}
```

```text
1 signature: 1 valid, 0 not valid
valid: true
```

`pdfsig signed.pdf` reports `Signature Validation: Signature is Valid.`

## Convert to PDF/A

`pdfa.ConvertFile` writes a PDF/A-2b copy and lists what it changed. A file that cannot be converted fails with every reason.

```go
package main

import (
	"context"
	"fmt"
	"log"

	"recursiveai.org/go/onepdf/pdfa"
)

func main() {
	res, err := pdfa.ConvertFile(context.Background(), "letter-pdfa.pdf", "letter.pdf")
	if err != nil {
		log.Fatal(err) // a file that cannot be converted fails with every reason
	}
	fmt.Println(res.Profile)
	for _, c := range res.Changes {
		fmt.Println("-", c.Description)
	}
}
```

```text
PDF/A-2b
- an output intent with a generated RGB profile was added
- the XMP metadata was written from the information dictionary
```

## Next

- [Overview](https://recursiveai.org/onepdf/go/docs/overview/): every package, the README examples, how fonts are found, and performance.
- [Substitute fonts](https://recursiveai.org/onepdf/go/docs/fonts/): the fonts module.
- [API reference on pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onepdf).
