Elementos

Texto

O elemento mais fundamental. Adicione texto com estilizacao opcional:

c.Text("Hello, World!")
c.Text("Styled text", template.FontSize(18), template.Bold())
c.Text("Red centered", template.TextColor(pdf.Red), template.AlignCenter())

Opcoes de Texto

OpcaoDescricao
FontSize(size)Tamanho da fonte em pontos (padrao: 12)
Bold()Peso negrito
Italic()Estilo italico
FontFamily(name)Usar uma fonte registrada
TextColor(color)Cor do primeiro plano
BgColor(color)Cor de fundo
AlignLeft()Alinhamento a esquerda (padrao)
AlignCenter()Alinhamento centralizado
AlignRight()Alinhamento a direita
Underline()Decoracao sublinhado
Strikethrough()Decoracao tachado
LetterSpacing(pts)Espaco extra entre caracteres
TextIndent(value)Recuo da primeira linha

Rich Text

Texto inline com estilos mistos usando RichText():

c.RichText(func(rt *template.RichTextBuilder) {
    rt.Span("Normal text ")
    rt.Span("bold", template.Bold())
    rt.Span(" and ")
    rt.Span("red", template.TextColor(pdf.Red))
    rt.Span(" in one line.")
})
┌─────────────────────────────────────────────┐
│  Normal text bold and red in one line.      │
│              ^^^^     ^^^                   │
│              bold     red color             │
└─────────────────────────────────────────────┘

Tabela

Tabelas com cabecalhos e linhas de dados:

// Basic table
c.Table(
    []string{"Name", "Age", "City"},
    [][]string{
        {"Alice", "30", "Tokyo"},
        {"Bob", "25", "New York"},
        {"Charlie", "35", "London"},
    },
)
┌──────────┬──────┬──────────┐
│  Name    │ Age  │  City    │ ← cabecalho (negrito)
├──────────┼──────┼──────────┤
│  Alice   │  30  │  Tokyo   │
│  Bob     │  25  │  New York│
│  Charlie │  35  │  London  │
└──────────┴──────┴──────────┘

Tabela Estilizada

darkBlue := pdf.RGBHex(0x1A237E)
lightGray := pdf.RGBHex(0xF5F5F5)

c.Table(
    []string{"Product", "Category", "Qty", "Unit Price", "Total"},
    [][]string{
        {"Laptop Pro 15", "Electronics", "2", "$1,299.00", "$2,598.00"},
        {"Wireless Mouse", "Accessories", "10", "$29.99", "$299.90"},
        {"USB-C Hub", "Accessories", "5", "$49.99", "$249.95"},
        {"Monitor 27\"", "Electronics", "3", "$399.00", "$1,197.00"},
        {"Keyboard", "Accessories", "10", "$79.99", "$799.90"},
        {"Webcam HD", "Electronics", "4", "$89.99", "$359.96"},
    },
    template.ColumnWidths(30, 20, 10, 20, 20),
    template.TableHeaderStyle(
        template.TextColor(pdf.White),
        template.BgColor(darkBlue),
    ),
    template.TableStripe(lightGray),
)
┌─────────────┬────────────┬─────┬───────────┬──────────┐
│  Product    │  Category  │ Qty │Unit Price │  Total   │ ← branco sobre azul escuro
├─────────────┼────────────┼─────┼───────────┼──────────┤
│  Laptop Pro │ Electronics│  2  │ $1,299.00 │$2,598.00 │ ← fundo branco
│  Wireless.. │ Accessories│ 10  │    $29.99 │  $299.90 │ ← listras cinza
│  USB-C Hub  │ Accessories│  5  │    $49.99 │  $249.95 │ ← fundo branco
│  Monitor 27"│ Electronics│  3  │   $399.00 │$1,197.00 │ ← listras cinza
│  Keyboard   │ Accessories│ 10  │    $79.99 │  $799.90 │ ← fundo branco
│  Webcam HD  │ Electronics│  4  │    $89.99 │  $359.96 │ ← listras cinza
└─────────────┴────────────┴─────┴───────────┴──────────┘

Opcoes de Tabela

OpcaoDescricao
ColumnWidths(widths...)Porcentagens de largura das colunas (deve somar 100)
TableHeaderStyle(opts...)Estilo para a linha de cabecalho
TableStripe(color)Cor de fundo alternada nas linhas
TableCellVAlign(align)Alinhamento vertical: VAlignTop, VAlignMiddle, VAlignBottom

Alinhamento Vertical de Tabela

c.Table(
    []string{"Align", "Short", "Long Content"},
    [][]string{
        {"Top", "A", "This is a longer text that wraps to multiple lines"},
        {"Middle", "B", "Another longer text for demonstration purposes"},
    },
    template.TableCellVAlign(document.VAlignMiddle),
)

Imagem

Adicione imagens JPEG ou PNG:

imgData, _ := os.ReadFile("photo.jpg")

c.Image(imgData)
c.Image(imgData, template.FitWidth(document.Mm(80)))
c.Image(imgData, template.FitHeight(document.Mm(50)))

