PDF Merge
Overview
Since v1.0.2gpdf can merge multiple PDF documents into one. You can combine entire documents or extract specific page ranges from each source.
Common use cases:
- Combining a cover page with generated content
- Merging invoices into a single bundle
- Extracting specific pages from a large document
- Assembling reports from multiple sources
Basic Merge
Use gpdf.Merge() to combine two or more PDFs:
import gpdf "github.com/gpdf-dev/gpdf"
cover, _ := os.ReadFile("cover.pdf")
body, _ := os.ReadFile("body.pdf")
merged, err := gpdf.Merge([]gpdf.Source{
{Data: cover},
{Data: body},
})
if err != nil {
log.Fatal(err)
}
os.WriteFile("output.pdf", merged, 0644)
Each Source contains raw PDF bytes. By default, all pages from each source are included.
Page Range Extraction
Use PageRange to include only specific pages from a source (1-based, inclusive):
full, _ := os.ReadFile("report.pdf")
// Extract pages 2 through 4
extracted, err := gpdf.Merge([]gpdf.Source{
{Data: full, Pages: gpdf.PageRange{From: 2, To: 4}},
})
PageRange rules:
From: 0or omitted — starts from the first pageTo: 0or omitted — goes through the last page- Zero value
PageRange{}— includes all pages
Setting Metadata
Use WithMergeMetadata to set document info on the merged output:
merged, err := gpdf.Merge(
[]gpdf.Source{
{Data: cover},
{Data: body},
{Data: appendix},
},
gpdf.WithMergeMetadata("Policy Bundle", "Example Ltd", "gpdf"),
)
Parameters: title, author, producer.
Merge + Overlay
Combine merge with overlay to add page numbers or watermarks after merging:
// Step 1: Merge documents
merged, _ := gpdf.Merge([]gpdf.Source{
{Data: cover},
{Data: body},
})
// Step 2: Open merged result and add page numbers
doc, _ := gpdf.Open(merged)
count, _ := doc.PageCount()
doc.EachPage(func(i int, p *template.PageBuilder) {
p.Absolute(document.Mm(170), document.Mm(285), func(c *template.ColBuilder) {
c.Text(fmt.Sprintf("%d / %d", i+1, count),
template.FontSize(10),
template.AlignRight(),
)
}, template.AbsoluteWidth(document.Mm(20)))
})
result, _ := doc.Save()
os.WriteFile("final.pdf", result, 0644)
API Reference
| Function / Type | Description |
|---|---|
gpdf.Merge(sources, opts...) | Merge multiple PDFs into one |
gpdf.Source | Input PDF: Data []byte + Pages PageRange |
gpdf.PageRange | 1-based inclusive range: From, To (0 = default) |
gpdf.WithMergeMetadata(title, author, producer) | Set document metadata on output |
Next Steps
- Existing PDF Overlay — Add content on top of existing PDFs
- Examples: Merge — More merge code examples
- API Reference — Full
gpdfpackage reference