元素

文本

最基本的元素。添加带可选样式的文本:

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

文本选项

选项说明
FontSize(size)字号(单位:点,默认:12)
Bold()粗体
Italic()斜体
FontFamily(name)使用已注册的字体
TextColor(color)前景色
BgColor(color)背景色
AlignLeft()左对齐(默认)
AlignCenter()居中对齐
AlignRight()右对齐
Underline()下划线装饰
Strikethrough()删除线装饰
LetterSpacing(pts)字符间额外间距
TextIndent(value)首行缩进

富文本

使用 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             │
└─────────────────────────────────────────────┘

表格

带表头和数据行的表格:

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

带样式的表格

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   │ ← 深蓝底白字
├─────────────┼────────────┼─────┼───────────┼──────────┤
│  Laptop Pro │ Electronics│  2  │ $1,299.00 │$2,598.00 │ ← 白色背景
│  Wireless.. │ 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 │ ← 灰色斑马纹
└─────────────┴────────────┴─────┴───────────┴──────────┘

表格选项

选项说明
ColumnWidths(widths...)列宽百分比(必须加起来等于 100)
ColumnAlign(aligns...) Since v1.0.10 按列设置水平对齐:AlignLeftAlignCenterAlignRight(同时应用于表头与正文)
TableHeaderStyle(opts...)表头行的样式
TableStripe(color)交替行背景色
TableCellVAlign(align)垂直对齐:VAlignTopVAlignMiddleVAlignBottom
WithTableBorder(spec)表格外框边框
WithTableCellBorder(spec)给每个表头与正文单元格绘制相同边框(Excel 风格的网格线)
WithTableBorderCollapse(b)合并相邻单元格的边框
WithTableBackground(color)填充表格外框背景

边框与背景

Since v1.0.7

可以添加外框、单元格网格线或背景填充。用 template.Border(...) 构建 BorderSpec,再通过 WithTableBorder(外框)或 WithTableCellBorder(每个单元格)应用:

outer := template.Border(
    template.BorderWidth(document.Pt(1)),
    template.BorderColor(pdf.RGBHex(0x1A237E)),
)
grid := template.Border(
    template.BorderWidth(document.Pt(0.5)),
    template.BorderColor(pdf.Gray(0.5)),
)

// 仅外框
c.Table(header, rows, template.WithTableBorder(outer))

// 给每个单元格添加 Excel 风格网格线
c.Table(header, rows, template.WithTableCellBorder(grid))

// 外框 + 网格 + 背景填充
c.Table(header, rows,
    template.WithTableBorder(outer),
    template.WithTableCellBorder(grid),
    template.WithTableBackground(pdf.RGBHex(0xFAFAFA)),
)

// 虚线网格
dashed := template.Border(
    template.BorderWidth(document.Pt(0.75)),
    template.BorderColor(pdf.RGBHex(0x0D47A1)),
    template.BorderLine(document.BorderDashed),
)
c.Table(header, rows, template.WithTableCellBorder(dashed))

完整的 BorderSpec 构建器参考请见 边框

表格垂直对齐

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),
)

表格列对齐

Since v1.0.10

按列设置水平对齐 — 典型用例是将数值或金额列右对齐。每个参数应用于相同索引的列,同时影响表头和正文。未指定的列默认左对齐。

c.Table(
    []string{"商品", "数量", "价格"},
    [][]string{
        {"苹果",   "3",   "¥1.50"},
        {"香蕉",   "12",  "¥0.30"},
        {"樱桃",   "120", "¥5.00"},
    },
    template.ColumnAlign(
        document.AlignLeft,   // 商品
        document.AlignRight,  // 数量
        document.AlignRight,  // 价格
    ),
)

图片

添加 JPEG 或 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)))

图片选项

选项说明
FitWidth(value)缩放到指定宽度
FitHeight(value)缩放到指定高度
WithFitMode(mode)适配模式:FitContainFitCoverFitStretchFitOriginal
WithAlign(align)水平对齐:AlignLeftAlignCenterAlignRight
MinDisplayWidth(v)当被缩小到该宽度以下时溢出到下一页
MinDisplayHeight(v)当被缩小到该高度以下时溢出到下一页
WithImageBorder(spec)在图片周围绘制边框
WithImageBackground(color)填充图片背景(适用于透明 PNG)

图片适配模式

// 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))

图片对齐

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

边框与背景

Since v1.0.7

为图片添加边框并填充背景(适用于透明 PNG):

c.Image(pngData,
    template.FitWidth(document.Mm(60)),
    template.WithImageBorder(template.Border(
        template.BorderWidth(document.Pt(2)),
        template.BorderColor(pdf.RGBHex(0xE53935)),
    )),
    template.WithImageBackground(pdf.RGBHex(0xFFF8E1)),
)