Opcoes de Imagem

OpcaoDescricao
FitWidth(value)Escalar para a largura especificada
FitHeight(value)Escalar para a altura especificada
WithFitMode(mode)Modo de ajuste: FitContain, FitCover, FitStretch, FitOriginal
WithAlign(align)Alinhamento horizontal: AlignLeft, AlignCenter, AlignRight

Modos de Ajuste de Imagem

// Contain: scale to fit, preserve aspect ratio (default)
c.Image(data, template.WithFitMode(document.FitContain))

// Cover: scale to fill, may crop
c.Image(data, template.WithFitMode(document.FitCover))

// Stretch: fill bounds, may distort
c.Image(data, template.WithFitMode(document.FitStretch))

// Original: use original dimensions
c.Image(data, template.WithFitMode(document.FitOriginal))

Alinhamento de Imagem

c.Image(data, template.FitWidth(document.Mm(40)), template.WithAlign(document.AlignCenter))
c.Image(data, template.FitWidth(document.Mm(40)), template.WithAlign(document.AlignRight))

Lista

Lista Nao Ordenada

c.List([]string{
    "Declarative document definition",
    "All element types supported",
    "Style options (bold, italic, color, align)",
    "Header and footer support",
})
┌─────────────────────────────────────────────┐
│  • Declarative document definition          │
│  • All element types supported              │
│  • Style options (bold, italic, color, ...)  │
│  • Header and footer support                │
└─────────────────────────────────────────────┘

Lista Ordenada

c.OrderedList([]string{
    "Text with styles",
    "Tables with headers",
    "Lists (ordered/unordered)",
    "Lines and spacers",
    "QR codes and barcodes",
})
┌─────────────────────────────────────────────┐
│  1. Text with styles                        │
│  2. Tables with headers                     │
│  3. Lists (ordered/unordered)               │
│  4. Lines and spacers                       │
│  5. QR codes and barcodes                   │
└─────────────────────────────────────────────┘

Opcoes de Lista

OpcaoDescricao
ListIndent(value)Recuo a partir da esquerda

Linha

Linhas horizontais com cor e espessura opcionais:

// Default line (gray, 1pt)
c.Line()

// Colored line
c.Line(template.LineColor(pdf.Red))
c.Line(template.LineColor(pdf.Blue))

// Custom thickness
c.Line(template.LineThickness(document.Pt(0.5)))   // thin
c.Line(template.LineThickness(document.Pt(2)))     // medium
c.Line(template.LineThickness(document.Pt(5)))     // thick

// Color + thickness
c.Line(
    template.LineColor(pdf.RGBHex(0x1A237E)),
    template.LineThickness(document.Pt(2)),
)
┌─────────────────────────────────────────────┐
│  Default line:                              │
│  ─────────────────────────────── (gray 1pt) │
│  Red line:                                  │
│  ─────────────────────────────── (red)      │
│  Thin (0.5pt):                              │
│  ─────────────────────────────── (thin)     │
│  Thick (5pt):                               │
│  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ (thick)    │
└─────────────────────────────────────────────┘

Opcoes de Linha

OpcaoDescricao
LineColor(color)Cor da linha
LineThickness(value)Espessura da linha

Espacador

Adicione espaco vertical entre elementos:

c.Text("Before spacer")
c.Spacer(document.Mm(10))    // 10mm gap
c.Text("After spacer")

c.Spacer(document.Mm(5))     // 5mm
c.Spacer(document.Mm(15))    // 15mm
c.Spacer(document.Mm(30))    // 30mm
┌─────────────────────────────────────────────┐
│  Before spacer                              │
│                                             │
│                  ↕ 10mm                     │
│                                             │
│  After spacer                               │
└─────────────────────────────────────────────┘

QR Code

Gere QR codes a partir de texto ou URLs:

// Basic QR code
c.QRCode("https://gpdf.dev")

// With custom size
c.QRCode("https://gpdf.dev", template.QRSize(document.Mm(30)))

// With error correction level
c.QRCode("HELLO", template.QRSize(document.Mm(25)),
    template.QRErrorCorrection(qrcode.LevelH))

// Japanese content
c.QRCode("こんにちは世界", template.QRSize(document.Mm(30)))

QR Codes com Tamanhos Diferentes

page.AutoRow(func(r *template.RowBuilder) {
    r.Col(4, func(c *template.ColBuilder) {
        c.Text("20mm", template.FontSize(9))
        c.QRCode("https://gpdf.dev", template.QRSize(document.Mm(20)))
    })
    r.Col(4, func(c *template.ColBuilder) {
        c.Text("30mm", template.FontSize(9))
        c.QRCode("https://gpdf.dev", template.QRSize(document.Mm(30)))
    })
    r.Col(4, func(c *template.ColBuilder) {
        c.Text("40mm", template.FontSize(9))
        c.QRCode("https://gpdf.dev", template.QRSize(document.Mm(40)))
    })
})
┌───────────────┬───────────────┬───────────────┐
│  20mm         │  30mm         │  40mm         │
│  ┌──┐         │  ┌────┐       │  ┌──────┐     │
│  │QR│         │  │ QR │       │  │  QR  │     │
│  └──┘         │  └────┘       │  │      │     │
│               │               │  └──────┘     │
└───────────────┴───────────────┴───────────────┘

