Go Templates
Visao Geral
gpdf integra-se com o pacote text/template do Go para geracao de conteudo dinamico. Os templates produzem saida em JSON schema que o gpdf renderiza como PDF.
Duas abordagens estao disponiveis:
- FromJSON — Expressoes Go template inline no JSON (mais simples)
- FromTemplate — Go template pre-analisado para controle total (flexivel)
FromJSON com Expressoes de Template
A abordagem mais simples — incorpore expressoes Go template diretamente no JSON:
schema := []byte(`{
"page": {"size": "A4", "margins": "20mm"},
"metadata": {"title": "{{.Title}}"},
"body": [
{"row": {"cols": [
{"span": 12, "text": "{{.Title}}", "style": {"size": 24, "bold": true}}
]}},
{"row": {"cols": [
{"span": 12, "text": "Author: {{.Author}}"}
]}}
]
}`)
doc, err := template.FromJSON(schema, map[string]any{
"Title": "Monthly Report",
"Author": "ACME Corp",
})
FromTemplate com Templates Pre-Analisados
Para logica complexa como loops e condicionais, use FromTemplate:
import (
gotemplate "text/template"
"github.com/gpdf-dev/gpdf/template"
)
tmplStr := `{
"page": {"size": "A4", "margins": "20mm"},
"metadata": {"title": "{{.Title}}"},
"body": [
{"row": {"cols": [
{"span": 12, "text": "{{.Title}}", "style": {"size": 24, "bold": true}}
]}},
{"row": {"cols": [
{"span": 12, "spacer": "5mm"}
]}},
{{- range $i, $section := .Sections}}
{{- if $i}},{{end}}
{"row": {"cols": [
{"span": 12, "elements": [
{"type": "text", "content": "{{$section.Heading}}", "style": {"size": 16, "bold": true, "color": "#1A237E"}},
{"type": "spacer", "height": "3mm"},
{"type": "text", "content": "{{$section.Body}}"},
{"type": "spacer", "height": "8mm"}
]}
]}}
{{- end}}
]
}`
tmpl, err := gotemplate.New("report").Funcs(template.TemplateFuncMap()).Parse(tmplStr)
if err != nil {
log.Fatal(err)
}
type section struct {
Heading string
Body string
}
data := map[string]any{
"Title": "Quarterly Report - Q1 2026",
"Sections": []section{
{
Heading: "Executive Summary",
Body: "Revenue increased 25% year-over-year, driven by new enterprise offerings.",
},
{
Heading: "Product Development",
Body: "The gpdf library reached v0.8 with JSON schema and Go template support.",
},
{
Heading: "Market Analysis",
Body: "PDF generation market grows. Zero-dependency approach resonates with Go devs.",
},
{
Heading: "Next Steps",
Body: "Focus on reusable components, fuzz testing, and v1.0 release.",
},
},
}
doc, err := template.FromTemplate(tmpl, data)
if err != nil {
log.Fatal(err)
}
pdfData, err := doc.Generate()
┌─ A4 ──────────────────────────────────────────────┐
│ │
│ Quarterly Report - Q1 2026 ← 24pt bold │
│ │
│ Executive Summary ← 16pt bold blue │
│ Revenue increased 25% year-over-year, driven │
│ by new enterprise offerings. │
│ │
│ Product Development │
│ The gpdf library reached v0.8 with JSON schema │
│ and Go template support. │
│ │
│ Market Analysis │
│ PDF generation market grows. Zero-dependency │
│ approach resonates with Go devs. │
│ │
│ Next Steps │
│ Focus on reusable components, fuzz testing, │
│ and v1.0 release. │
│ │
└───────────────────────────────────────────────────┘
Mapa de Funcoes de Template
Use TemplateFuncMap() ao analisar templates — ele fornece funcoes auxiliares:
tmpl, err := gotemplate.New("doc").Funcs(template.TemplateFuncMap()).Parse(tmplStr)
Funcoes Disponiveis
| Funcao | Descricao |
|---|---|
toJSON | Converte um valor Go para string JSON (util para incorporar dados) |
Secoes Dinamicas com Range
Itere sobre dados para gerar secoes repetidas:
{{- range $i, $item := .Items}}
{{- if $i}},{{end}}
{"row": {"cols": [
{"span": 6, "text": "{{$item.Name}}"},
{"span": 6, "text": "{{$item.Value}}", "style": {"align": "right"}}
]}}
{{- end}}
Condicionais
Use if para conteudo condicional:
{{- if .ShowHeader}}
{"row": {"cols": [
{"span": 12, "text": "{{.HeaderText}}", "style": {"size": 20, "bold": true}}
]}},
{{- end}}
Dicas
- Use
{{-e-}}para remover espacos em branco ao redor de acoes de template - Trate virgulas JSON com cuidado em loops
range(use{{if $i}},{{end}}) - Use
TemplateFuncMap()para obter funcoes auxiliares integradas - Opcoes Go (
WithFont,WithMargins, etc.) podem sobrescrever configuracoes do template:
doc, err := template.FromTemplate(tmpl, data,
template.WithFont("NotoSansJP", fontData),
template.WithDefaultFont("NotoSansJP", 12),
)