完整的 BorderSpec 构建器参考请见 边框

盒子

Since v1.0.7

将任意列内容包装在带有边框、填充与内边距的矩形容器中。适用于提示框、注意事项以及相关元素的分组:

c.Box(func(c *template.ColBuilder) {
    c.Text("盒子内部", template.Bold())
    c.Text("两行正文示例。")
},
    template.WithBoxBorder(template.Border(
        template.BorderWidth(document.Pt(1)),
        template.BorderColor(pdf.RGBHex(0x1A237E)),
    )),
    template.WithBoxBackground(pdf.RGBHex(0xE8EAF6)),
    template.WithBoxPadding(document.UniformEdges(document.Mm(4))),
)

盒子选项

选项说明
WithBoxBorder(spec)盒子周围的边框
WithBoxBackground(color)背景色
WithBoxPadding(edges)内边距
WithBoxMargin(edges)外边距
WithBoxWidth(value)显式宽度
WithBoxHeight(value)显式高度

边框

Since v1.0.7

template.Border(...) 构建一个可复用的 BorderSpec,可用于表格(WithTableBorder / WithTableCellBorder)、图片(WithImageBorder)、盒子(WithBoxBorder)以及文本(WithTextBorder):

spec := template.Border(
    template.BorderWidth(document.Pt(1)),       // 四边均匀
    template.BorderColor(pdf.RGBHex(0x1A237E)),
    template.BorderLine(document.BorderSolid),  // BorderSolid | BorderDashed | BorderDotted
)

未指定宽度时的默认值为 1pt 黑色实线

边框辅助函数

选项说明
Border(opts...)构建 BorderSpec
BorderWidth(v)四边均匀的宽度
BorderWidths(t, r, b, l)按 CSS 顺序(top, right, bottom, left)设置每边宽度
BorderColor(c)边框颜色
BorderLine(style)线条样式:BorderSolidBorderDashedBorderDottedBorderNone

列表

无序列表

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                │
└─────────────────────────────────────────────┘

有序列表

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                   │
└─────────────────────────────────────────────┘

列表选项

选项说明
ListIndent(value)左侧缩进

分割线

带可选颜色和粗细的水平分割线:

// 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)    │
└─────────────────────────────────────────────┘

分割线选项

选项说明
LineColor(color)线条颜色
LineThickness(value)线条粗细

间距

在元素之间添加垂直空间:

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                               │
└─────────────────────────────────────────────┘

二维码

从文本或 URL 生成二维码:

// 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)))

不同尺寸的二维码

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  │     │
│  └──┘         │  └────┘       │  │      │     │
│               │               │  └──────┘     │
└───────────────┴───────────────┴───────────────┘

纠错级别

级别恢复能力最佳适用
qrcode.LevelL~7%干净的环境
qrcode.LevelM~15%通用场景(默认)
qrcode.LevelQ~25%工业用途
qrcode.LevelH~30%恶劣环境
import "github.com/gpdf-dev/gpdf/qrcode"

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

二维码选项

选项说明
QRSize(value)显示尺寸(宽度 = 高度)
QRMinSize(value)最小显示尺寸 — 低于此值时溢出到下一页
QRErrorCorrection(level)纠错级别
QRScale(s)每个 QR 模块的像素数

最小尺寸

Since v1.0.6

QRMinSize 可防止布局将二维码缩小到配置的最小值以下。当当前页面剩余空间会导致二维码低于该尺寸时,二维码将被推到下一页,而不是以无法扫描的尺寸渲染。

c.QRCode("https://gpdf.dev",
    template.QRSize(document.Mm(30)),
    template.QRMinSize(document.Mm(20)))

条形码

生成 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")

列中的条形码

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            │
└────────────────────────┴────────────────────────┘

条形码选项

选项说明
BarcodeWidth(value)显示宽度
BarcodeHeight(value)显示高度
BarcodeFormat(format)条形码格式(默认:Code 128)

绝对定位

在页面的精确 XY 坐标处放置元素,不受正常网格流影响。适用于水印、印章、Logo 和叠加层。

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)               │   │
│  │   └──┘                                   │   │
│  └──────────────────────────────────────────┘   │
└─────────────────────────────────────────────────┘

坐标原点

原点说明默认
内容区域XY 相对于内容区域左上角(边距内)
页面XY 相对于页面左上角(忽略边距)

绝对定位选项

选项说明
AbsoluteWidth(value)绝对定位块的显式宽度
AbsoluteHeight(value)绝对定位块的显式高度
AbsoluteOriginPage()使用页面角作为原点而非内容区域

页码 / 总页数

在页眉或页脚中实现自动页码:

// 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))

两者都接受标准文本选项进行样式设置。