Niveis de Correcao de Erro

NivelRecuperacaoMelhor Para
qrcode.LevelL~7%Ambientes limpos
qrcode.LevelM~15%Uso geral (padrao)
qrcode.LevelQ~25%Uso industrial
qrcode.LevelH~30%Ambientes adversos
import "github.com/gpdf-dev/gpdf/qrcode"

c.QRCode("HELLO", template.QRErrorCorrection(qrcode.LevelH))

Opcoes de QR Code

OpcaoDescricao
QRSize(value)Tamanho de exibicao (largura = altura)
QRErrorCorrection(level)Nivel de correcao de erro
QRScale(s)Pixels por modulo QR

Codigo de Barras

Gere codigos de barras Code 128:

// Basic barcode
c.Barcode("INV-2026-0001")

// With custom width
c.Barcode("PRODUCT-A-12345", template.BarcodeWidth(document.Mm(80)))

// With custom height
c.Barcode("SMALL-BAR", template.BarcodeHeight(document.Mm(10)))

// Numeric data (automatically optimized with Code C)
c.Barcode("1234567890")

Codigos de Barras em Colunas

page.AutoRow(func(r *template.RowBuilder) {
    r.Col(6, func(c *template.ColBuilder) {
        c.Text("Item A", template.FontSize(9))
        c.Barcode("ITEM-A-001", template.BarcodeWidth(document.Mm(60)))
    })
    r.Col(6, func(c *template.ColBuilder) {
        c.Text("Item B", template.FontSize(9))
        c.Barcode("ITEM-B-002", template.BarcodeWidth(document.Mm(60)))
    })
})
┌────────────────────────┬────────────────────────┐
│  Item A                │  Item B                │
│  ║║│║║│║║║│║║│║║│      │  ║║│║║│║║║│║║│║║│      │
│  ITEM-A-001            │  ITEM-B-002            │
└────────────────────────┴────────────────────────┘

Opcoes de Codigo de Barras

OpcaoDescricao
BarcodeWidth(value)Largura de exibicao
BarcodeHeight(value)Altura de exibicao
BarcodeFormat(format)Formato do codigo de barras (padrao: Code 128)

Posicionamento Absoluto

Coloque elementos em coordenadas XY exatas na pagina, fora do fluxo normal do grid. Util para marcas d'agua, carimbos, logos e overlays.

page.Absolute(document.Mm(120), document.Mm(20), func(c *template.ColBuilder) {
    c.Text("CONFIDENTIAL", template.FontSize(20), template.Bold(), template.TextColor(pdf.Red))
})

// With explicit size
page.Absolute(document.Mm(10), document.Mm(250), func(c *template.ColBuilder) {
    c.QRCode("https://gpdf.dev", template.QRSize(document.Mm(20)))
}, gpdf.AbsoluteWidth(document.Mm(25)), gpdf.AbsoluteHeight(document.Mm(25)))

// Use page corner as origin (ignores margins)
page.Absolute(document.Mm(0), document.Mm(0), func(c *template.ColBuilder) {
    c.Text("Top-left corner of page")
}, gpdf.AbsoluteOriginPage())
┌─ Page ──────────────────────────────────────────┐
│  ┌─ Content Area ───────────────────────────┐   │
│  │                                          │   │
│  │   [Normal flow content]                  │   │
│  │                                          │   │
│  │              ┌──────────────┐            │   │
│  │              │ CONFIDENTIAL │ ← absolute │   │
│  │              └──────────────┘   (120,20) │   │
│  │                                          │   │
│  │   ┌──┐                                   │   │
│  │   │QR│ ← absolute (10,250)               │   │
│  │   └──┘                                   │   │
│  └──────────────────────────────────────────┘   │
└─────────────────────────────────────────────────┘

Origens de Coordenadas

OrigemDescricaoPadrao
Area de ConteudoXY relativo ao canto superior esquerdo da area de conteudo (dentro das margens)Sim
PaginaXY relativo ao canto superior esquerdo da pagina (ignora margens)Nao

Opcoes de Posicionamento Absoluto

OpcaoDescricao
AbsoluteWidth(value)Largura explicita para o bloco absoluto
AbsoluteHeight(value)Altura explicita para o bloco absoluto
AbsoluteOriginPage()Usar canto da pagina como origem em vez da area de conteudo

Numero de Pagina / Total de Paginas

Numeracao automatica de paginas em cabecalhos ou rodapes:

// Current page number (e.g., "1", "2", "3")
c.PageNumber(template.AlignRight(), template.FontSize(8))

// Total page count (e.g., "4 total pages")
c.TotalPages(template.AlignRight(), template.FontSize(9))

Ambos aceitam opcoes padrao de texto para estilizacao.